typing: move vararg_length on each argument, instead of the whole signature
[nit.git] / src / semantize / typing.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 # Intraprocedural resolution of static types and OO-services
18 # By OO-services we mean message sending, attribute access, instantiation, etc.
19 module typing
20
21 import modelize
22 import local_var_init
23 import literal
24
25 redef class ToolContext
26 var typing_phase: Phase = new TypingPhase(self, [flow_phase, modelize_property_phase, local_var_init_phase])
27 end
28
29 private class TypingPhase
30 super Phase
31 redef fun process_npropdef(npropdef) do npropdef.do_typing(toolcontext.modelbuilder)
32 end
33
34 private class TypeVisitor
35 var modelbuilder: ModelBuilder
36
37 # The module of the analysis
38 # Used to correctly query the model
39 var mmodule: MModule
40
41 # The static type of the receiver
42 # Mainly used for type tests and type resolutions
43 var anchor: nullable MClassType = null
44
45 # The analyzed mclassdef
46 var mclassdef: nullable MClassDef = null
47
48 # The analyzed property
49 var mpropdef: nullable MPropDef
50
51 var selfvariable = new Variable("self")
52
53 # Is `self` use restricted?
54 # * no explicit `self`
55 # * method called on the implicit self must be top-level
56 # Currently only used for `new` factory since there is no valid receiver inside
57 var is_toplevel_context = false
58
59 init
60 do
61 var mpropdef = self.mpropdef
62
63 if mpropdef != null then
64 self.mpropdef = mpropdef
65 var mclassdef = mpropdef.mclassdef
66 self.mclassdef = mclassdef
67 self.anchor = mclassdef.bound_mtype
68
69 var mclass = mclassdef.mclass
70
71 var selfvariable = new Variable("self")
72 self.selfvariable = selfvariable
73 selfvariable.declared_type = mclass.mclass_type
74
75 var mprop = mpropdef.mproperty
76 if mprop isa MMethod and mprop.is_new then
77 is_toplevel_context = true
78 end
79 end
80 end
81
82 fun anchor_to(mtype: MType): MType
83 do
84 var anchor = anchor
85 if anchor == null then
86 assert not mtype.need_anchor
87 return mtype
88 end
89 return mtype.anchor_to(mmodule, anchor)
90 end
91
92 fun is_subtype(sub, sup: MType): Bool
93 do
94 return sub.is_subtype(mmodule, anchor, sup)
95 end
96
97 fun resolve_for(mtype, subtype: MType, for_self: Bool): MType
98 do
99 #print "resolve_for {mtype} sub={subtype} forself={for_self} mmodule={mmodule} anchor={anchor}"
100 var res = mtype.resolve_for(subtype, anchor, mmodule, not for_self)
101 return res
102 end
103
104 # Check that `sub` is a subtype of `sup`.
105 # If `sub` is not a valid suptype, then display an error on `node` an return null.
106 # If `sub` is a safe subtype of `sup` then return `sub`.
107 # If `sub` is an unsafe subtype (ie an implicit cast is required), then return `sup`.
108 #
109 # The point of the return type is to determinate the usable type on an expression when `autocast` is true:
110 # If the suptype is safe, then the return type is the one on the expression typed by `sub`.
111 # Is the subtype is unsafe, then the return type is the one of an implicit cast on `sup`.
112 fun check_subtype(node: ANode, sub, sup: MType, autocast: Bool): nullable MType
113 do
114 if self.is_subtype(sub, sup) then return sub
115 if autocast and self.is_subtype(sub, self.anchor_to(sup)) then
116 # FIXME workaround to the current unsafe typing policy. To remove once fixed virtual types exists.
117 #node.debug("Unsafe typing: expected {sup}, got {sub}")
118 return sup
119 end
120 if sup isa MBottomType then return null # Skip error
121 if sub.need_anchor then
122 var u = anchor_to(sub)
123 self.modelbuilder.error(node, "Type Error: expected `{sup}`, got `{sub}: {u}`.")
124 else
125 self.modelbuilder.error(node, "Type Error: expected `{sup}`, got `{sub}`.")
126 end
127 return null
128 end
129
130 # Visit an expression and do not care about the return value
131 fun visit_stmt(nexpr: nullable AExpr)
132 do
133 if nexpr == null then return
134 nexpr.accept_typing(self)
135 end
136
137 # Visit an expression and expects that it is not a statement
138 # Return the type of the expression
139 # Display an error and return null if:
140 # * the type cannot be determined or
141 # * `nexpr` is a statement
142 fun visit_expr(nexpr: AExpr): nullable MType
143 do
144 nexpr.accept_typing(self)
145 var mtype = nexpr.mtype
146 if mtype != null then return mtype
147 if not nexpr.is_typed then
148 if not self.modelbuilder.toolcontext.error_count > 0 then # check that there is really an error
149 if self.modelbuilder.toolcontext.verbose_level > 1 then
150 nexpr.debug("No return type but no error.")
151 end
152 end
153 return null # forward error
154 end
155 self.error(nexpr, "Error: expected an expression.")
156 return null
157 end
158
159 # Visit an expression and expect its static type is a least a `sup`
160 # Return the type of the expression or null if
161 # * the type cannot be determined or
162 # * `nexpr` is a statement or
163 # * `nexpr` is not a `sup`
164 fun visit_expr_subtype(nexpr: AExpr, sup: nullable MType): nullable MType
165 do
166 var sub = visit_expr(nexpr)
167 if sub == null then return null # Forward error
168
169 if sup == null then return null # Forward error
170
171 var res = check_subtype(nexpr, sub, sup, true)
172 if res != sub then
173 nexpr.implicit_cast_to = res
174 end
175 return res
176 end
177
178 # Visit an expression and expect its static type is a `Bool`
179 # Return the type of the expression or null if
180 # * the type cannot be determined or
181 # * `nexpr` is a statement or
182 # * `nexpr` is not a `Bool`
183 fun visit_expr_bool(nexpr: AExpr): nullable MType
184 do
185 return self.visit_expr_subtype(nexpr, self.type_bool(nexpr))
186 end
187
188
189 fun check_expr_cast(node: ANode, nexpr: AExpr, ntype: AType): nullable MType
190 do
191 var sub = nexpr.mtype
192 if sub == null then return null # Forward error
193
194 var sup = ntype.mtype
195 if sup == null then return null # Forward error
196
197 if sup == sub then
198 self.modelbuilder.warning(node, "useless-type-test", "Warning: expression is already a `{sup}`.")
199 else if self.is_subtype(sub, sup) then
200 self.modelbuilder.warning(node, "useless-type-test", "Warning: expression is already a `{sup}` since it is a `{sub}`.")
201 end
202 return sup
203 end
204
205 # Can `mtype` be null (up to the current knowledge)?
206 fun can_be_null(mtype: MType): Bool
207 do
208 if mtype isa MNullableType or mtype isa MNullType then return true
209 if mtype isa MFormalType then
210 var x = anchor_to(mtype)
211 if x isa MNullableType or x isa MNullType then return true
212 end
213 return false
214 end
215
216 # Check that `mtype` can be null (up to the current knowledge).
217 #
218 # If not then display a `useless-null-test` warning on node and return false.
219 # Else return true.
220 fun check_can_be_null(anode: ANode, mtype: MType): Bool
221 do
222 if mtype isa MNullType then
223 modelbuilder.warning(anode, "useless-null-test", "Warning: expression is always `null`.")
224 return true
225 end
226 if can_be_null(mtype) then return true
227
228 if mtype isa MFormalType then
229 var res = anchor_to(mtype)
230 modelbuilder.warning(anode, "useless-null-test", "Warning: expression is not null, since it is a `{mtype}: {res}`.")
231 else
232 modelbuilder.warning(anode, "useless-null-test", "Warning: expression is not null, since it is a `{mtype}`.")
233 end
234 return false
235 end
236
237 # Special verification on != and == for null
238 # Return true
239 fun null_test(anode: ABinopExpr)
240 do
241 var mtype = anode.n_expr.mtype
242 var mtype2 = anode.n_expr2.mtype
243
244 if mtype == null or mtype2 == null then return
245
246 if not mtype2 isa MNullType then return
247
248 # Check of useless null
249 if not can_be_null(mtype) then return
250
251 if mtype isa MNullType then
252 # Because of type adaptation, we cannot just stop here
253 # so return use `null` as a bottom type that will be merged easily (cf) `merge_types`
254 mtype = null
255 else
256 mtype = mtype.as_notnull
257 end
258
259 # Check for type adaptation
260 var variable = anode.n_expr.its_variable
261 if variable == null then return
262
263 # One is null (mtype2 see above) the other is not null
264 if anode isa AEqExpr then
265 anode.after_flow_context.when_true.set_var(self, variable, mtype2)
266 anode.after_flow_context.when_false.set_var(self, variable, mtype)
267 else if anode isa ANeExpr then
268 anode.after_flow_context.when_false.set_var(self, variable, mtype2)
269 anode.after_flow_context.when_true.set_var(self, variable, mtype)
270 else
271 abort
272 end
273 end
274
275 fun try_get_mproperty_by_name2(anode: ANode, mtype: MType, name: String): nullable MProperty
276 do
277 return self.modelbuilder.try_get_mproperty_by_name2(anode, mmodule, mtype, name)
278 end
279
280 fun resolve_mtype(node: AType): nullable MType
281 do
282 return self.modelbuilder.resolve_mtype(mmodule, mclassdef, node)
283 end
284
285 fun try_get_mclass(node: ANode, name: String): nullable MClass
286 do
287 var mclass = modelbuilder.try_get_mclass_by_name(node, mmodule, name)
288 return mclass
289 end
290
291 fun get_mclass(node: ANode, name: String): nullable MClass
292 do
293 var mclass = modelbuilder.get_mclass_by_name(node, mmodule, name)
294 return mclass
295 end
296
297 fun type_bool(node: ANode): nullable MType
298 do
299 var mclass = self.get_mclass(node, "Bool")
300 if mclass == null then return null
301 return mclass.mclass_type
302 end
303
304 fun get_method(node: ANode, recvtype: MType, name: String, recv_is_self: Bool): nullable CallSite
305 do
306 var unsafe_type = self.anchor_to(recvtype)
307
308 #debug("recv: {recvtype} (aka {unsafe_type})")
309 if recvtype isa MNullType then
310 var objclass = get_mclass(node, "Object")
311 if objclass == null then return null # Forward error
312 unsafe_type = objclass.mclass_type
313 end
314
315 var mproperty = self.try_get_mproperty_by_name2(node, unsafe_type, name)
316 if name == "new" and mproperty == null then
317 name = "init"
318 mproperty = self.try_get_mproperty_by_name2(node, unsafe_type, name)
319 end
320
321 if mproperty == null then
322 if recv_is_self then
323 self.modelbuilder.error(node, "Error: method or variable `{name}` unknown in `{recvtype}`.")
324 else if recvtype.need_anchor then
325 self.modelbuilder.error(node, "Error: method `{name}` does not exists in `{recvtype}: {unsafe_type}`.")
326 else
327 self.modelbuilder.error(node, "Error: method `{name}` does not exists in `{recvtype}`.")
328 end
329 return null
330 end
331
332 assert mproperty isa MMethod
333
334 # `null` only accepts some methods of object.
335 if recvtype isa MNullType and not mproperty.is_null_safe then
336 self.error(node, "Error: method `{name}` called on `null`.")
337 return null
338 else if unsafe_type isa MNullableType and not mproperty.is_null_safe then
339 modelbuilder.advice(node, "call-on-nullable", "Warning: method call on a nullable receiver `{recvtype}`.")
340 end
341
342 if is_toplevel_context and recv_is_self and not mproperty.is_toplevel then
343 error(node, "Error: `{name}` is not a top-level method, thus need a receiver.")
344 end
345 if not recv_is_self and mproperty.is_toplevel then
346 error(node, "Error: cannot call `{name}`, a top-level method, with a receiver.")
347 end
348
349 if mproperty.visibility == protected_visibility and not recv_is_self and self.mmodule.visibility_for(mproperty.intro_mclassdef.mmodule) < intrude_visibility and not modelbuilder.toolcontext.opt_ignore_visibility.value then
350 self.modelbuilder.error(node, "Error: method `{name}` is protected and can only accessed by `self`.")
351 return null
352 end
353
354 var info = mproperty.deprecation
355 if info != null and self.mpropdef.mproperty.deprecation == null then
356 var mdoc = info.mdoc
357 if mdoc != null then
358 self.modelbuilder.warning(node, "deprecated-method", "Deprecation Warning: method `{name}` is deprecated: {mdoc.content.first}")
359 else
360 self.modelbuilder.warning(node, "deprecated-method", "Deprecation Warning: method `{name}` is deprecated.")
361 end
362 end
363
364 var propdefs = mproperty.lookup_definitions(self.mmodule, unsafe_type)
365 var mpropdef
366 if propdefs.length == 0 then
367 self.modelbuilder.error(node, "Type Error: no definition found for property `{name}` in `{unsafe_type}`.")
368 return null
369 else if propdefs.length == 1 then
370 mpropdef = propdefs.first
371 else
372 self.modelbuilder.warning(node, "property-conflict", "Warning: conflicting property definitions for property `{name}` in `{unsafe_type}`: {propdefs.join(" ")}")
373 mpropdef = mproperty.intro
374 end
375
376
377 var msignature = mpropdef.new_msignature or else mpropdef.msignature
378 if msignature == null then return null # skip error
379 msignature = resolve_for(msignature, recvtype, recv_is_self).as(MSignature)
380
381 var erasure_cast = false
382 var rettype = mpropdef.msignature.return_mtype
383 if not recv_is_self and rettype != null then
384 rettype = rettype.undecorate
385 if rettype isa MParameterType then
386 var erased_rettype = msignature.return_mtype
387 assert erased_rettype != null
388 #node.debug("Erasure cast: Really a {rettype} but unsafely a {erased_rettype}")
389 erasure_cast = true
390 end
391 end
392
393 var callsite = new CallSite(node.hot_location, recvtype, mmodule, anchor, recv_is_self, mproperty, mpropdef, msignature, erasure_cast)
394 return callsite
395 end
396
397 fun try_get_method(node: ANode, recvtype: MType, name: String, recv_is_self: Bool): nullable CallSite
398 do
399 var unsafe_type = self.anchor_to(recvtype)
400 var mproperty = self.try_get_mproperty_by_name2(node, unsafe_type, name)
401 if mproperty == null then return null
402 return get_method(node, recvtype, name, recv_is_self)
403 end
404
405
406 # Visit the expressions of args and check their conformity with the corresponding type in signature
407 # The point of this method is to handle varargs correctly
408 # Note: The signature must be correctly adapted
409 fun check_signature(node: ANode, args: Array[AExpr], mproperty: MProperty, msignature: MSignature): nullable SignatureMap
410 do
411 var vararg_rank = msignature.vararg_rank
412 if vararg_rank >= 0 then
413 if args.length < msignature.arity then
414 modelbuilder.error(node, "Error: expected at least {msignature.arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
415 return null
416 end
417 else if args.length != msignature.arity then
418 # Too much argument
419 if args.length > msignature.arity then
420 modelbuilder.error(node, "Error: expected {msignature.arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
421 return null
422 end
423 # Other cases are managed later
424 end
425
426
427 #debug("CALL {unsafe_type}.{msignature}")
428
429 # Associate each parameter to a position in the arguments
430 var map = new SignatureMap
431
432 # Special case for the isolated last argument
433 # TODO: reify this method characteristics (where? the param, the signature, the method?)
434 var last_is_padded = mproperty.name.chars.last == '='
435 var nbargs = args.length
436 if last_is_padded then
437 nbargs -= 1
438 assert not args.last isa ANamedargExpr
439 map.map[msignature.arity - 1] = args.length - 1
440 self.visit_expr_subtype(args.last, msignature.mparameters.last.mtype)
441 end
442
443 # First, handle named arguments
444 for i in [0..args.length[ do
445 var e = args[i]
446 if not e isa ANamedargExpr then continue
447 var name = e.n_id.text
448 var param = msignature.mparameter_by_name(name)
449 if param == null then
450 modelbuilder.error(e.n_id, "Error: no parameter `{name}` for `{mproperty}{msignature}`.")
451 return null
452 end
453 var idx = msignature.mparameters.index_of(param)
454 var prev = map.map.get_or_null(idx)
455 if prev != null then
456 modelbuilder.error(e, "Error: parameter `{name}` already associated with argument #{prev} for `{mproperty}{msignature}`.")
457 return null
458 end
459 map.map[idx] = i
460 e.mtype = self.visit_expr_subtype(e.n_expr, param.mtype)
461 end
462
463 # Number of minimum mandatory remaining parameters
464 var min_arity = 0
465
466 # Second, associate remaining parameters
467 var vararg_decl = args.length - msignature.arity
468 var j = 0
469 for i in [0..msignature.arity[ do
470 # Skip parameters associated by name
471 if map.map.has_key(i) then continue
472
473 var param = msignature.mparameters[i]
474
475 # Search the next free argument: skip named arguments since they are already associated
476 while j < nbargs and args[j] isa ANamedargExpr do j += 1
477 if j >= nbargs then
478 if not param.mtype isa MNullableType then
479 min_arity = j + 1
480 end
481 j += 1
482 continue
483 end
484 var arg = args[j]
485 map.map[i] = j
486 j += 1
487
488 if i == vararg_rank then
489 j += vararg_decl
490 continue # skip the vararg
491 end
492
493 var paramtype = param.mtype
494 self.visit_expr_subtype(arg, paramtype)
495 end
496
497 if min_arity > 0 then
498 if last_is_padded then min_arity += 1
499 if min_arity < msignature.arity then
500 modelbuilder.error(node, "Error: expected at least {min_arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
501 else
502 modelbuilder.error(node, "Error: expected {min_arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
503 end
504 return null
505 end
506
507 # Third, check varargs
508 if vararg_rank >= 0 then
509 var paramtype = msignature.mparameters[vararg_rank].mtype
510 var first = args[vararg_rank]
511 if vararg_decl == 0 then
512 var mclass = get_mclass(node, "Array")
513 if mclass == null then return null # Forward error
514 var array_mtype = mclass.get_mtype([paramtype])
515 if first isa AVarargExpr then
516 self.visit_expr_subtype(first.n_expr, array_mtype)
517 first.mtype = first.n_expr.mtype
518 else
519 # only one vararg, maybe `...` was forgot, so be gentle!
520 var t = visit_expr(first)
521 if t == null then return null # Forward error
522 if not is_subtype(t, paramtype) and is_subtype(t, array_mtype) then
523 # Not acceptable but could be a `...`
524 error(first, "Type Error: expected `{paramtype}`, got `{t}`. Is an ellipsis `...` missing on the argument?")
525 return null
526 end
527 # Standard valid vararg, finish the job
528 map.vararg_decl = 1
529 self.visit_expr_subtype(first, paramtype)
530 end
531 else
532 first.vararg_decl = vararg_decl + 1
533 for i in [vararg_rank..vararg_rank+vararg_decl] do
534 self.visit_expr_subtype(args[i], paramtype)
535 end
536 end
537 end
538
539 return map
540 end
541
542 fun error(node: ANode, message: String)
543 do
544 self.modelbuilder.error(node, message)
545 end
546
547 fun get_variable(node: AExpr, variable: Variable): nullable MType
548 do
549 if not variable.is_adapted then return variable.declared_type
550
551 var flow = node.after_flow_context
552 if flow == null then return null # skip error
553
554 if flow.vars.has_key(variable) then
555 return flow.vars[variable]
556 else
557 #node.debug("*** START Collected for {variable}")
558 var mtypes = flow.collect_types(variable)
559 #node.debug("**** END Collected for {variable}")
560 if mtypes.length == 0 then
561 return variable.declared_type
562 else if mtypes.length == 1 then
563 return mtypes.first
564 else
565 var res = merge_types(node,mtypes)
566 if res == null then res = variable.declared_type
567 return res
568 end
569 end
570 end
571
572 # Some variables where type-adapted during the visit
573 var dirty = false
574
575 # Some loops had been visited during the visit
576 var has_loop = false
577
578 fun set_variable(node: AExpr, variable: Variable, mtype: nullable MType)
579 do
580 var flow = node.after_flow_context
581 assert flow != null
582
583 flow.set_var(self, variable, mtype)
584 end
585
586 fun merge_types(node: ANode, col: Array[nullable MType]): nullable MType
587 do
588 if col.length == 1 then return col.first
589 for t1 in col do
590 if t1 == null then continue # return null
591 var found = true
592 for t2 in col do
593 if t2 == null then continue # return null
594 if can_be_null(t2) and not can_be_null(t1) then
595 t1 = t1.as_nullable
596 end
597 if not is_subtype(t2, t1) then found = false
598 end
599 if found then
600 #print "merge {col.join(" ")} -> {t1}"
601 return t1
602 end
603 end
604 #self.modelbuilder.warning(node, "Type Error: {col.length} conflicting types: <{col.join(", ")}>")
605 return null
606 end
607 end
608
609 # Mapping between parameters and arguments in a call.
610 #
611 # Parameters and arguments are not stored in the class but referenced by their position (starting from 0)
612 #
613 # The point of this class is to help engine and other things to map arguments in the AST to parameters of the model.
614 class SignatureMap
615 # Associate a parameter to an argument
616 var map = new ArrayMap[Int, Int]
617 end
618
619 # A specific method call site with its associated informations.
620 class CallSite
621 super MEntity
622
623 # The associated location of the callsite
624 var location: Location
625
626 # The static type of the receiver (possibly unresolved)
627 var recv: MType
628
629 # The module where the callsite is present
630 var mmodule: MModule
631
632 # The anchor to use with `recv` or `msignature`
633 var anchor: nullable MClassType
634
635 # Is the receiver self?
636 # If "for_self", virtual types of the signature are kept
637 # If "not_for_self", virtual type are erased
638 var recv_is_self: Bool
639
640 # The designated method
641 var mproperty: MMethod
642
643 # The statically designated method definition
644 # The most specif one, it is.
645 var mpropdef: MMethodDef
646
647 # The resolved signature for the receiver
648 var msignature: MSignature
649
650 # Is a implicit cast required on erasure typing policy?
651 var erasure_cast: Bool
652
653 # The mapping used on the call to associate arguments to parameters
654 # If null then no specific association is required.
655 var signaturemap: nullable SignatureMap = null
656
657 private fun check_signature(v: TypeVisitor, node: ANode, args: Array[AExpr]): Bool
658 do
659 var map = v.check_signature(node, args, self.mproperty, self.msignature)
660 signaturemap = map
661 if map == null then is_broken = true
662 return map == null
663 end
664 end
665
666 redef class Variable
667 # The declared type of the variable
668 var declared_type: nullable MType is writable
669
670 # Was the variable type-adapted?
671 # This is used to speedup type retrieval while it remains `false`
672 private var is_adapted = false
673 end
674
675 redef class FlowContext
676 # Store changes of types because of type evolution
677 private var vars = new HashMap[Variable, nullable MType]
678
679 # Adapt the variable to a static type
680 # Warning1: do not modify vars directly.
681 # Warning2: sub-flow may have cached a unadapted variable
682 private fun set_var(v: TypeVisitor, variable: Variable, mtype: nullable MType)
683 do
684 if variable.declared_type == mtype and not variable.is_adapted then return
685 if vars.has_key(variable) and vars[variable] == mtype then return
686 self.vars[variable] = mtype
687 v.dirty = true
688 variable.is_adapted = true
689 #node.debug "set {variable} to {mtype or else "X"}"
690 end
691
692 # Look in the flow and previous flow and collect all first reachable type adaptation of a local variable
693 private fun collect_types(variable: Variable): Array[nullable MType]
694 do
695 #node.debug "flow for {variable}"
696 var res = new Array[nullable MType]
697
698 var todo = [self]
699 var seen = new HashSet[FlowContext]
700 while not todo.is_empty do
701 var f = todo.pop
702 if f.is_unreachable then continue
703 if seen.has(f) then continue
704 seen.add f
705
706 if f.vars.has_key(variable) then
707 # Found something. Collect it and do not process further on this path
708 res.add f.vars[variable]
709 #f.node.debug "process {variable}: got {f.vars[variable] or else "X"}"
710 else
711 todo.add_all f.previous
712 todo.add_all f.loops
713 if f.previous.is_empty then
714 # Root flowcontext mean a parameter or something related
715 res.add variable.declared_type
716 #f.node.debug "root process {variable}: got {variable.declared_type or else "X"}"
717 end
718 end
719 end
720 #self.node.debug "##### end flow for {variable}: {res.join(" ")}"
721 return res
722 end
723 end
724
725 redef class APropdef
726 # The entry point of the whole typing analysis
727 fun do_typing(modelbuilder: ModelBuilder)
728 do
729 end
730
731 # The variable associated to the receiver (if any)
732 var selfvariable: nullable Variable
733 end
734
735 redef class AMethPropdef
736 redef fun do_typing(modelbuilder: ModelBuilder)
737 do
738 var mpropdef = self.mpropdef
739 if mpropdef == null then return # skip error
740
741 var v = new TypeVisitor(modelbuilder, mpropdef.mclassdef.mmodule, mpropdef)
742 self.selfvariable = v.selfvariable
743
744 var mmethoddef = self.mpropdef.as(not null)
745 var msignature = mmethoddef.msignature
746 if msignature == null then return # skip error
747 for i in [0..msignature.arity[ do
748 var mtype = msignature.mparameters[i].mtype
749 if msignature.vararg_rank == i then
750 var arrayclass = v.get_mclass(self.n_signature.n_params[i], "Array")
751 if arrayclass == null then return # Skip error
752 mtype = arrayclass.get_mtype([mtype])
753 end
754 var variable = self.n_signature.n_params[i].variable
755 assert variable != null
756 variable.declared_type = mtype
757 end
758
759 var nblock = self.n_block
760 if nblock == null then return
761
762 loop
763 v.dirty = false
764 v.visit_stmt(nblock)
765 if not v.has_loop or not v.dirty then break
766 end
767
768 var post_visitor = new PostTypingVisitor(v)
769 post_visitor.enter_visit(self)
770
771 if not nblock.after_flow_context.is_unreachable and msignature.return_mtype != null then
772 # We reach the end of the function without having a return, it is bad
773 v.error(self, "Error: reached end of function; expected `return` with a value.")
774 end
775 end
776 end
777
778 private class PostTypingVisitor
779 super Visitor
780 var type_visitor: TypeVisitor
781 redef fun visit(n) do
782 n.visit_all(self)
783 n.accept_post_typing(type_visitor)
784 if n isa AExpr and n.mtype == null and not n.is_typed then
785 n.is_broken = true
786 end
787 end
788 end
789
790 redef class ANode
791 private fun accept_post_typing(v: TypeVisitor) do end
792 end
793
794 redef class AAttrPropdef
795 redef fun do_typing(modelbuilder: ModelBuilder)
796 do
797 if not has_value then return
798
799 var mpropdef = self.mreadpropdef
800 if mpropdef == null or mpropdef.msignature == null then return # skip error
801
802 var v = new TypeVisitor(modelbuilder, mpropdef.mclassdef.mmodule, mpropdef)
803 self.selfvariable = v.selfvariable
804
805 var nexpr = self.n_expr
806 if nexpr != null then
807 var mtype = self.mtype
808 v.visit_expr_subtype(nexpr, mtype)
809 end
810 var nblock = self.n_block
811 if nblock != null then
812 v.visit_stmt(nblock)
813 if not nblock.after_flow_context.is_unreachable then
814 # We reach the end of the init without having a return, it is bad
815 v.error(self, "Error: reached end of block; expected `return`.")
816 end
817 end
818 end
819 end
820
821 ###
822
823 redef class AExpr
824 # The static type of the expression.
825 # null if self is a statement or in case of error
826 var mtype: nullable MType = null
827
828 # Is the statement correctly typed?
829 # Used to distinguish errors and statements when `mtype == null`
830 var is_typed: Bool = false
831
832 # If required, the following implicit cast `.as(XXX)`
833 # Such a cast may by required after evaluating the expression when
834 # a unsafe operation is detected (silently accepted by the Nit language).
835 # The attribute is computed by `check_subtype`
836 var implicit_cast_to: nullable MType = null
837
838 # Return the variable read (if any)
839 # Used to perform adaptive typing
840 fun its_variable: nullable Variable do return null
841
842 private fun accept_typing(v: TypeVisitor)
843 do
844 v.error(self, "no implemented accept_typing for {self.class_name}")
845 end
846
847 # Is non-null if `self` is a leaf of a comprehension array construction.
848 # In this case, the enclosing literal array node is designated.
849 # The result of the evaluation of `self` must be
850 # stored inside the designated array (there is an implicit `push`)
851 var comprehension: nullable AArrayExpr = null
852
853 # It indicates the number of arguments collected as a vararg.
854 #
855 # When 0, the argument is used as is, without transformation.
856 # When 1, the argument is transformed into an singleton array.
857 # Above 1, the arguments and the next ones are transformed into a common array.
858 #
859 # This attribute is meaning less on expressions not used as attributes.
860 var vararg_decl: Int = 0
861 end
862
863 redef class ABlockExpr
864 redef fun accept_typing(v)
865 do
866 for e in self.n_expr do v.visit_stmt(e)
867 self.is_typed = true
868 end
869
870 # The type of a blockexpr is the one of the last expression (or null if empty)
871 redef fun mtype
872 do
873 if self.n_expr.is_empty then return null
874 return self.n_expr.last.mtype
875 end
876 end
877
878 redef class AVardeclExpr
879 redef fun accept_typing(v)
880 do
881 var variable = self.variable
882 if variable == null then return # Skip error
883
884 var ntype = self.n_type
885 var mtype: nullable MType
886 if ntype == null then
887 mtype = null
888 else
889 mtype = v.resolve_mtype(ntype)
890 if mtype == null then return # Skip error
891 end
892
893 var nexpr = self.n_expr
894 if nexpr != null then
895 if mtype != null then
896 var etype = v.visit_expr_subtype(nexpr, mtype)
897 if etype == mtype then
898 assert ntype != null
899 v.modelbuilder.advice(ntype, "useless-type", "Warning: useless type definition for variable `{variable.name}`")
900 end
901 else
902 mtype = v.visit_expr(nexpr)
903 if mtype == null then return # Skip error
904 end
905 end
906
907 var decltype = mtype
908 if mtype == null or mtype isa MNullType then
909 var objclass = v.get_mclass(self, "Object")
910 if objclass == null then return # skip error
911 decltype = objclass.mclass_type.as_nullable
912 if mtype == null then mtype = decltype
913 end
914
915 variable.declared_type = decltype
916 v.set_variable(self, variable, mtype)
917
918 #debug("var {variable}: {mtype}")
919
920 self.mtype = mtype
921 self.is_typed = true
922 end
923 end
924
925 redef class AVarExpr
926 redef fun its_variable do return self.variable
927 redef fun accept_typing(v)
928 do
929 var variable = self.variable
930 if variable == null then return # Skip error
931
932 var mtype = v.get_variable(self, variable)
933 if mtype != null then
934 #debug("{variable} is {mtype}")
935 else
936 #debug("{variable} is untyped")
937 end
938
939 self.mtype = mtype
940 end
941 end
942
943 redef class AVarAssignExpr
944 redef fun accept_typing(v)
945 do
946 var variable = self.variable
947 assert variable != null
948
949 var mtype = v.visit_expr_subtype(n_value, variable.declared_type)
950
951 v.set_variable(self, variable, mtype)
952
953 self.is_typed = true
954 end
955 end
956
957 redef class AReassignFormExpr
958 # The method designed by the reassign operator.
959 var reassign_callsite: nullable CallSite
960
961 var read_type: nullable MType = null
962
963 # Determine the `reassign_property`
964 # `readtype` is the type of the reading of the left value.
965 # `writetype` is the type of the writing of the left value.
966 # (Because of `ACallReassignExpr`, both can be different.
967 # Return the static type of the value to store.
968 private fun resolve_reassignment(v: TypeVisitor, readtype, writetype: MType): nullable MType
969 do
970 var reassign_name = self.n_assign_op.operator
971
972 self.read_type = readtype
973
974 var callsite = v.get_method(self.n_assign_op, readtype, reassign_name, false)
975 if callsite == null then return null # Skip error
976 self.reassign_callsite = callsite
977
978 var msignature = callsite.msignature
979 var rettype = msignature.return_mtype
980 assert msignature.arity == 1 and rettype != null
981
982 var value_type = v.visit_expr_subtype(self.n_value, msignature.mparameters.first.mtype)
983 if value_type == null then return null # Skip error
984
985 v.check_subtype(self, rettype, writetype, false)
986 return rettype
987 end
988 end
989
990 redef class AVarReassignExpr
991 redef fun accept_typing(v)
992 do
993 var variable = self.variable
994 assert variable != null
995
996 var readtype = v.get_variable(self, variable)
997 if readtype == null then return
998
999 read_type = readtype
1000
1001 var writetype = variable.declared_type
1002 if writetype == null then return
1003
1004 var rettype = self.resolve_reassignment(v, readtype, writetype)
1005
1006 v.set_variable(self, variable, rettype)
1007
1008 self.is_typed = rettype != null
1009 end
1010 end
1011
1012
1013 redef class AContinueExpr
1014 redef fun accept_typing(v)
1015 do
1016 var nexpr = self.n_expr
1017 if nexpr != null then
1018 v.visit_expr(nexpr)
1019 end
1020 self.is_typed = true
1021 end
1022 end
1023
1024 redef class ABreakExpr
1025 redef fun accept_typing(v)
1026 do
1027 var nexpr = self.n_expr
1028 if nexpr != null then
1029 v.visit_expr(nexpr)
1030 end
1031 self.is_typed = true
1032 end
1033 end
1034
1035 redef class AReturnExpr
1036 redef fun accept_typing(v)
1037 do
1038 var nexpr = self.n_expr
1039 var ret_type
1040 var mpropdef = v.mpropdef
1041 if mpropdef isa MMethodDef then
1042 ret_type = mpropdef.msignature.return_mtype
1043 else if mpropdef isa MAttributeDef then
1044 ret_type = mpropdef.static_mtype
1045 else
1046 abort
1047 end
1048 if nexpr != null then
1049 if ret_type != null then
1050 v.visit_expr_subtype(nexpr, ret_type)
1051 else
1052 v.visit_expr(nexpr)
1053 v.error(nexpr, "Error: `return` with value in a procedure.")
1054 return
1055 end
1056 else if ret_type != null then
1057 v.error(self, "Error: `return` without value in a function.")
1058 return
1059 end
1060 self.is_typed = true
1061 end
1062 end
1063
1064 redef class AAbortExpr
1065 redef fun accept_typing(v)
1066 do
1067 self.is_typed = true
1068 end
1069 end
1070
1071 redef class AIfExpr
1072 redef fun accept_typing(v)
1073 do
1074 v.visit_expr_bool(n_expr)
1075
1076 v.visit_stmt(n_then)
1077 v.visit_stmt(n_else)
1078
1079 self.is_typed = true
1080
1081 if n_then != null and n_else == null then
1082 self.mtype = n_then.mtype
1083 end
1084 end
1085 end
1086
1087 redef class AIfexprExpr
1088 redef fun accept_typing(v)
1089 do
1090 v.visit_expr_bool(n_expr)
1091
1092 var t1 = v.visit_expr(n_then)
1093 var t2 = v.visit_expr(n_else)
1094
1095 if t1 == null or t2 == null then
1096 return # Skip error
1097 end
1098
1099 var t = v.merge_types(self, [t1, t2])
1100 if t == null then
1101 v.error(self, "Type Error: ambiguous type `{t1}` vs `{t2}`.")
1102 end
1103 self.mtype = t
1104 end
1105 end
1106
1107 redef class ADoExpr
1108 redef fun accept_typing(v)
1109 do
1110 v.visit_stmt(n_block)
1111 self.is_typed = true
1112 end
1113 end
1114
1115 redef class AWhileExpr
1116 redef fun accept_typing(v)
1117 do
1118 v.has_loop = true
1119 v.visit_expr_bool(n_expr)
1120 v.visit_stmt(n_block)
1121 self.is_typed = true
1122 end
1123 end
1124
1125 redef class ALoopExpr
1126 redef fun accept_typing(v)
1127 do
1128 v.has_loop = true
1129 v.visit_stmt(n_block)
1130 self.is_typed = true
1131 end
1132 end
1133
1134 redef class AForExpr
1135 redef fun accept_typing(v)
1136 do
1137 v.has_loop = true
1138
1139 for g in n_groups do
1140 var mtype = v.visit_expr(g.n_expr)
1141 if mtype == null then return
1142 g.do_type_iterator(v, mtype)
1143 if g.is_broken then is_broken = true
1144 end
1145
1146 v.visit_stmt(n_block)
1147
1148 self.mtype = n_block.mtype
1149 self.is_typed = true
1150 end
1151 end
1152
1153 redef class AForGroup
1154 var coltype: nullable MClassType
1155
1156 var method_iterator: nullable CallSite
1157 var method_is_ok: nullable CallSite
1158 var method_item: nullable CallSite
1159 var method_next: nullable CallSite
1160 var method_key: nullable CallSite
1161 var method_finish: nullable CallSite
1162
1163 var method_lt: nullable CallSite
1164 var method_successor: nullable CallSite
1165
1166 private fun do_type_iterator(v: TypeVisitor, mtype: MType)
1167 do
1168 if mtype isa MNullType then
1169 v.error(self, "Type Error: `for` cannot iterate over `null`.")
1170 return
1171 end
1172
1173 # get obj class
1174 var objcla = v.get_mclass(self, "Object")
1175 if objcla == null then return
1176
1177 # check iterator method
1178 var itdef = v.get_method(self, mtype, "iterator", n_expr isa ASelfExpr)
1179 if itdef == null then
1180 v.error(self, "Type Error: `for` expects a type providing an `iterator` method, got `{mtype}`.")
1181 return
1182 end
1183 self.method_iterator = itdef
1184
1185 # check that iterator return something
1186 var ittype = itdef.msignature.return_mtype
1187 if ittype == null then
1188 v.error(self, "Type Error: `for` expects the method `iterator` to return an `Iterator` or `MapIterator` type.")
1189 return
1190 end
1191
1192 # get iterator type
1193 var colit_cla = v.try_get_mclass(self, "Iterator")
1194 var mapit_cla = v.try_get_mclass(self, "MapIterator")
1195 var is_col = false
1196 var is_map = false
1197
1198 if colit_cla != null and v.is_subtype(ittype, colit_cla.get_mtype([objcla.mclass_type.as_nullable])) then
1199 # Iterator
1200 var coltype = ittype.supertype_to(v.mmodule, v.anchor, colit_cla)
1201 var variables = self.variables
1202 if variables.length != 1 then
1203 v.error(self, "Type Error: `for` expects only one variable when using `Iterator`.")
1204 else
1205 variables.first.declared_type = coltype.arguments.first
1206 end
1207 is_col = true
1208 end
1209
1210 if mapit_cla != null and v.is_subtype(ittype, mapit_cla.get_mtype([objcla.mclass_type.as_nullable, objcla.mclass_type.as_nullable])) then
1211 # Map Iterator
1212 var coltype = ittype.supertype_to(v.mmodule, v.anchor, mapit_cla)
1213 var variables = self.variables
1214 if variables.length != 2 then
1215 v.error(self, "Type Error: `for` expects two variables when using `MapIterator`.")
1216 else
1217 variables[0].declared_type = coltype.arguments[0]
1218 variables[1].declared_type = coltype.arguments[1]
1219 end
1220 is_map = true
1221 end
1222
1223 if not is_col and not is_map then
1224 v.error(self, "Type Error: `for` expects the method `iterator` to return an `Iterator` or `MapIterator` type.")
1225 return
1226 end
1227
1228 # anchor formal and virtual types
1229 if mtype.need_anchor then mtype = v.anchor_to(mtype)
1230
1231 mtype = mtype.undecorate
1232 self.coltype = mtype.as(MClassType)
1233
1234 # get methods is_ok, next, item
1235 var ikdef = v.get_method(self, ittype, "is_ok", false)
1236 if ikdef == null then
1237 v.error(self, "Type Error: `for` expects a method `is_ok` in type `{ittype}`.")
1238 return
1239 end
1240 self.method_is_ok = ikdef
1241
1242 var itemdef = v.get_method(self, ittype, "item", false)
1243 if itemdef == null then
1244 v.error(self, "Type Error: `for` expects a method `item` in type `{ittype}`.")
1245 return
1246 end
1247 self.method_item = itemdef
1248
1249 var nextdef = v.get_method(self, ittype, "next", false)
1250 if nextdef == null then
1251 v.error(self, "Type Error: `for` expects a method `next` in type {ittype}.")
1252 return
1253 end
1254 self.method_next = nextdef
1255
1256 self.method_finish = v.try_get_method(self, ittype, "finish", false)
1257
1258 if is_map then
1259 var keydef = v.get_method(self, ittype, "key", false)
1260 if keydef == null then
1261 v.error(self, "Type Error: `for` expects a method `key` in type `{ittype}`.")
1262 return
1263 end
1264 self.method_key = keydef
1265 end
1266
1267 if self.variables.length == 1 and n_expr isa ARangeExpr then
1268 var variable = variables.first
1269 var vtype = variable.declared_type.as(not null)
1270
1271 if n_expr isa AOrangeExpr then
1272 self.method_lt = v.get_method(self, vtype, "<", false)
1273 else
1274 self.method_lt = v.get_method(self, vtype, "<=", false)
1275 end
1276
1277 self.method_successor = v.get_method(self, vtype, "successor", false)
1278 end
1279 end
1280 end
1281
1282 redef class AWithExpr
1283 var method_start: nullable CallSite
1284 var method_finish: nullable CallSite
1285
1286 redef fun accept_typing(v: TypeVisitor)
1287 do
1288 var mtype = v.visit_expr(n_expr)
1289 if mtype == null then return
1290
1291 method_start = v.get_method(self, mtype, "start", n_expr isa ASelfExpr)
1292 method_finish = v.get_method(self, mtype, "finish", n_expr isa ASelfExpr)
1293
1294 v.visit_stmt(n_block)
1295 self.mtype = n_block.mtype
1296 self.is_typed = true
1297 end
1298 end
1299
1300 redef class AAssertExpr
1301 redef fun accept_typing(v)
1302 do
1303 v.visit_expr_bool(n_expr)
1304
1305 v.visit_stmt(n_else)
1306 self.is_typed = true
1307 end
1308 end
1309
1310 redef class AOrExpr
1311 redef fun accept_typing(v)
1312 do
1313 v.visit_expr_bool(n_expr)
1314 v.visit_expr_bool(n_expr2)
1315 self.mtype = v.type_bool(self)
1316 end
1317 end
1318
1319 redef class AImpliesExpr
1320 redef fun accept_typing(v)
1321 do
1322 v.visit_expr_bool(n_expr)
1323 v.visit_expr_bool(n_expr2)
1324 self.mtype = v.type_bool(self)
1325 end
1326 end
1327
1328 redef class AAndExpr
1329 redef fun accept_typing(v)
1330 do
1331 v.visit_expr_bool(n_expr)
1332 v.visit_expr_bool(n_expr2)
1333 self.mtype = v.type_bool(self)
1334 end
1335 end
1336
1337
1338 redef class ANotExpr
1339 redef fun accept_typing(v)
1340 do
1341 v.visit_expr_bool(n_expr)
1342 self.mtype = v.type_bool(self)
1343 end
1344 end
1345
1346 redef class AOrElseExpr
1347 redef fun accept_typing(v)
1348 do
1349 var t1 = v.visit_expr(n_expr)
1350 var t2 = v.visit_expr(n_expr2)
1351
1352 if t1 == null or t2 == null then
1353 return # Skip error
1354 end
1355
1356 if t1 isa MNullType then
1357 self.mtype = t2
1358 return
1359 else if v.can_be_null(t1) then
1360 t1 = t1.as_notnull
1361 end
1362
1363 var t = v.merge_types(self, [t1, t2])
1364 if t == null then
1365 var c = v.get_mclass(self, "Object")
1366 if c == null then return # forward error
1367 t = c.mclass_type
1368 if v.can_be_null(t2) then
1369 t = t.as_nullable
1370 end
1371 #v.error(self, "Type Error: ambiguous type {t1} vs {t2}")
1372 end
1373 self.mtype = t
1374 end
1375
1376 redef fun accept_post_typing(v)
1377 do
1378 var t1 = n_expr.mtype
1379 if t1 == null then
1380 return
1381 else
1382 v.check_can_be_null(n_expr, t1)
1383 end
1384 end
1385 end
1386
1387 redef class ATrueExpr
1388 redef fun accept_typing(v)
1389 do
1390 self.mtype = v.type_bool(self)
1391 end
1392 end
1393
1394 redef class AFalseExpr
1395 redef fun accept_typing(v)
1396 do
1397 self.mtype = v.type_bool(self)
1398 end
1399 end
1400
1401 redef class AIntegerExpr
1402 redef fun accept_typing(v)
1403 do
1404 var mclass: nullable MClass = null
1405 if value isa Byte then
1406 mclass = v.get_mclass(self, "Byte")
1407 else if value isa Int then
1408 mclass = v.get_mclass(self, "Int")
1409 else if value isa Int8 then
1410 mclass = v.get_mclass(self, "Int8")
1411 else if value isa Int16 then
1412 mclass = v.get_mclass(self, "Int16")
1413 else if value isa UInt16 then
1414 mclass = v.get_mclass(self, "UInt16")
1415 else if value isa Int32 then
1416 mclass = v.get_mclass(self, "Int32")
1417 else if value isa UInt32 then
1418 mclass = v.get_mclass(self, "UInt32")
1419 end
1420 if mclass == null then return # Forward error
1421 self.mtype = mclass.mclass_type
1422 end
1423 end
1424
1425 redef class AFloatExpr
1426 redef fun accept_typing(v)
1427 do
1428 var mclass = v.get_mclass(self, "Float")
1429 if mclass == null then return # Forward error
1430 self.mtype = mclass.mclass_type
1431 end
1432 end
1433
1434 redef class ACharExpr
1435 redef fun accept_typing(v)
1436 do
1437 var mclass = v.get_mclass(self, "Char")
1438 if mclass == null then return # Forward error
1439 self.mtype = mclass.mclass_type
1440 end
1441 end
1442
1443 redef class AStringFormExpr
1444 redef fun accept_typing(v)
1445 do
1446 var mclass = v.get_mclass(self, "String")
1447 if mclass == null then return # Forward error
1448 self.mtype = mclass.mclass_type
1449 end
1450 end
1451
1452 redef class ASuperstringExpr
1453 redef fun accept_typing(v)
1454 do
1455 var mclass = v.get_mclass(self, "String")
1456 if mclass == null then return # Forward error
1457 self.mtype = mclass.mclass_type
1458 var objclass = v.get_mclass(self, "Object")
1459 if objclass == null then return # Forward error
1460 var objtype = objclass.mclass_type
1461 for nexpr in self.n_exprs do
1462 v.visit_expr_subtype(nexpr, objtype)
1463 end
1464 end
1465 end
1466
1467 redef class AArrayExpr
1468 # The `with_capacity` method on Array
1469 var with_capacity_callsite: nullable CallSite
1470
1471 # The `push` method on arrays
1472 var push_callsite: nullable CallSite
1473
1474 # The element of each type
1475 var element_mtype: nullable MType
1476
1477 # Set that `self` is a part of comprehension array `na`
1478 # If `self` is a `for`, or a `if`, then `set_comprehension` is recursively applied.
1479 private fun set_comprehension(n: nullable AExpr)
1480 do
1481 if n == null then
1482 return
1483 else if n isa AForExpr then
1484 set_comprehension(n.n_block)
1485 else if n isa AIfExpr then
1486 set_comprehension(n.n_then)
1487 set_comprehension(n.n_else)
1488 else
1489 # is a leave
1490 n.comprehension = self
1491 end
1492 end
1493 redef fun accept_typing(v)
1494 do
1495 var mtype: nullable MType = null
1496 var ntype = self.n_type
1497 if ntype != null then
1498 mtype = v.resolve_mtype(ntype)
1499 if mtype == null then return # Skip error
1500 end
1501 var mtypes = new Array[nullable MType]
1502 var useless = false
1503 for e in self.n_exprs do
1504 var t = v.visit_expr(e)
1505 if t == null then
1506 return # Skip error
1507 end
1508 set_comprehension(e)
1509 if mtype != null then
1510 if v.check_subtype(e, t, mtype, false) == null then return # Forward error
1511 if t == mtype then useless = true
1512 else
1513 mtypes.add(t)
1514 end
1515 end
1516 if mtype == null then
1517 # Ensure monotony for type adaptation on loops
1518 if self.element_mtype != null then mtypes.add self.element_mtype
1519 mtype = v.merge_types(self, mtypes)
1520 end
1521 if mtype == null or mtype isa MNullType then
1522 v.error(self, "Type Error: ambiguous array type {mtypes.join(" ")}")
1523 return
1524 end
1525 if useless then
1526 assert ntype != null
1527 v.modelbuilder.warning(ntype, "useless-type", "Warning: useless type declaration `{mtype}` in literal Array since it can be inferred from the elements type.")
1528 end
1529
1530 self.element_mtype = mtype
1531
1532 var mclass = v.get_mclass(self, "Array")
1533 if mclass == null then return # Forward error
1534 var array_mtype = mclass.get_mtype([mtype])
1535
1536 with_capacity_callsite = v.get_method(self, array_mtype, "with_capacity", false)
1537 push_callsite = v.get_method(self, array_mtype, "push", false)
1538
1539 self.mtype = array_mtype
1540 end
1541 end
1542
1543 redef class ARangeExpr
1544 var init_callsite: nullable CallSite
1545
1546 redef fun accept_typing(v)
1547 do
1548 var discrete_class = v.get_mclass(self, "Discrete")
1549 if discrete_class == null then return # Forward error
1550 var discrete_type = discrete_class.intro.bound_mtype
1551 var t1 = v.visit_expr_subtype(self.n_expr, discrete_type)
1552 var t2 = v.visit_expr_subtype(self.n_expr2, discrete_type)
1553 if t1 == null or t2 == null then return
1554 var mclass = v.get_mclass(self, "Range")
1555 if mclass == null then return # Forward error
1556 var mtype
1557 if v.is_subtype(t1, t2) then
1558 mtype = mclass.get_mtype([t2])
1559 else if v.is_subtype(t2, t1) then
1560 mtype = mclass.get_mtype([t1])
1561 else
1562 v.error(self, "Type Error: cannot create range: `{t1}` vs `{t2}`.")
1563 return
1564 end
1565
1566 self.mtype = mtype
1567
1568 # get the constructor
1569 var callsite
1570 if self isa ACrangeExpr then
1571 callsite = v.get_method(self, mtype, "init", false)
1572 else if self isa AOrangeExpr then
1573 callsite = v.get_method(self, mtype, "without_last", false)
1574 else
1575 abort
1576 end
1577 init_callsite = callsite
1578 end
1579 end
1580
1581 redef class ANullExpr
1582 redef fun accept_typing(v)
1583 do
1584 self.mtype = v.mmodule.model.null_type
1585 end
1586 end
1587
1588 redef class AIsaExpr
1589 # The static type to cast to.
1590 # (different from the static type of the expression that is `Bool`).
1591 var cast_type: nullable MType
1592 redef fun accept_typing(v)
1593 do
1594 v.visit_expr(n_expr)
1595
1596 var mtype = v.resolve_mtype(n_type)
1597
1598 self.cast_type = mtype
1599
1600 var variable = self.n_expr.its_variable
1601 if variable != null then
1602 #var orig = self.n_expr.mtype
1603 #var from = if orig != null then orig.to_s else "invalid"
1604 #var to = if mtype != null then mtype.to_s else "invalid"
1605 #debug("adapt {variable}: {from} -> {to}")
1606 self.after_flow_context.when_true.set_var(v, variable, mtype)
1607 end
1608
1609 self.mtype = v.type_bool(self)
1610 end
1611
1612 redef fun accept_post_typing(v)
1613 do
1614 v.check_expr_cast(self, self.n_expr, self.n_type)
1615 end
1616 end
1617
1618 redef class AAsCastExpr
1619 redef fun accept_typing(v)
1620 do
1621 v.visit_expr(n_expr)
1622
1623 self.mtype = v.resolve_mtype(n_type)
1624 end
1625
1626 redef fun accept_post_typing(v)
1627 do
1628 v.check_expr_cast(self, self.n_expr, self.n_type)
1629 end
1630 end
1631
1632 redef class AAsNotnullExpr
1633 redef fun accept_typing(v)
1634 do
1635 var mtype = v.visit_expr(self.n_expr)
1636 if mtype == null then return # Forward error
1637
1638 if mtype isa MNullType then
1639 v.error(self, "Type Error: `as(not null)` on `null`.")
1640 return
1641 end
1642
1643 if v.can_be_null(mtype) then
1644 mtype = mtype.as_notnull
1645 end
1646
1647 self.mtype = mtype
1648 end
1649
1650 redef fun accept_post_typing(v)
1651 do
1652 var mtype = n_expr.mtype
1653 if mtype == null then return
1654 v.check_can_be_null(n_expr, mtype)
1655 end
1656 end
1657
1658 redef class AParExpr
1659 redef fun accept_typing(v)
1660 do
1661 self.mtype = v.visit_expr(self.n_expr)
1662 end
1663 end
1664
1665 redef class AOnceExpr
1666 redef fun accept_typing(v)
1667 do
1668 self.mtype = v.visit_expr(self.n_expr)
1669 end
1670 end
1671
1672 redef class ASelfExpr
1673 redef var its_variable: nullable Variable
1674 redef fun accept_typing(v)
1675 do
1676 if v.is_toplevel_context and not self isa AImplicitSelfExpr then
1677 v.error(self, "Error: `self` cannot be used in top-level method.")
1678 end
1679 var variable = v.selfvariable
1680 self.its_variable = variable
1681 self.mtype = v.get_variable(self, variable)
1682 end
1683 end
1684
1685 redef class AImplicitSelfExpr
1686 # Is the implicit receiver `sys`?
1687 #
1688 # By default, the implicit receiver is `self`.
1689 # But when there is not method for `self`, `sys` is used as a fall-back.
1690 # Is this case this flag is set to `true`.
1691 var is_sys = false
1692 end
1693
1694 ## MESSAGE SENDING AND PROPERTY
1695
1696 redef class ASendExpr
1697 # The property invoked by the send.
1698 var callsite: nullable CallSite
1699
1700 redef fun accept_typing(v)
1701 do
1702 var nrecv = self.n_expr
1703 var recvtype = v.visit_expr(nrecv)
1704 var name = self.property_name
1705 var node = self.property_node
1706
1707 if recvtype == null then return # Forward error
1708
1709 var callsite = null
1710 var unsafe_type = v.anchor_to(recvtype)
1711 var mproperty = v.try_get_mproperty_by_name2(node, unsafe_type, name)
1712 if mproperty == null and nrecv isa AImplicitSelfExpr then
1713 # Special fall-back search in `sys` when noting found in the implicit receiver.
1714 var sysclass = v.try_get_mclass(node, "Sys")
1715 if sysclass != null then
1716 var systype = sysclass.mclass_type
1717 mproperty = v.try_get_mproperty_by_name2(node, systype, name)
1718 if mproperty != null then
1719 callsite = v.get_method(node, systype, name, false)
1720 if callsite == null then return # Forward error
1721 # Update information, we are looking at `sys` now, not `self`
1722 nrecv.is_sys = true
1723 nrecv.its_variable = null
1724 nrecv.mtype = systype
1725 recvtype = systype
1726 end
1727 end
1728 end
1729 if callsite == null then
1730 # If still nothing, just exit
1731 callsite = v.get_method(node, recvtype, name, nrecv isa ASelfExpr)
1732 if callsite == null then return
1733 end
1734
1735 self.callsite = callsite
1736 var msignature = callsite.msignature
1737
1738 var args = compute_raw_arguments
1739
1740 callsite.check_signature(v, node, args)
1741
1742 if callsite.mproperty.is_init then
1743 var vmpropdef = v.mpropdef
1744 if not (vmpropdef isa MMethodDef and vmpropdef.mproperty.is_init) then
1745 v.error(node, "Error: an `init` can only be called from another `init`.")
1746 end
1747 if vmpropdef isa MMethodDef and vmpropdef.mproperty.is_root_init and not callsite.mproperty.is_root_init then
1748 v.error(node, "Error: `{vmpropdef}` cannot call a factory `{callsite.mproperty}`.")
1749 end
1750 end
1751
1752 var ret = msignature.return_mtype
1753 if ret != null then
1754 self.mtype = ret
1755 else
1756 self.is_typed = true
1757 end
1758 end
1759
1760 # The name of the property
1761 # Each subclass simply provide the correct name.
1762 private fun property_name: String is abstract
1763
1764 # The node identifying the name (id, operator, etc) for messages.
1765 #
1766 # Is `self` by default
1767 private fun property_node: ANode do return self
1768
1769 # An array of all arguments (excluding self)
1770 fun raw_arguments: Array[AExpr] do return compute_raw_arguments
1771
1772 private fun compute_raw_arguments: Array[AExpr] is abstract
1773 end
1774
1775 redef class ABinopExpr
1776 redef fun compute_raw_arguments do return [n_expr2]
1777 redef fun property_name do return operator
1778 redef fun property_node do return n_op
1779 end
1780
1781 redef class AEqFormExpr
1782 redef fun accept_typing(v)
1783 do
1784 super
1785 v.null_test(self)
1786 end
1787
1788 redef fun accept_post_typing(v)
1789 do
1790 var mtype = n_expr.mtype
1791 var mtype2 = n_expr2.mtype
1792
1793 if mtype == null or mtype2 == null then return
1794
1795 if not mtype2 isa MNullType then return
1796
1797 v.check_can_be_null(n_expr, mtype)
1798 end
1799 end
1800
1801 redef class AUnaryopExpr
1802 redef fun property_name do return "unary {operator}"
1803 redef fun compute_raw_arguments do return new Array[AExpr]
1804 end
1805
1806
1807 redef class ACallExpr
1808 redef fun property_name do return n_qid.n_id.text
1809 redef fun property_node do return n_qid
1810 redef fun compute_raw_arguments do return n_args.to_a
1811 end
1812
1813 redef class ACallAssignExpr
1814 redef fun property_name do return n_qid.n_id.text + "="
1815 redef fun property_node do return n_qid
1816 redef fun compute_raw_arguments
1817 do
1818 var res = n_args.to_a
1819 res.add(n_value)
1820 return res
1821 end
1822 end
1823
1824 redef class ABraExpr
1825 redef fun property_name do return "[]"
1826 redef fun compute_raw_arguments do return n_args.to_a
1827 end
1828
1829 redef class ABraAssignExpr
1830 redef fun property_name do return "[]="
1831 redef fun compute_raw_arguments
1832 do
1833 var res = n_args.to_a
1834 res.add(n_value)
1835 return res
1836 end
1837 end
1838
1839 redef class ASendReassignFormExpr
1840 # The property invoked for the writing
1841 var write_callsite: nullable CallSite
1842
1843 redef fun accept_typing(v)
1844 do
1845 var recvtype = v.visit_expr(self.n_expr)
1846 var name = self.property_name
1847 var node = self.property_node
1848
1849 if recvtype == null then return # Forward error
1850
1851 var for_self = self.n_expr isa ASelfExpr
1852 var callsite = v.get_method(node, recvtype, name, for_self)
1853
1854 if callsite == null then return
1855 self.callsite = callsite
1856
1857 var args = compute_raw_arguments
1858
1859 callsite.check_signature(v, node, args)
1860
1861 var readtype = callsite.msignature.return_mtype
1862 if readtype == null then
1863 v.error(node, "Error: `{name}` is not a function.")
1864 return
1865 end
1866
1867 var wcallsite = v.get_method(node, recvtype, name + "=", self.n_expr isa ASelfExpr)
1868 if wcallsite == null then return
1869 self.write_callsite = wcallsite
1870
1871 var wtype = self.resolve_reassignment(v, readtype, wcallsite.msignature.mparameters.last.mtype)
1872 if wtype == null then return
1873
1874 args = args.to_a # duplicate so raw_arguments keeps only the getter args
1875 args.add(self.n_value)
1876 wcallsite.check_signature(v, node, args)
1877
1878 self.is_typed = true
1879 end
1880 end
1881
1882 redef class ACallReassignExpr
1883 redef fun property_name do return n_qid.n_id.text
1884 redef fun property_node do return n_qid.n_id
1885 redef fun compute_raw_arguments do return n_args.to_a
1886 end
1887
1888 redef class ABraReassignExpr
1889 redef fun property_name do return "[]"
1890 redef fun compute_raw_arguments do return n_args.to_a
1891 end
1892
1893 redef class AInitExpr
1894 redef fun property_name do return "init"
1895 redef fun property_node do return n_kwinit
1896 redef fun compute_raw_arguments do return n_args.to_a
1897 end
1898
1899 redef class AExprs
1900 fun to_a: Array[AExpr] do return self.n_exprs.to_a
1901 end
1902
1903 ###
1904
1905 redef class ASuperExpr
1906 # The method to call if the super is in fact a 'super init call'
1907 # Note: if the super is a normal call-next-method, then this attribute is null
1908 var callsite: nullable CallSite
1909
1910 # The method to call is the super is a standard `call-next-method` super-call
1911 # Note: if the super is a special super-init-call, then this attribute is null
1912 var mpropdef: nullable MMethodDef
1913
1914 redef fun accept_typing(v)
1915 do
1916 var anchor = v.anchor
1917 assert anchor != null
1918 var recvtype = v.get_variable(self, v.selfvariable)
1919 assert recvtype != null
1920 var mproperty = v.mpropdef.mproperty
1921 if not mproperty isa MMethod then
1922 v.error(self, "Error: `super` only usable in a `method`.")
1923 return
1924 end
1925 var superprops = mproperty.lookup_super_definitions(v.mmodule, anchor)
1926 if superprops.length == 0 then
1927 if mproperty.is_init and v.mpropdef.is_intro then
1928 process_superinit(v)
1929 return
1930 end
1931 v.error(self, "Error: no super method to call for `{mproperty}`.")
1932 return
1933 end
1934 # FIXME: covariance of return type in linear extension?
1935 var superprop = superprops.first
1936
1937 var msignature = superprop.msignature.as(not null)
1938 msignature = v.resolve_for(msignature, recvtype, true).as(MSignature)
1939 var args = self.n_args.to_a
1940 if args.length > 0 then
1941 signaturemap = v.check_signature(self, args, mproperty, msignature)
1942 end
1943 self.mtype = msignature.return_mtype
1944 self.is_typed = true
1945 v.mpropdef.has_supercall = true
1946 mpropdef = v.mpropdef.as(MMethodDef)
1947 end
1948
1949 # The mapping used on the call to associate arguments to parameters.
1950 # If null then no specific association is required.
1951 var signaturemap: nullable SignatureMap
1952
1953 private fun process_superinit(v: TypeVisitor)
1954 do
1955 var anchor = v.anchor
1956 assert anchor != null
1957 var recvtype = v.get_variable(self, v.selfvariable)
1958 assert recvtype != null
1959 var mpropdef = v.mpropdef
1960 assert mpropdef isa MMethodDef
1961 var mproperty = mpropdef.mproperty
1962 var superprop: nullable MMethodDef = null
1963 for msupertype in mpropdef.mclassdef.supertypes do
1964 msupertype = msupertype.anchor_to(v.mmodule, anchor)
1965 var errcount = v.modelbuilder.toolcontext.error_count
1966 var candidate = v.try_get_mproperty_by_name2(self, msupertype, mproperty.name).as(nullable MMethod)
1967 if candidate == null then
1968 if v.modelbuilder.toolcontext.error_count > errcount then return # Forward error
1969 continue # Try next super-class
1970 end
1971 if superprop != null and candidate.is_root_init then
1972 continue
1973 end
1974 if superprop != null and superprop.mproperty != candidate and not superprop.mproperty.is_root_init then
1975 v.error(self, "Error: conflicting super constructor to call for `{mproperty}`: `{candidate.full_name}`, `{superprop.mproperty.full_name}`")
1976 return
1977 end
1978 var candidatedefs = candidate.lookup_definitions(v.mmodule, anchor)
1979 if superprop != null and superprop.mproperty == candidate then
1980 if superprop == candidatedefs.first then continue
1981 candidatedefs.add(superprop)
1982 end
1983 if candidatedefs.length > 1 then
1984 v.error(self, "Error: conflicting property definitions for property `{mproperty}` in `{recvtype}`: {candidatedefs.join(", ")}")
1985 return
1986 end
1987 superprop = candidatedefs.first
1988 end
1989 if superprop == null then
1990 v.error(self, "Error: no super method to call for `{mproperty}`.")
1991 return
1992 end
1993
1994 var msignature = superprop.new_msignature or else superprop.msignature.as(not null)
1995 msignature = v.resolve_for(msignature, recvtype, true).as(MSignature)
1996
1997 var callsite = new CallSite(hot_location, recvtype, v.mmodule, v.anchor, true, superprop.mproperty, superprop, msignature, false)
1998 self.callsite = callsite
1999
2000 var args = self.n_args.to_a
2001 if args.length > 0 then
2002 callsite.check_signature(v, self, args)
2003 else
2004 # Check there is at least enough parameters
2005 if mpropdef.msignature.arity < msignature.arity then
2006 v.error(self, "Error: not enough implicit arguments to pass. Got `{mpropdef.msignature.arity}`, expected at least `{msignature.arity}`. Signature is `{msignature}`.")
2007 return
2008 end
2009 # Check that each needed parameter is conform
2010 var i = 0
2011 for sp in msignature.mparameters do
2012 var p = mpropdef.msignature.mparameters[i]
2013 if not v.is_subtype(p.mtype, sp.mtype) then
2014 v.error(self, "Type Error: expected argument #{i} of type `{sp.mtype}`, got implicit argument `{p.name}` of type `{p.mtype}`. Signature is {msignature}")
2015 return
2016 end
2017 i += 1
2018 end
2019 end
2020
2021 self.is_typed = true
2022 end
2023 end
2024
2025 ####
2026
2027 redef class ANewExpr
2028 # The constructor invoked by the new.
2029 var callsite: nullable CallSite
2030
2031 # The designated type
2032 var recvtype: nullable MClassType
2033
2034 redef fun accept_typing(v)
2035 do
2036 var recvtype = v.resolve_mtype(self.n_type)
2037 if recvtype == null then return
2038
2039 if not recvtype isa MClassType then
2040 if recvtype isa MNullableType then
2041 v.error(self, "Type Error: cannot instantiate the nullable type `{recvtype}`.")
2042 return
2043 else if recvtype isa MFormalType then
2044 v.error(self, "Type Error: cannot instantiate the formal type `{recvtype}`.")
2045 return
2046 else
2047 v.error(self, "Type Error: cannot instantiate the type `{recvtype}`.")
2048 return
2049 end
2050 end
2051
2052 self.recvtype = recvtype
2053 var kind = recvtype.mclass.kind
2054
2055 var name: String
2056 var nqid = self.n_qid
2057 var node: ANode
2058 if nqid != null then
2059 name = nqid.n_id.text
2060 node = nqid
2061 else
2062 name = "new"
2063 node = self.n_kwnew
2064 end
2065 if name == "intern" then
2066 if kind != concrete_kind then
2067 v.error(self, "Type Error: cannot instantiate {kind} {recvtype}.")
2068 return
2069 end
2070 if n_args.n_exprs.not_empty then
2071 v.error(n_args, "Type Error: the intern constructor expects no arguments.")
2072 return
2073 end
2074 # Our job is done
2075 self.mtype = recvtype
2076 return
2077 end
2078
2079 var callsite = v.get_method(node, recvtype, name, false)
2080 if callsite == null then return
2081
2082 if not callsite.mproperty.is_new then
2083 if kind != concrete_kind then
2084 v.error(self, "Type Error: cannot instantiate {kind} `{recvtype}`.")
2085 return
2086 end
2087 self.mtype = recvtype
2088 else
2089 self.mtype = callsite.msignature.return_mtype
2090 assert self.mtype != null
2091 end
2092
2093 self.callsite = callsite
2094
2095 if not callsite.mproperty.is_init_for(recvtype.mclass) then
2096 v.error(self, "Error: `{name}` is not a constructor.")
2097 return
2098 end
2099
2100 var args = n_args.to_a
2101 callsite.check_signature(v, node, args)
2102 end
2103 end
2104
2105 ####
2106
2107 redef class AAttrFormExpr
2108 # The attribute accessed.
2109 var mproperty: nullable MAttribute
2110
2111 # The static type of the attribute.
2112 var attr_type: nullable MType
2113
2114 # Resolve the attribute accessed.
2115 private fun resolve_property(v: TypeVisitor)
2116 do
2117 var recvtype = v.visit_expr(self.n_expr)
2118 if recvtype == null then return # Skip error
2119 var node = self.n_id
2120 var name = node.text
2121 if recvtype isa MNullType then
2122 v.error(node, "Error: attribute `{name}` access on `null`.")
2123 return
2124 end
2125
2126 var unsafe_type = v.anchor_to(recvtype)
2127 var mproperty = v.try_get_mproperty_by_name2(node, unsafe_type, name)
2128 if mproperty == null then
2129 v.modelbuilder.error(node, "Error: attribute `{name}` does not exist in `{recvtype}`.")
2130 return
2131 end
2132 assert mproperty isa MAttribute
2133 self.mproperty = mproperty
2134
2135 var mpropdefs = mproperty.lookup_definitions(v.mmodule, unsafe_type)
2136 assert mpropdefs.length == 1
2137 var mpropdef = mpropdefs.first
2138 var attr_type = mpropdef.static_mtype
2139 if attr_type == null then return # skip error
2140 attr_type = v.resolve_for(attr_type, recvtype, self.n_expr isa ASelfExpr)
2141 self.attr_type = attr_type
2142 end
2143 end
2144
2145 redef class AAttrExpr
2146 redef fun accept_typing(v)
2147 do
2148 self.resolve_property(v)
2149 self.mtype = self.attr_type
2150 end
2151 end
2152
2153
2154 redef class AAttrAssignExpr
2155 redef fun accept_typing(v)
2156 do
2157 self.resolve_property(v)
2158 var mtype = self.attr_type
2159
2160 v.visit_expr_subtype(self.n_value, mtype)
2161 self.is_typed = mtype != null
2162 end
2163 end
2164
2165 redef class AAttrReassignExpr
2166 redef fun accept_typing(v)
2167 do
2168 self.resolve_property(v)
2169 var mtype = self.attr_type
2170 if mtype == null then return # Skip error
2171
2172 var rettype = self.resolve_reassignment(v, mtype, mtype)
2173
2174 self.is_typed = rettype != null
2175 end
2176 end
2177
2178 redef class AIssetAttrExpr
2179 redef fun accept_typing(v)
2180 do
2181 self.resolve_property(v)
2182 var mtype = self.attr_type
2183 if mtype == null then return # Skip error
2184
2185 var recvtype = self.n_expr.mtype.as(not null)
2186 var bound = v.resolve_for(mtype, recvtype, false)
2187 if bound isa MNullableType then
2188 v.error(n_id, "Type Error: `isset` on a nullable attribute.")
2189 end
2190 self.mtype = v.type_bool(self)
2191 end
2192 end
2193
2194 redef class AVarargExpr
2195 redef fun accept_typing(v)
2196 do
2197 # This kind of pseudo-expression can be only processed trough a signature
2198 # See `check_signature`
2199 # Other cases are a syntax error.
2200 v.error(self, "Syntax Error: unexpected `...`.")
2201 end
2202 end
2203
2204 ###
2205
2206 redef class ADebugTypeExpr
2207 redef fun accept_typing(v)
2208 do
2209 var expr = v.visit_expr(self.n_expr)
2210 if expr == null then return
2211 var unsafe = v.anchor_to(expr)
2212 var ntype = self.n_type
2213 var mtype = v.resolve_mtype(ntype)
2214 if mtype != null and mtype != expr then
2215 var umtype = v.anchor_to(mtype)
2216 v.modelbuilder.warning(self, "debug", "Found type {expr} (-> {unsafe}), expected {mtype} (-> {umtype})")
2217 end
2218 self.is_typed = true
2219 end
2220 end