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