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