model: try_get_primitive_method asks for a MClass (and not a MType)
[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 v.add_monomorphic_send(vararg, self.modelbuilder.force_get_primitive_method(node, "with_native", vararg.mclass, self.mainmodule))
116 var native = self.mainmodule.get_primitive_class("NativeArray").get_mtype([elttype])
117 v.add_type(native)
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 npropdef isa AExternMethPropdef then
157 # UGLY: We force the "instantation" of the concrete return type if any
158 var ret = mmethoddef.msignature.return_mtype
159 if ret != null and ret isa MClassType and ret.mclass.kind != abstract_kind and ret.mclass.kind != interface_kind then
160 v.add_type(ret)
161 end
162 else if npropdef isa AExternInitPropdef then
163 v.add_type(v.receiver)
164 else
165
166 end
167
168 v.enter_visit(npropdef)
169 end
170
171 #print "MMethod {live_methods.length}: {live_methods.join(", ")}"
172 #print "MMethodDef {live_methoddefs.length}: {live_methoddefs.join(", ")}"
173
174 #print "open MType {live_open_types.length}: {live_open_types.join(", ")}"
175 var todo_types = new List[MClassType]
176 todo_types.add_all(live_types)
177 while not todo_types.is_empty do
178 var t = todo_types.shift
179 for ot in live_open_types do
180 #print "{ot}/{t} ?"
181 if not ot.can_resolve_for(t, t, mainmodule) then continue
182 var rt = ot.anchor_to(mainmodule, t)
183 if live_types.has(rt) then continue
184 #print "{ot}/{t} -> {rt}"
185 live_types.add(rt)
186 todo_types.add(rt)
187 check_depth(rt)
188 end
189 end
190 #print "MType {live_types.length}: {live_types.join(", ")}"
191
192 #print "open cast MType {live_open_cast_types.length}: {live_open_cast_types.join(", ")}"
193 for ot in live_open_cast_types do
194 #print "live_open_cast_type: {ot}"
195 for t in live_types do
196 if not ot.can_resolve_for(t, t, mainmodule) then continue
197 var rt = ot.anchor_to(mainmodule, t)
198 if rt isa MNullableType then rt = rt.mtype
199 assert rt isa MClassType
200 live_cast_types.add(rt)
201 #print " {ot}/{t} -> {rt}"
202 end
203 end
204 #print "cast MType {live_cast_types.length}: {live_cast_types.join(", ")}"
205 end
206
207 private fun check_depth(mtype: MClassType)
208 do
209 var d = mtype.length
210 if d > 255 then
211 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}.")
212 end
213 end
214
215 fun add_new(recv: MClassType, mtype: MClassType)
216 do
217 assert not recv.need_anchor
218 if mtype.need_anchor then
219 if live_open_types.has(mtype) then return
220 live_open_types.add(mtype)
221 else
222 if live_types.has(mtype) then return
223 live_types.add(mtype)
224 end
225
226 var mclass = mtype.mclass
227 if live_classes.has(mclass) then return
228 live_classes.add(mclass)
229
230 for p in totry_methods do try_send(mtype, p)
231 for p in live_super_sends do try_super_send(mtype, p)
232
233 var bound_mtype = mtype.anchor_to(mainmodule, recv)
234 for cd in bound_mtype.collect_mclassdefs(mainmodule)
235 do
236 if not self.modelbuilder.mclassdef2nclassdef.has_key(cd) then continue
237 var nclassdef = self.modelbuilder.mclassdef2nclassdef[cd]
238 for npropdef in nclassdef.n_propdefs do
239 if not npropdef isa AAttrPropdef then continue
240 var nexpr = npropdef.n_expr
241 if nexpr == null then continue
242 var mpropdef = npropdef.mpropdef.as(not null)
243 var v = new RapidTypeVisitor(self, bound_mtype, mpropdef)
244 v.enter_visit(nexpr)
245 end
246 end
247
248 end
249
250 fun add_cast(mtype: MType)
251 do
252 if mtype isa MNullableType then mtype = mtype.mtype
253 if mtype.need_anchor then
254 live_open_cast_types.add(mtype)
255 else
256 assert mtype isa MClassType
257 live_cast_types.add(mtype)
258 end
259 end
260
261 fun try_send(recv: MClassType, mproperty: MMethod)
262 do
263 recv = recv.mclass.intro.bound_mtype
264 if not recv.has_mproperty(mainmodule, mproperty) then return
265 var d = mproperty.lookup_first_definition(mainmodule, recv)
266 add_call(d)
267 end
268
269 fun add_call(mpropdef: MMethodDef)
270 do
271 if live_methoddefs.has(mpropdef) then return
272 live_methoddefs.add(mpropdef)
273 todo.add(mpropdef)
274
275 var mproperty = mpropdef.mproperty
276 if mproperty.mpropdefs.length <= 1 then return
277 # If all definitions of a method are live, we can remove the definition of the totry set
278 for d in mproperty.mpropdefs do
279 if d.is_abstract then continue
280 if not live_methoddefs.has(d) then return
281 end
282 #print "full property: {mpropdef.mproperty} for {mpropdef.mproperty.mpropdefs.length} definitions"
283 totry_methods.remove(mpropdef.mproperty)
284 end
285
286 fun add_send(recv: MType, mproperty: MMethod)
287 do
288 if live_methods.has(mproperty) then return
289 #print "new prop: {mproperty}"
290 live_methods.add(mproperty)
291 if mproperty.mpropdefs.length == 1 then
292 # If there is only one definition, just add the definition and do not try again the property
293 var d = mproperty.mpropdefs.first
294 add_call(d)
295 return
296 end
297 # Else, the property is potentially called with various reciever
298 # So just try the methods with existing receiver and register it for future receiver
299 totry_methods.add(mproperty)
300 for c in live_classes do
301 try_send(c.intro.bound_mtype, mproperty)
302 end
303 end
304
305 fun try_super_send(recv: MClassType, mpropdef: MMethodDef)
306 do
307 recv = recv.mclass.intro.bound_mtype
308 if not recv.collect_mclassdefs(mainmodule).has(mpropdef.mclassdef) then return
309 var d = mpropdef.lookup_next_definition(mainmodule, recv)
310 add_call(d)
311 end
312
313 fun add_super_send(recv: MType, mpropdef: MMethodDef)
314 do
315 if live_super_sends.has(mpropdef) then return
316 #print "new super prop: {mpropdef}"
317 live_super_sends.add(mpropdef)
318 for t in live_types do
319 try_super_send(t, mpropdef)
320 end
321 end
322 end
323
324 class RapidTypeVisitor
325 super Visitor
326
327 var analysis: RapidTypeAnalysis
328 var receiver: MClassType
329 var mpropdef: MPropDef
330
331 init(analysis: RapidTypeAnalysis, receiver: MClassType, mpropdef: MPropDef)
332 do
333 self.analysis = analysis
334 self.receiver = receiver
335 self.mpropdef = mpropdef
336 assert not receiver.need_anchor
337 end
338
339 redef fun visit(n)
340 do
341 if n == null then return
342 n.accept_rapid_type_visitor(self)
343 if n isa AExpr then
344 var implicit_cast_to = n.implicit_cast_to
345 if implicit_cast_to != null then self.add_cast_type(implicit_cast_to)
346 end
347
348 # RTA does not enter in AAnnotations
349 if not n isa AAnnotations then
350 n.visit_all(self)
351 end
352 end
353
354 fun cleanup_type(mtype: MType): nullable MClassType
355 do
356 mtype = mtype.anchor_to(self.analysis.mainmodule, self.receiver)
357 if mtype isa MNullType then return null
358 if mtype isa MNullableType then mtype = mtype.mtype
359 assert mtype isa MClassType
360 assert not mtype.need_anchor
361 return mtype
362 end
363
364 fun get_class(name: String): MClass
365 do
366 return analysis.mainmodule.get_primitive_class(name)
367 end
368
369 fun get_method(recv: MType, name: String): MMethod
370 do
371 var mtype = cleanup_type(recv)
372 assert mtype != null
373 return self.analysis.modelbuilder.force_get_primitive_method(self.current_node.as(not null), name, mtype.mclass, self.analysis.mainmodule)
374 end
375
376 fun add_type(mtype: MClassType) do analysis.add_new(receiver, mtype)
377
378 fun add_monomorphic_send(mtype: MType, mproperty: MMethod) do analysis.try_send(mtype.as(MClassType), mproperty)
379
380 fun add_send(mtype: MType, mproperty: MMethod) do analysis.add_send(mtype, mproperty)
381
382 fun add_cast_type(mtype: MType) do analysis.add_cast(mtype)
383 end
384
385 ###
386
387 redef class ANode
388 private fun accept_rapid_type_visitor(v: RapidTypeVisitor)
389 do
390 end
391 end
392
393 redef class AIntExpr
394 redef fun accept_rapid_type_visitor(v)
395 do
396 v.add_type(self.mtype.as(MClassType))
397 end
398 end
399
400 redef class AFloatExpr
401 redef fun accept_rapid_type_visitor(v)
402 do
403 v.add_type(self.mtype.as(MClassType))
404 end
405 end
406
407 redef class ACharExpr
408 redef fun accept_rapid_type_visitor(v)
409 do
410 v.add_type(self.mtype.as(MClassType))
411 end
412 end
413
414 redef class AArrayExpr
415 redef fun accept_rapid_type_visitor(v)
416 do
417 var mtype = self.mtype.as(MClassType)
418 v.add_type(mtype)
419 var native = v.analysis.mainmodule.get_primitive_class("NativeArray").get_mtype([mtype.arguments.first])
420 v.add_type(native)
421 mtype = v.cleanup_type(mtype).as(not null)
422 var prop = v.get_method(mtype, "with_native")
423 v.add_monomorphic_send(mtype, prop)
424 end
425 end
426
427 redef class AStringFormExpr
428 redef fun accept_rapid_type_visitor(v)
429 do
430 var mtype = self.mtype.as(MClassType)
431 v.add_type(mtype)
432 var native = v.get_class("NativeString").mclass_type
433 v.add_type(native)
434 var prop = v.get_method(mtype, "from_cstring")
435 v.add_monomorphic_send(mtype, prop)
436 end
437 end
438
439 redef class ASuperstringExpr
440 redef fun accept_rapid_type_visitor(v)
441 do
442 var arraytype = v.get_class("Array").get_mtype([v.get_class("Object").mclass_type])
443 v.add_type(arraytype)
444 v.add_type(v.get_class("NativeArray").get_mtype([v.get_class("Object").mclass_type]))
445 var prop = v.get_method(arraytype, "join")
446 v.add_monomorphic_send(arraytype, prop)
447 var prop2 = v.get_method(arraytype, "with_native")
448 v.add_monomorphic_send(arraytype, prop2)
449 end
450 end
451
452 redef class ACrangeExpr
453 redef fun accept_rapid_type_visitor(v)
454 do
455 var mtype = self.mtype.as(MClassType)
456 v.add_type(mtype)
457 var prop = v.get_method(mtype, "init")
458 v.add_monomorphic_send(mtype, prop)
459 end
460 end
461
462 redef class AOrangeExpr
463 redef fun accept_rapid_type_visitor(v)
464 do
465 var mtype = self.mtype.as(MClassType)
466 v.add_type(mtype)
467 var prop = v.get_method(mtype, "without_last")
468 v.add_monomorphic_send(mtype, prop)
469 end
470 end
471
472 redef class ATrueExpr
473 redef fun accept_rapid_type_visitor(v)
474 do
475 v.add_type(self.mtype.as(MClassType))
476 end
477 end
478
479 redef class AFalseExpr
480 redef fun accept_rapid_type_visitor(v)
481 do
482 v.add_type(self.mtype.as(MClassType))
483 end
484 end
485
486 redef class AIsaExpr
487 redef fun accept_rapid_type_visitor(v)
488 do
489 v.add_cast_type(self.cast_type.as(not null))
490 end
491 end
492
493 redef class AAsCastExpr
494 redef fun accept_rapid_type_visitor(v)
495 do
496 v.add_cast_type(self.mtype.as(not null))
497 end
498 end
499
500 redef class ASendExpr
501 redef fun accept_rapid_type_visitor(v)
502 do
503 var mproperty = self.mproperty.as(not null)
504 var recvtype = self.n_expr.mtype.as(not null)
505 v.add_send(recvtype, mproperty)
506 end
507 end
508
509
510 redef class ASendReassignFormExpr
511 redef fun accept_rapid_type_visitor(v)
512 do
513 v.add_send(self.read_type.as(not null), self.reassign_property.mproperty)
514 var mproperty = self.mproperty.as(not null)
515 var write_mproperty = self.write_mproperty.as(not null)
516 if n_expr isa ASelfExpr then
517 v.add_monomorphic_send(v.receiver, mproperty)
518 v.add_monomorphic_send(v.receiver, write_mproperty)
519 else
520 var recvtype = self.n_expr.mtype.as(not null)
521 v.add_send(recvtype, mproperty)
522 v.add_send(recvtype, write_mproperty)
523 end
524 end
525 end
526
527 redef class AVarReassignExpr
528 redef fun accept_rapid_type_visitor(v)
529 do
530 v.add_send(self.read_type.as(not null), self.reassign_property.mproperty)
531 end
532 end
533
534 redef class AAttrReassignExpr
535 redef fun accept_rapid_type_visitor(v)
536 do
537 v.add_send(self.read_type.as(not null), self.reassign_property.mproperty)
538 end
539 end
540
541 redef class ASuperExpr
542 redef fun accept_rapid_type_visitor(v)
543 do
544 var mproperty = self.mproperty
545 if mproperty != null then
546 v.add_monomorphic_send(v.receiver, mproperty)
547 return
548 end
549
550 v.analysis.add_super_send(v.receiver, v.mpropdef.as(MMethodDef))
551 end
552 end
553
554 redef class AForExpr
555 redef fun accept_rapid_type_visitor(v)
556 do
557 var recvtype = self.n_expr.mtype.as(not null)
558 var colltype = self.coltype.as(not null)
559 var itmeth = v.get_method(colltype, "iterator")
560 v.add_send(recvtype, itmeth)
561 var iteratortype = itmeth.intro.msignature.return_mtype.as(MClassType).mclass.intro.bound_mtype
562 var objtype = v.get_class("Object").mclass_type
563 v.add_send(objtype, v.get_method(iteratortype, "is_ok"))
564 if self.variables.length == 1 then
565 v.add_send(objtype, v.get_method(iteratortype, "item"))
566 else if self.variables.length == 2 then
567 v.add_send(objtype, v.get_method(iteratortype, "key"))
568 v.add_send(objtype, v.get_method(iteratortype, "item"))
569 else
570 abort
571 end
572 v.add_send(objtype, v.get_method(iteratortype, "next"))
573 end
574 end
575
576 redef class ANewExpr
577 redef fun accept_rapid_type_visitor(v)
578 do
579 var mtype = self.mtype.as(MClassType)
580 v.add_type(mtype)
581 var mproperty = self.mproperty.as(not null)
582 v.add_monomorphic_send(mtype, mproperty)
583 end
584 end