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