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