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