model: rta uses its visitor only to visit FFI extern methods
[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 redef class ModelBuilder
32 fun do_rapid_type_analysis(mainmodule: MModule): RapidTypeAnalysis
33 do
34 var analysis = new RapidTypeAnalysis(self, mainmodule)
35 analysis.run_analysis
36 return analysis
37 end
38 end
39
40 # RapidTypeAnalysis looks for alive rapid types in application.
41 # The entry point of the analysis is the mainmodule of the application.
42 class RapidTypeAnalysis
43 # The modelbuilder used to get the AST.
44 var modelbuilder: ModelBuilder
45
46 # The main module of the analysis.
47 # Used to perform types operations.
48 var mainmodule: MModule
49
50 # The pool to live types.
51 # During the analysis, new types are added and combined with
52 # live_methods to determine new methoddefs to visit
53 var live_types = new HashSet[MClassType]
54
55 # The pool of undesolved live types
56 # They are globally resolved at the end of the analaysis
57 var live_open_types = new HashSet[MClassType]
58
59 # Live (instantiated) classes.
60 var live_classes = new HashSet[MClass]
61
62 # The pool of types used to perform type checks (isa and as).
63 var live_cast_types = new HashSet[MClassType]
64
65 # The pool of undesolved types used to perform type checks (isa and as).
66 # They are globally resolved at the end of the analaysis
67 var live_open_cast_types = new HashSet[MType]
68
69 # Live method definitions.
70 var live_methoddefs = new HashSet[MMethodDef]
71
72 # Live methods.
73 var live_methods = new HashSet[MMethod]
74
75 # Live call-to-super.
76 var live_super_sends = new HashSet[MMethodDef]
77
78 # Methods that are are still candidate to the try_send
79 private var totry_methods = new HashSet[MMethod]
80
81 # The method definitions that remain to visit
82 private var todo = new List[MMethodDef]
83
84 # Run the analysis until all visitable method definitions are visited.
85 fun run_analysis
86 do
87 var maintype = mainmodule.sys_type
88 if maintype == null then return # No entry point
89 add_new(maintype, maintype)
90 var initprop = mainmodule.try_get_primitive_method("init", maintype.mclass)
91 if initprop != null then
92 add_send(maintype, initprop)
93 end
94 var mainprop = mainmodule.try_get_primitive_method("main", maintype.mclass)
95 if mainprop != null then
96 add_send(maintype, mainprop)
97 end
98
99 # Force Bool
100 var classes = self.modelbuilder.model.get_mclasses_by_name("Bool")
101 if classes != null then for c in classes do self.add_new(c.mclass_type, c.mclass_type)
102
103 while not todo.is_empty do
104 var mmethoddef = todo.shift
105 #print "# visit {mmethoddef}"
106 var v = new RapidTypeVisitor(self, mmethoddef.mclassdef.bound_mtype, mmethoddef)
107
108 var vararg_rank = mmethoddef.msignature.vararg_rank
109 if vararg_rank > -1 then
110 var node = self.modelbuilder.mpropdef2npropdef[mmethoddef]
111 var elttype = mmethoddef.msignature.mparameters[vararg_rank].mtype
112 #elttype = elttype.anchor_to(self.mainmodule, v.receiver)
113 var vararg = self.mainmodule.get_primitive_class("Array").get_mtype([elttype])
114 v.add_type(vararg)
115 var native = self.mainmodule.get_primitive_class("NativeArray").get_mtype([elttype])
116 v.add_type(native)
117 v.add_monomorphic_send(vararg, self.modelbuilder.force_get_primitive_method(node, "with_native", vararg.mclass, self.mainmodule))
118 end
119
120
121 for i in [0..mmethoddef.msignature.arity[ do
122 var origtype = mmethoddef.mproperty.intro.msignature.mparameters[i].mtype
123 if not origtype.need_anchor then continue # skip non covariant stuff
124 var paramtype = mmethoddef.msignature.mparameters[i].mtype
125 #paramtype = v.cleanup_type(paramtype).as(not null)
126 add_cast(paramtype)
127 end
128
129 if not modelbuilder.mpropdef2npropdef.has_key(mmethoddef) then
130 # It is an init for a class?
131 if mmethoddef.mproperty.name == "init" then
132 var nclassdef = self.modelbuilder.mclassdef2nclassdef[mmethoddef.mclassdef]
133 var super_inits = nclassdef.super_inits
134 if super_inits != null then
135 #assert args.length == 1
136 for su in super_inits do
137 v.add_monomorphic_send(v.receiver, su)
138 end
139 end
140
141 else
142 abort
143 end
144 continue
145 end
146
147 var npropdef = modelbuilder.mpropdef2npropdef[mmethoddef]
148
149 if npropdef isa AConcreteMethPropdef then
150 var auto_super_inits = npropdef.auto_super_inits
151 if auto_super_inits != null then
152 for auto_super_init in auto_super_inits do
153 v.add_monomorphic_send(v.receiver, auto_super_init)
154 end
155 end
156 else if npropdef isa AInternMethPropdef or
157 (npropdef isa AExternMethPropdef and npropdef.n_extern != null) then
158 # UGLY: We force the "instantation" of the concrete return type if any
159 var ret = mmethoddef.msignature.return_mtype
160 if ret != null and ret isa MClassType and ret.mclass.kind != abstract_kind and ret.mclass.kind != interface_kind then
161 v.add_type(ret)
162 end
163 else if npropdef isa AExternMethPropdef then
164 var nclassdef = npropdef.parent.as(AClassdef)
165 v.enter_visit(npropdef)
166 else if npropdef isa AExternInitPropdef then
167 v.add_type(v.receiver)
168 else
169
170 end
171
172 v.enter_visit(npropdef)
173 end
174
175 #print "MMethod {live_methods.length}: {live_methods.join(", ")}"
176 #print "MMethodDef {live_methoddefs.length}: {live_methoddefs.join(", ")}"
177
178 #print "open MType {live_open_types.length}: {live_open_types.join(", ")}"
179 var todo_types = new List[MClassType]
180 todo_types.add_all(live_types)
181 while not todo_types.is_empty do
182 var t = todo_types.shift
183 for ot in live_open_types do
184 #print "{ot}/{t} ?"
185 if not ot.can_resolve_for(t, t, mainmodule) then continue
186 var rt = ot.anchor_to(mainmodule, t)
187 if live_types.has(rt) then continue
188 #print "{ot}/{t} -> {rt}"
189 live_types.add(rt)
190 todo_types.add(rt)
191 check_depth(rt)
192 end
193 end
194 #print "MType {live_types.length}: {live_types.join(", ")}"
195
196 #print "open cast MType {live_open_cast_types.length}: {live_open_cast_types.join(", ")}"
197 for ot in live_open_cast_types do
198 #print "live_open_cast_type: {ot}"
199 for t in live_types do
200 if not ot.can_resolve_for(t, t, mainmodule) then continue
201 var rt = ot.anchor_to(mainmodule, t)
202 if rt isa MNullableType then rt = rt.mtype
203 assert rt isa MClassType
204 live_cast_types.add(rt)
205 #print " {ot}/{t} -> {rt}"
206 end
207 end
208 #print "cast MType {live_cast_types.length}: {live_cast_types.join(", ")}"
209 end
210
211 private fun check_depth(mtype: MClassType)
212 do
213 var d = mtype.length
214 if d > 255 then
215 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}.")
216 end
217 end
218
219 fun add_new(recv: MClassType, mtype: MClassType)
220 do
221 assert not recv.need_anchor
222 if mtype.need_anchor then
223 if live_open_types.has(mtype) then return
224 live_open_types.add(mtype)
225 else
226 if live_types.has(mtype) then return
227 live_types.add(mtype)
228 end
229
230 var mclass = mtype.mclass
231 if live_classes.has(mclass) then return
232 live_classes.add(mclass)
233
234 for p in totry_methods do try_send(mtype, p)
235 for p in live_super_sends do try_super_send(mtype, p)
236
237 var bound_mtype = mtype.anchor_to(mainmodule, recv)
238 for cd in bound_mtype.collect_mclassdefs(mainmodule)
239 do
240 if not self.modelbuilder.mclassdef2nclassdef.has_key(cd) then continue
241 var nclassdef = self.modelbuilder.mclassdef2nclassdef[cd]
242 for npropdef in nclassdef.n_propdefs do
243 if not npropdef isa AAttrPropdef then continue
244 var nexpr = npropdef.n_expr
245 if nexpr == null then continue
246 var mpropdef = npropdef.mpropdef.as(not null)
247 var v = new RapidTypeVisitor(self, bound_mtype, mpropdef)
248 v.enter_visit(nexpr)
249 end
250 end
251
252 end
253
254 fun add_cast(mtype: MType)
255 do
256 if mtype isa MNullableType then mtype = mtype.mtype
257 if mtype.need_anchor then
258 live_open_cast_types.add(mtype)
259 else
260 assert mtype isa MClassType
261 live_cast_types.add(mtype)
262 end
263 end
264
265 fun try_send(recv: MClassType, mproperty: MMethod)
266 do
267 recv = recv.mclass.intro.bound_mtype
268 if not recv.has_mproperty(mainmodule, mproperty) then return
269 var d = mproperty.lookup_first_definition(mainmodule, recv)
270 add_call(d)
271 end
272
273 fun add_call(mpropdef: MMethodDef)
274 do
275 if live_methoddefs.has(mpropdef) then return
276 live_methoddefs.add(mpropdef)
277 todo.add(mpropdef)
278
279 var mproperty = mpropdef.mproperty
280 if mproperty.mpropdefs.length <= 1 then return
281 # If all definitions of a method are live, we can remove the definition of the totry set
282 for d in mproperty.mpropdefs do
283 if d.is_abstract then continue
284 if not live_methoddefs.has(d) then return
285 end
286 #print "full property: {mpropdef.mproperty} for {mpropdef.mproperty.mpropdefs.length} definitions"
287 totry_methods.remove(mpropdef.mproperty)
288 end
289
290 fun add_send(recv: MType, mproperty: MMethod)
291 do
292 if live_methods.has(mproperty) then return
293 #print "new prop: {mproperty}"
294 live_methods.add(mproperty)
295 if mproperty.mpropdefs.length == 1 then
296 # If there is only one definition, just add the definition and do not try again the property
297 var d = mproperty.mpropdefs.first
298 add_call(d)
299 return
300 end
301 # Else, the property is potentially called with various reciever
302 # So just try the methods with existing receiver and register it for future receiver
303 totry_methods.add(mproperty)
304 for c in live_classes do
305 try_send(c.intro.bound_mtype, mproperty)
306 end
307 end
308
309 fun try_super_send(recv: MClassType, mpropdef: MMethodDef)
310 do
311 recv = recv.mclass.intro.bound_mtype
312 if not recv.collect_mclassdefs(mainmodule).has(mpropdef.mclassdef) then return
313 var d = mpropdef.lookup_next_definition(mainmodule, recv)
314 add_call(d)
315 end
316
317 fun add_super_send(recv: MType, mpropdef: MMethodDef)
318 do
319 if live_super_sends.has(mpropdef) then return
320 #print "new super prop: {mpropdef}"
321 live_super_sends.add(mpropdef)
322 for t in live_types do
323 try_super_send(t, mpropdef)
324 end
325 end
326 end
327
328 class RapidTypeVisitor
329 super Visitor
330
331 var analysis: RapidTypeAnalysis
332 var receiver: MClassType
333 var mpropdef: MPropDef
334
335 init(analysis: RapidTypeAnalysis, receiver: MClassType, mpropdef: MPropDef)
336 do
337 self.analysis = analysis
338 self.receiver = receiver
339 self.mpropdef = mpropdef
340 assert not receiver.need_anchor
341 end
342
343 redef fun visit(n)
344 do
345 n.accept_rapid_type_visitor(self)
346 if n isa AExpr then
347 var implicit_cast_to = n.implicit_cast_to
348 if implicit_cast_to != null then self.add_cast_type(implicit_cast_to)
349 end
350
351 # RTA does not enter in AAnnotations
352 if not n isa AAnnotations then
353 n.visit_all(self)
354 end
355 end
356
357 fun cleanup_type(mtype: MType): nullable MClassType
358 do
359 mtype = mtype.anchor_to(self.analysis.mainmodule, self.receiver)
360 if mtype isa MNullType then return null
361 if mtype isa MNullableType then mtype = mtype.mtype
362 assert mtype isa MClassType
363 assert not mtype.need_anchor
364 return mtype
365 end
366
367 fun get_class(name: String): MClass
368 do
369 return analysis.mainmodule.get_primitive_class(name)
370 end
371
372 fun get_method(recv: MType, name: String): MMethod
373 do
374 var mtype = cleanup_type(recv)
375 assert mtype != null
376 return self.analysis.modelbuilder.force_get_primitive_method(self.current_node.as(not null), name, mtype.mclass, self.analysis.mainmodule)
377 end
378
379 fun add_type(mtype: MClassType) do analysis.add_new(receiver, mtype)
380
381 fun add_monomorphic_send(mtype: MType, mproperty: MMethod) do analysis.try_send(mtype.as(MClassType), mproperty)
382
383 fun add_send(mtype: MType, mproperty: MMethod) do analysis.add_send(mtype, mproperty)
384
385 fun add_cast_type(mtype: MType) do analysis.add_cast(mtype)
386 end
387
388 ###
389
390 redef class ANode
391 private fun accept_rapid_type_visitor(v: RapidTypeVisitor)
392 do
393 end
394 end
395
396 redef class AIntExpr
397 redef fun accept_rapid_type_visitor(v)
398 do
399 v.add_type(self.mtype.as(MClassType))
400 end
401 end
402
403 redef class AFloatExpr
404 redef fun accept_rapid_type_visitor(v)
405 do
406 v.add_type(self.mtype.as(MClassType))
407 end
408 end
409
410 redef class ACharExpr
411 redef fun accept_rapid_type_visitor(v)
412 do
413 v.add_type(self.mtype.as(MClassType))
414 end
415 end
416
417 redef class AArrayExpr
418 redef fun accept_rapid_type_visitor(v)
419 do
420 var mtype = self.mtype.as(MClassType)
421 v.add_type(mtype)
422 var native = v.analysis.mainmodule.get_primitive_class("NativeArray").get_mtype([mtype.arguments.first])
423 v.add_type(native)
424 mtype = v.cleanup_type(mtype).as(not null)
425 var prop = v.get_method(mtype, "with_native")
426 v.add_monomorphic_send(mtype, prop)
427 end
428 end
429
430 redef class AStringFormExpr
431 redef fun accept_rapid_type_visitor(v)
432 do
433 var native = v.get_class("NativeString").mclass_type
434 v.add_type(native)
435 var prop = v.get_method(native, "to_s_with_length")
436 v.add_monomorphic_send(native, prop)
437 end
438 end
439
440 redef class ASuperstringExpr
441 redef fun accept_rapid_type_visitor(v)
442 do
443 var arraytype = v.get_class("Array").get_mtype([v.get_class("Object").mclass_type])
444 v.add_type(arraytype)
445 v.add_type(v.get_class("NativeArray").get_mtype([v.get_class("Object").mclass_type]))
446 var prop = v.get_method(arraytype, "join")
447 v.add_monomorphic_send(arraytype, prop)
448 var prop2 = v.get_method(arraytype, "with_native")
449 v.add_monomorphic_send(arraytype, prop2)
450 end
451 end
452
453 redef class ACrangeExpr
454 redef fun accept_rapid_type_visitor(v)
455 do
456 var mtype = self.mtype.as(MClassType)
457 v.add_type(mtype)
458 var prop = v.get_method(mtype, "init")
459 v.add_monomorphic_send(mtype, prop)
460 end
461 end
462
463 redef class AOrangeExpr
464 redef fun accept_rapid_type_visitor(v)
465 do
466 var mtype = self.mtype.as(MClassType)
467 v.add_type(mtype)
468 var prop = v.get_method(mtype, "without_last")
469 v.add_monomorphic_send(mtype, prop)
470 end
471 end
472
473 redef class ATrueExpr
474 redef fun accept_rapid_type_visitor(v)
475 do
476 v.add_type(self.mtype.as(MClassType))
477 end
478 end
479
480 redef class AFalseExpr
481 redef fun accept_rapid_type_visitor(v)
482 do
483 v.add_type(self.mtype.as(MClassType))
484 end
485 end
486
487 redef class AIsaExpr
488 redef fun accept_rapid_type_visitor(v)
489 do
490 v.add_cast_type(self.cast_type.as(not null))
491 end
492 end
493
494 redef class AAsCastExpr
495 redef fun accept_rapid_type_visitor(v)
496 do
497 v.add_cast_type(self.mtype.as(not null))
498 end
499 end
500
501 redef class ASendExpr
502 redef fun accept_rapid_type_visitor(v)
503 do
504 var mproperty = self.mproperty.as(not null)
505 var recvtype = self.n_expr.mtype.as(not null)
506 v.add_send(recvtype, mproperty)
507 end
508 end
509
510
511 redef class ASendReassignFormExpr
512 redef fun accept_rapid_type_visitor(v)
513 do
514 v.add_send(self.read_type.as(not null), self.reassign_property.mproperty)
515 var mproperty = self.mproperty.as(not null)
516 var write_mproperty = self.write_mproperty.as(not null)
517 if n_expr isa ASelfExpr then
518 v.add_monomorphic_send(v.receiver, mproperty)
519 v.add_monomorphic_send(v.receiver, write_mproperty)
520 else
521 var recvtype = self.n_expr.mtype.as(not null)
522 v.add_send(recvtype, mproperty)
523 v.add_send(recvtype, write_mproperty)
524 end
525 end
526 end
527
528 redef class AVarReassignExpr
529 redef fun accept_rapid_type_visitor(v)
530 do
531 v.add_send(self.read_type.as(not null), self.reassign_property.mproperty)
532 end
533 end
534
535 redef class AAttrReassignExpr
536 redef fun accept_rapid_type_visitor(v)
537 do
538 v.add_send(self.read_type.as(not null), self.reassign_property.mproperty)
539 end
540 end
541
542 redef class ASuperExpr
543 redef fun accept_rapid_type_visitor(v)
544 do
545 var mproperty = self.mproperty
546 if mproperty != null then
547 v.add_monomorphic_send(v.receiver, mproperty)
548 return
549 end
550
551 v.analysis.add_super_send(v.receiver, v.mpropdef.as(MMethodDef))
552 end
553 end
554
555 redef class AForExpr
556 redef fun accept_rapid_type_visitor(v)
557 do
558 var recvtype = self.n_expr.mtype.as(not null)
559 var colltype = self.coltype.as(not null)
560 var itmeth = v.get_method(colltype, "iterator")
561 v.add_send(recvtype, itmeth)
562 var iteratortype = itmeth.intro.msignature.return_mtype.as(MClassType).mclass.intro.bound_mtype
563 var objtype = v.get_class("Object").mclass_type
564 v.add_send(objtype, v.get_method(iteratortype, "is_ok"))
565 if self.variables.length == 1 then
566 v.add_send(objtype, v.get_method(iteratortype, "item"))
567 else if self.variables.length == 2 then
568 v.add_send(objtype, v.get_method(iteratortype, "key"))
569 v.add_send(objtype, v.get_method(iteratortype, "item"))
570 else
571 abort
572 end
573 v.add_send(objtype, v.get_method(iteratortype, "next"))
574 end
575 end
576
577 redef class ANewExpr
578 redef fun accept_rapid_type_visitor(v)
579 do
580 var mtype = self.mtype.as(MClassType)
581 v.add_type(mtype)
582 var mproperty = self.mproperty.as(not null)
583 v.add_monomorphic_send(mtype, mproperty)
584 end
585 end