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