typing: add `ARangeExpr::init_callsite` and use it everywhere
[nit.git] / src / rapid_type_analysis.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2012 Jean Privat <jean@pryen.org>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17
18 # Rapid type analysis on the AST
19 #
20 # Rapid type analysis is an analyse that aproximates the set of live classes
21 # and the set of live methods starting from the entry point of the program.
22 # These two sets are interdependant and computed together.
23 # It is quite efficient but the type set is global and pollutes each call site.
24 module rapid_type_analysis
25
26 import model
27 import modelbuilder
28 import typing
29 import auto_super_init
30
31 import csv # for live_types_to_csv
32 import ordered_tree # for live_methods_to_tree
33
34 redef class ModelBuilder
35 fun do_rapid_type_analysis(mainmodule: MModule): RapidTypeAnalysis
36 do
37 var analysis = new RapidTypeAnalysis(self, mainmodule)
38 analysis.run_analysis
39 return analysis
40 end
41 end
42
43 # RapidTypeAnalysis looks for alive rapid types in application.
44 # The entry point of the analysis is the mainmodule of the application.
45 class RapidTypeAnalysis
46 # The modelbuilder used to get the AST.
47 var modelbuilder: ModelBuilder
48
49 # The main module of the analysis.
50 # Used to perform types operations.
51 var mainmodule: MModule
52
53 # The pool to live types.
54 # During the analysis, new types are added and combined with
55 # live_methods to determine new methoddefs to visit
56 var live_types = new HashSet[MClassType]
57
58 # The pool of undesolved live types
59 # They are globally resolved at the end of the analaysis
60 var live_open_types = new HashSet[MClassType]
61
62 # Live (instantiated) classes.
63 var live_classes = new HashSet[MClass]
64
65 # The pool of types used to perform type checks (isa and as).
66 var live_cast_types = new HashSet[MType]
67
68 # The pool of undesolved types used to perform type checks (isa and as).
69 # They are globally resolved at the end of the analaysis
70 var live_open_cast_types = new HashSet[MType]
71
72 # Live method definitions.
73 var live_methoddefs = new HashSet[MMethodDef]
74
75 # Live methods.
76 var live_methods = new HashSet[MMethod]
77
78 # Live call-to-super.
79 var live_super_sends = new HashSet[MMethodDef]
80
81 # Return a ready-to-save CSV document objet that agregates informations about live types.
82 # Each discovered type is listed in a line, with its status: resolution, liveness, cast-liveness.
83 # Note: types are listed in an alphanumeric order to improve human reading.
84 fun live_types_to_csv: CSVDocument
85 do
86 # Gather all kind of type
87 var typeset = new HashSet[MType]
88 typeset.add_all(live_types)
89 typeset.add_all(live_open_types)
90 typeset.add_all(live_cast_types)
91 typeset.add_all(live_open_cast_types)
92 var types = typeset.to_a
93 (new CachedAlphaComparator).sort(types)
94 var res = new CSVDocument
95 res.header = ["Type", "Resolution", "Liveness", "Cast-liveness"]
96 for t in types do
97 var reso
98 if t.need_anchor then reso = "OPEN " else reso = "CLOSED"
99 var live
100 if t isa MClassType and (live_types.has(t) or live_open_types.has(t)) then live = "LIVE" else live = "DEAD"
101 var cast
102 if live_cast_types.has(t) or live_open_cast_types.has(t) then cast = "CAST LIVE" else cast = "CAST DEAD"
103 res.add_line(t, reso, live, cast)
104 end
105 return res
106 end
107
108 # Return a ready-to-save OrderedTree object that agregates infomration about live methods.
109 # Note: methods are listed in an alphanumeric order to improve human reading.
110 fun live_methods_to_tree: OrderedTree[Object]
111 do
112 var tree = new OrderedTree[Object]
113 for x in live_methods do
114 var xn = x.full_name
115 tree.add(null, xn)
116 for z in x.mpropdefs do
117 var zn = z.to_s
118 if live_methoddefs.has(z) then
119 tree.add(xn, zn)
120 if live_super_sends.has(z) then
121 tree.add(zn, zn + "(super)")
122 end
123 else if live_super_sends.has(z) then
124 tree.add(xn, zn + "(super)")
125 end
126 end
127 end
128 tree.sort_with(alpha_comparator)
129 return tree
130 end
131
132 # Methods that are are still candidate to the try_send
133 private var totry_methods = new HashSet[MMethod]
134
135 # The method definitions that remain to visit
136 private var todo = new List[MMethodDef]
137
138 private fun force_alive(classname: String)
139 do
140 var classes = self.modelbuilder.model.get_mclasses_by_name(classname)
141 if classes != null then for c in classes do self.add_new(c.mclass_type, c.mclass_type)
142 end
143
144 # Run the analysis until all visitable method definitions are visited.
145 fun run_analysis
146 do
147 var maintype = mainmodule.sys_type
148 if maintype == null then return # No entry point
149 add_new(maintype, maintype)
150 var initprop = mainmodule.try_get_primitive_method("init", maintype.mclass)
151 if initprop != null then
152 add_send(maintype, initprop)
153 end
154 var mainprop = mainmodule.try_get_primitive_method("main", maintype.mclass)
155 if mainprop != null then
156 add_send(maintype, mainprop)
157 end
158
159 # Force primitive types
160 force_alive("Bool")
161 force_alive("Int")
162 force_alive("Float")
163 force_alive("Char")
164
165 while not todo.is_empty do
166 var mmethoddef = todo.shift
167 #print "# visit {mmethoddef}"
168 var v = new RapidTypeVisitor(self, mmethoddef.mclassdef.bound_mtype, mmethoddef)
169
170 var vararg_rank = mmethoddef.msignature.vararg_rank
171 if vararg_rank > -1 then
172 var node = self.modelbuilder.mpropdef2npropdef[mmethoddef]
173 var elttype = mmethoddef.msignature.mparameters[vararg_rank].mtype
174 #elttype = elttype.anchor_to(self.mainmodule, v.receiver)
175 var vararg = self.mainmodule.get_primitive_class("Array").get_mtype([elttype])
176 v.add_type(vararg)
177 var native = self.mainmodule.get_primitive_class("NativeArray").get_mtype([elttype])
178 v.add_type(native)
179 v.add_monomorphic_send(vararg, self.modelbuilder.force_get_primitive_method(node, "with_native", vararg.mclass, self.mainmodule))
180 end
181
182
183 for i in [0..mmethoddef.msignature.arity[ do
184 var origtype = mmethoddef.mproperty.intro.msignature.mparameters[i].mtype
185 if not origtype.need_anchor then continue # skip non covariant stuff
186 var paramtype = mmethoddef.msignature.mparameters[i].mtype
187 #paramtype = v.cleanup_type(paramtype).as(not null)
188 add_cast(paramtype)
189 end
190
191 if not modelbuilder.mpropdef2npropdef.has_key(mmethoddef) then
192 # It is an init for a class?
193 if mmethoddef.mproperty.name == "init" then
194 var nclassdef = self.modelbuilder.mclassdef2nclassdef[mmethoddef.mclassdef]
195 var super_inits = nclassdef.super_inits
196 if super_inits != null then
197 #assert args.length == 1
198 for su in super_inits do
199 v.add_monomorphic_send(v.receiver, su)
200 end
201 end
202
203 else
204 abort
205 end
206 continue
207 end
208
209 var npropdef = modelbuilder.mpropdef2npropdef[mmethoddef]
210
211 if npropdef isa AConcreteMethPropdef then
212 var auto_super_inits = npropdef.auto_super_inits
213 if auto_super_inits != null then
214 for auto_super_init in auto_super_inits do
215 v.add_callsite(auto_super_init)
216 end
217 end
218 else if npropdef isa AInternMethPropdef or
219 (npropdef isa AExternMethPropdef and npropdef.n_extern != null) then
220 # UGLY: We force the "instantation" of the concrete return type if any
221 var ret = mmethoddef.msignature.return_mtype
222 if ret != null and ret isa MClassType and ret.mclass.kind != abstract_kind and ret.mclass.kind != interface_kind then
223 v.add_type(ret)
224 end
225 else if npropdef isa AExternMethPropdef then
226 var nclassdef = npropdef.parent.as(AClassdef)
227 v.enter_visit(npropdef)
228 else if npropdef isa AExternInitPropdef then
229 v.add_type(v.receiver)
230 else
231
232 end
233
234 v.enter_visit(npropdef)
235 end
236
237 #print "MMethod {live_methods.length}: {live_methods.join(", ")}"
238 #print "MMethodDef {live_methoddefs.length}: {live_methoddefs.join(", ")}"
239
240 #print "open MType {live_open_types.length}: {live_open_types.join(", ")}"
241 var todo_types = new List[MClassType]
242 todo_types.add_all(live_types)
243 while not todo_types.is_empty do
244 var t = todo_types.shift
245 for ot in live_open_types do
246 #print "{ot}/{t} ?"
247 if not ot.can_resolve_for(t, t, mainmodule) then continue
248 var rt = ot.anchor_to(mainmodule, t)
249 if live_types.has(rt) then continue
250 #print "{ot}/{t} -> {rt}"
251 live_types.add(rt)
252 todo_types.add(rt)
253 check_depth(rt)
254 end
255 end
256 #print "MType {live_types.length}: {live_types.join(", ")}"
257
258 #print "open cast MType {live_open_cast_types.length}: {live_open_cast_types.join(", ")}"
259 for ot in live_open_cast_types do
260 #print "live_open_cast_type: {ot}"
261 for t in live_types do
262 if not ot.can_resolve_for(t, t, mainmodule) then continue
263 var rt = ot.anchor_to(mainmodule, t)
264 live_cast_types.add(rt)
265 #print " {ot}/{t} -> {rt}"
266 end
267 end
268 #print "cast MType {live_cast_types.length}: {live_cast_types.join(", ")}"
269 end
270
271 private fun check_depth(mtype: MClassType)
272 do
273 var d = mtype.length
274 if d > 255 then
275 self.modelbuilder.toolcontext.fatal_error(null, "Fatal error: limitation in the rapidtype analysis engine: a type depth of {d} is too important, the problematic type is {mtype}.")
276 end
277 end
278
279 fun add_new(recv: MClassType, mtype: MClassType)
280 do
281 assert not recv.need_anchor
282 if mtype.need_anchor then
283 if live_open_types.has(mtype) then return
284 live_open_types.add(mtype)
285 else
286 if live_types.has(mtype) then return
287 live_types.add(mtype)
288 end
289
290 var mclass = mtype.mclass
291 if live_classes.has(mclass) then return
292 live_classes.add(mclass)
293
294 for p in totry_methods do try_send(mtype, p)
295 for p in live_super_sends do try_super_send(mtype, p)
296
297 var bound_mtype = mtype.anchor_to(mainmodule, recv)
298 for cd in bound_mtype.collect_mclassdefs(mainmodule)
299 do
300 if not self.modelbuilder.mclassdef2nclassdef.has_key(cd) then continue
301 var nclassdef = self.modelbuilder.mclassdef2nclassdef[cd]
302 for npropdef in nclassdef.n_propdefs do
303 if not npropdef isa AAttrPropdef then continue
304 var nexpr = npropdef.n_expr
305 if nexpr == null then continue
306 var mpropdef = npropdef.mpropdef.as(not null)
307 var v = new RapidTypeVisitor(self, bound_mtype, mpropdef)
308 v.enter_visit(nexpr)
309 end
310 end
311
312 end
313
314 fun add_cast(mtype: MType)
315 do
316 if mtype.need_anchor then
317 live_open_cast_types.add(mtype)
318 else
319 live_cast_types.add(mtype)
320 end
321 end
322
323 fun try_send(recv: MClassType, mproperty: MMethod)
324 do
325 recv = recv.mclass.intro.bound_mtype
326 if not recv.has_mproperty(mainmodule, mproperty) then return
327 var d = mproperty.lookup_first_definition(mainmodule, recv)
328 add_call(d)
329 end
330
331 fun add_call(mpropdef: MMethodDef)
332 do
333 if live_methoddefs.has(mpropdef) then return
334 live_methoddefs.add(mpropdef)
335 todo.add(mpropdef)
336
337 var mproperty = mpropdef.mproperty
338 if mproperty.mpropdefs.length <= 1 then return
339 # If all definitions of a method are live, we can remove the definition of the totry set
340 for d in mproperty.mpropdefs do
341 if d.is_abstract then continue
342 if not live_methoddefs.has(d) then return
343 end
344 #print "full property: {mpropdef.mproperty} for {mpropdef.mproperty.mpropdefs.length} definitions"
345 totry_methods.remove(mpropdef.mproperty)
346 end
347
348 fun add_send(recv: MType, mproperty: MMethod)
349 do
350 if live_methods.has(mproperty) then return
351 #print "new prop: {mproperty}"
352 live_methods.add(mproperty)
353 if mproperty.mpropdefs.length == 1 then
354 # If there is only one definition, just add the definition and do not try again the property
355 var d = mproperty.mpropdefs.first
356 add_call(d)
357 return
358 end
359 # Else, the property is potentially called with various reciever
360 # So just try the methods with existing receiver and register it for future receiver
361 totry_methods.add(mproperty)
362 for c in live_classes do
363 try_send(c.intro.bound_mtype, mproperty)
364 end
365 end
366
367 fun try_super_send(recv: MClassType, mpropdef: MMethodDef)
368 do
369 recv = recv.mclass.intro.bound_mtype
370 if not recv.collect_mclassdefs(mainmodule).has(mpropdef.mclassdef) then return
371 var d = mpropdef.lookup_next_definition(mainmodule, recv)
372 add_call(d)
373 end
374
375 fun add_super_send(recv: MType, mpropdef: MMethodDef)
376 do
377 if live_super_sends.has(mpropdef) then return
378 #print "new super prop: {mpropdef}"
379 live_super_sends.add(mpropdef)
380 for t in live_types do
381 try_super_send(t, mpropdef)
382 end
383 end
384 end
385
386 class RapidTypeVisitor
387 super Visitor
388
389 var analysis: RapidTypeAnalysis
390 var receiver: MClassType
391 var mpropdef: MPropDef
392
393 init(analysis: RapidTypeAnalysis, receiver: MClassType, mpropdef: MPropDef)
394 do
395 self.analysis = analysis
396 self.receiver = receiver
397 self.mpropdef = mpropdef
398 assert not receiver.need_anchor
399 end
400
401 redef fun visit(n)
402 do
403 n.accept_rapid_type_visitor(self)
404 if n isa AExpr then
405 var implicit_cast_to = n.implicit_cast_to
406 if implicit_cast_to != null then self.add_cast_type(implicit_cast_to)
407 end
408
409 # RTA does not enter in AAnnotations
410 if not n isa AAnnotations then
411 n.visit_all(self)
412 end
413 end
414
415 fun cleanup_type(mtype: MType): nullable MClassType
416 do
417 mtype = mtype.anchor_to(self.analysis.mainmodule, self.receiver)
418 if mtype isa MNullType then return null
419 if mtype isa MNullableType then mtype = mtype.mtype
420 assert mtype isa MClassType
421 assert not mtype.need_anchor
422 return mtype
423 end
424
425 fun get_class(name: String): MClass
426 do
427 return analysis.mainmodule.get_primitive_class(name)
428 end
429
430 fun get_method(recv: MType, name: String): MMethod
431 do
432 var mtype = cleanup_type(recv)
433 assert mtype != null
434 return self.analysis.modelbuilder.force_get_primitive_method(self.current_node.as(not null), name, mtype.mclass, self.analysis.mainmodule)
435 end
436
437 fun add_type(mtype: MClassType) do analysis.add_new(receiver, mtype)
438
439 fun add_monomorphic_send(mtype: MType, mproperty: MMethod) do analysis.try_send(mtype.as(MClassType), mproperty)
440
441 fun add_send(mtype: MType, mproperty: MMethod) do analysis.add_send(mtype, mproperty)
442
443 fun add_cast_type(mtype: MType) do analysis.add_cast(mtype)
444
445 fun add_callsite(callsite: nullable CallSite) do if callsite != null then analysis.add_send(callsite.recv, callsite.mproperty)
446 end
447
448 ###
449
450 redef class ANode
451 private fun accept_rapid_type_visitor(v: RapidTypeVisitor)
452 do
453 end
454 end
455
456 redef class AIntExpr
457 redef fun accept_rapid_type_visitor(v)
458 do
459 v.add_type(self.mtype.as(MClassType))
460 end
461 end
462
463 redef class AFloatExpr
464 redef fun accept_rapid_type_visitor(v)
465 do
466 v.add_type(self.mtype.as(MClassType))
467 end
468 end
469
470 redef class ACharExpr
471 redef fun accept_rapid_type_visitor(v)
472 do
473 v.add_type(self.mtype.as(MClassType))
474 end
475 end
476
477 redef class AArrayExpr
478 redef fun accept_rapid_type_visitor(v)
479 do
480 var mtype = self.mtype.as(MClassType)
481 v.add_type(mtype)
482 var native = v.analysis.mainmodule.get_primitive_class("NativeArray").get_mtype([mtype.arguments.first])
483 v.add_type(native)
484 mtype = v.cleanup_type(mtype).as(not null)
485 var prop = v.get_method(mtype, "with_native")
486 v.add_monomorphic_send(mtype, prop)
487 end
488 end
489
490 redef class AStringFormExpr
491 redef fun accept_rapid_type_visitor(v)
492 do
493 var native = v.get_class("NativeString").mclass_type
494 v.add_type(native)
495 var prop = v.get_method(native, "to_s_with_length")
496 v.add_monomorphic_send(native, prop)
497 end
498 end
499
500 redef class ASuperstringExpr
501 redef fun accept_rapid_type_visitor(v)
502 do
503 var arraytype = v.get_class("Array").get_mtype([v.get_class("Object").mclass_type])
504 v.add_type(arraytype)
505 v.add_type(v.get_class("NativeArray").get_mtype([v.get_class("Object").mclass_type]))
506 var prop = v.get_method(arraytype, "join")
507 v.add_monomorphic_send(arraytype, prop)
508 var prop2 = v.get_method(arraytype, "with_native")
509 v.add_monomorphic_send(arraytype, prop2)
510 end
511 end
512
513 redef class ACrangeExpr
514 redef fun accept_rapid_type_visitor(v)
515 do
516 var mtype = self.mtype.as(MClassType)
517 v.add_type(mtype)
518 v.add_callsite(init_callsite)
519 end
520 end
521
522 redef class AOrangeExpr
523 redef fun accept_rapid_type_visitor(v)
524 do
525 var mtype = self.mtype.as(MClassType)
526 v.add_type(mtype)
527 v.add_callsite(init_callsite)
528 end
529 end
530
531 redef class ATrueExpr
532 redef fun accept_rapid_type_visitor(v)
533 do
534 v.add_type(self.mtype.as(MClassType))
535 end
536 end
537
538 redef class AFalseExpr
539 redef fun accept_rapid_type_visitor(v)
540 do
541 v.add_type(self.mtype.as(MClassType))
542 end
543 end
544
545 redef class AIsaExpr
546 redef fun accept_rapid_type_visitor(v)
547 do
548 v.add_cast_type(self.cast_type.as(not null))
549 end
550 end
551
552 redef class AAsCastExpr
553 redef fun accept_rapid_type_visitor(v)
554 do
555 v.add_cast_type(self.mtype.as(not null))
556 end
557 end
558
559 redef class ASendExpr
560 redef fun accept_rapid_type_visitor(v)
561 do
562 v.add_callsite(callsite)
563 end
564 end
565
566
567 redef class ASendReassignFormExpr
568 redef fun accept_rapid_type_visitor(v)
569 do
570 v.add_callsite(callsite)
571 v.add_callsite(reassign_callsite)
572 v.add_callsite(write_callsite)
573 end
574 end
575
576 redef class AVarReassignExpr
577 redef fun accept_rapid_type_visitor(v)
578 do
579 v.add_callsite(reassign_callsite)
580 end
581 end
582
583 redef class AAttrReassignExpr
584 redef fun accept_rapid_type_visitor(v)
585 do
586 v.add_callsite(reassign_callsite)
587 end
588 end
589
590 redef class ASuperExpr
591 redef fun accept_rapid_type_visitor(v)
592 do
593 var callsite = self.callsite
594 if callsite != null then
595 v.add_callsite(callsite)
596 return
597 end
598
599 v.analysis.add_super_send(v.receiver, mpropdef.as(not null))
600 end
601 end
602
603 redef class AForExpr
604 redef fun accept_rapid_type_visitor(v)
605 do
606 v.add_callsite(self.method_iterator)
607 v.add_callsite(self.method_is_ok)
608 if self.variables.length == 1 then
609 v.add_callsite(self.method_item)
610 else if self.variables.length == 2 then
611 v.add_callsite(self.method_key)
612 v.add_callsite(self.method_item)
613 else
614 abort
615 end
616 v.add_callsite(self.method_next)
617 end
618 end
619
620 redef class ANewExpr
621 redef fun accept_rapid_type_visitor(v)
622 do
623 var mtype = self.mtype.as(MClassType)
624 v.add_type(mtype)
625 v.add_callsite(callsite)
626 end
627 end