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