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