typing: Add `do_typing` on AExpr
[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
1036 # Type the expression as if located in `visited_mpropdef`
1037 # `TypeVisitor` and `PostTypingVisitor` will be used to do the typing, see them for more information.
1038 #
1039 # `visited_mpropdef`: Correspond to the evaluation context in which the expression is located.
1040 fun do_typing(modelbuilder: ModelBuilder, visited_mpropdef: MPropDef)
1041 do
1042 var type_visitor = new TypeVisitor(modelbuilder, visited_mpropdef)
1043 type_visitor.visit_stmt(self)
1044 var post_visitor = new PostTypingVisitor(type_visitor)
1045 post_visitor.enter_visit(self)
1046 end
1047 end
1048
1049 redef class ABlockExpr
1050 redef fun accept_typing(v)
1051 do
1052 for e in self.n_expr do v.visit_stmt(e)
1053 self.is_typed = true
1054 end
1055
1056 # The type of a blockexpr is the one of the last expression (or null if empty)
1057 redef fun mtype
1058 do
1059 if self.n_expr.is_empty then return null
1060 return self.n_expr.last.mtype
1061 end
1062 end
1063
1064 redef class AVardeclExpr
1065 redef fun accept_typing(v)
1066 do
1067 var variable = self.variable
1068 if variable == null then return # Skip error
1069
1070 var ntype = self.n_type
1071 var mtype: nullable MType
1072 if ntype == null then
1073 mtype = null
1074 else
1075 mtype = v.resolve_mtype(ntype)
1076 if mtype == null then return # Skip error
1077 end
1078
1079 var nexpr = self.n_expr
1080 if nexpr != null then
1081 if mtype != null then
1082 var etype = v.visit_expr_subtype(nexpr, mtype)
1083 if etype == mtype then
1084 assert ntype != null
1085 v.modelbuilder.advice(ntype, "useless-type", "Warning: useless type definition for variable `{variable.name}`")
1086 end
1087 else
1088 mtype = v.visit_expr(nexpr)
1089 if mtype == null then return # Skip error
1090 end
1091 end
1092
1093 var decltype = mtype
1094 if mtype == null or mtype isa MNullType then
1095 var objclass = v.get_mclass(self, "Object")
1096 if objclass == null then return # skip error
1097 decltype = objclass.mclass_type.as_nullable
1098 if mtype == null then mtype = decltype
1099 end
1100
1101 variable.declared_type = decltype
1102 v.set_variable(self, variable, mtype)
1103
1104 #debug("var {variable}: {mtype}")
1105
1106 self.mtype = mtype
1107 self.is_typed = true
1108 end
1109 end
1110
1111 redef class AVarExpr
1112 redef fun its_variable do return self.variable
1113 redef fun accept_typing(v)
1114 do
1115 var variable = self.variable
1116 if variable == null then return # Skip error
1117
1118 var mtype = v.get_variable(self, variable)
1119 if mtype != null then
1120 #debug("{variable} is {mtype}")
1121 else
1122 #debug("{variable} is untyped")
1123 end
1124
1125 self.mtype = mtype
1126 end
1127 end
1128
1129 redef class AVarAssignExpr
1130 redef fun accept_typing(v)
1131 do
1132 var variable = self.variable
1133 assert variable != null
1134
1135 var mtype = v.visit_expr_subtype(n_value, variable.declared_type)
1136
1137 v.set_variable(self, variable, mtype)
1138
1139 self.is_typed = true
1140 end
1141 end
1142
1143 redef class AReassignFormExpr
1144 # The method designed by the reassign operator.
1145 var reassign_callsite: nullable CallSite
1146
1147 var read_type: nullable MType = null
1148
1149 # Determine the `reassign_property`
1150 # `readtype` is the type of the reading of the left value.
1151 # `writetype` is the type of the writing of the left value.
1152 # (Because of `ACallReassignExpr`, both can be different.
1153 # Return the static type of the value to store.
1154 private fun resolve_reassignment(v: TypeVisitor, readtype, writetype: MType): nullable MType
1155 do
1156 var reassign_name = self.n_assign_op.operator
1157
1158 self.read_type = readtype
1159
1160 var callsite = v.build_callsite_by_name(self.n_assign_op, readtype, reassign_name, false)
1161 if callsite == null then return null # Skip error
1162 self.reassign_callsite = callsite
1163
1164 var msignature = callsite.msignature
1165 var rettype = msignature.return_mtype
1166 assert msignature.arity == 1 and rettype != null
1167
1168 var value_type = v.visit_expr_subtype(self.n_value, msignature.mparameters.first.mtype)
1169 if value_type == null then return null # Skip error
1170
1171 v.check_subtype(self, rettype, writetype, false)
1172 return rettype
1173 end
1174 end
1175
1176 redef class AVarReassignExpr
1177 redef fun accept_typing(v)
1178 do
1179 var variable = self.variable
1180 assert variable != null
1181
1182 var readtype = v.get_variable(self, variable)
1183 if readtype == null then return
1184
1185 read_type = readtype
1186
1187 var writetype = variable.declared_type
1188 if writetype == null then return
1189
1190 var rettype = self.resolve_reassignment(v, readtype, writetype)
1191
1192 v.set_variable(self, variable, rettype)
1193
1194 self.is_typed = rettype != null
1195 end
1196 end
1197
1198 redef class AContinueExpr
1199 redef fun accept_typing(v)
1200 do
1201 var nexpr = self.n_expr
1202 if nexpr != null then
1203 v.visit_expr(nexpr)
1204 end
1205 self.is_typed = true
1206 end
1207 end
1208
1209 redef class ABreakExpr
1210 redef fun accept_typing(v)
1211 do
1212 var nexpr = self.n_expr
1213 if nexpr != null then
1214 v.visit_expr(nexpr)
1215 end
1216 self.is_typed = true
1217 end
1218 end
1219
1220 redef class AReturnExpr
1221 redef fun accept_typing(v)
1222 do
1223 var nexpr = self.n_expr
1224 var ret_type
1225 var mpropdef = v.mpropdef
1226 if mpropdef isa MMethodDef then
1227 ret_type = mpropdef.msignature.return_mtype
1228 else if mpropdef isa MAttributeDef then
1229 ret_type = mpropdef.static_mtype
1230 else
1231 abort
1232 end
1233 if nexpr != null then
1234 if ret_type != null then
1235 v.visit_expr_subtype(nexpr, ret_type)
1236 else
1237 v.visit_expr(nexpr)
1238 v.error(nexpr, "Error: `return` with value in a procedure.")
1239 return
1240 end
1241 else if ret_type != null then
1242 v.error(self, "Error: `return` without value in a function.")
1243 return
1244 end
1245 self.is_typed = true
1246 end
1247 end
1248
1249 redef class AAbortExpr
1250 redef fun accept_typing(v)
1251 do
1252 self.is_typed = true
1253 end
1254 end
1255
1256 redef class AIfExpr
1257 redef fun accept_typing(v)
1258 do
1259 v.visit_expr_bool(n_expr)
1260
1261 v.visit_stmt(n_then)
1262 v.visit_stmt(n_else)
1263
1264 self.is_typed = true
1265
1266 if n_then != null and n_else == null then
1267 self.mtype = n_then.mtype
1268 end
1269 end
1270 end
1271
1272 redef class AIfexprExpr
1273 redef fun accept_typing(v)
1274 do
1275 v.visit_expr_bool(n_expr)
1276
1277 var t1 = v.visit_expr(n_then)
1278 var t2 = v.visit_expr(n_else)
1279
1280 if t1 == null or t2 == null then
1281 return # Skip error
1282 end
1283
1284 var t = v.merge_types(self, [t1, t2])
1285 if t == null then
1286 v.error(self, "Type Error: ambiguous type `{t1}` vs `{t2}`.")
1287 end
1288 self.mtype = t
1289 end
1290 end
1291
1292 redef class ADoExpr
1293 redef fun accept_typing(v)
1294 do
1295 v.visit_stmt(n_block)
1296 v.visit_stmt(n_catch)
1297 self.is_typed = true
1298 end
1299 end
1300
1301 redef class AWhileExpr
1302 redef fun accept_typing(v)
1303 do
1304 v.has_loop = true
1305 v.visit_expr_bool(n_expr)
1306 v.visit_stmt(n_block)
1307 self.is_typed = true
1308 end
1309 end
1310
1311 redef class ALoopExpr
1312 redef fun accept_typing(v)
1313 do
1314 v.has_loop = true
1315 v.visit_stmt(n_block)
1316 self.is_typed = true
1317 end
1318 end
1319
1320 redef class AForExpr
1321 redef fun accept_typing(v)
1322 do
1323 v.has_loop = true
1324
1325 for g in n_groups do
1326 var mtype = v.visit_expr(g.n_expr)
1327 if mtype == null then return
1328 g.do_type_iterator(v, mtype)
1329 if g.is_broken then is_broken = true
1330 end
1331
1332 v.visit_stmt(n_block)
1333
1334 self.mtype = n_block.mtype
1335 self.is_typed = true
1336 end
1337 end
1338
1339 redef class AForGroup
1340 var coltype: nullable MClassType
1341
1342 var method_iterator: nullable CallSite
1343 var method_is_ok: nullable CallSite
1344 var method_item: nullable CallSite
1345 var method_next: nullable CallSite
1346 var method_key: nullable CallSite
1347 var method_finish: nullable CallSite
1348
1349 var method_lt: nullable CallSite
1350 var method_successor: nullable CallSite
1351
1352 private fun do_type_iterator(v: TypeVisitor, mtype: MType)
1353 do
1354 if mtype isa MNullType then
1355 v.error(self, "Type Error: `for` cannot iterate over `null`.")
1356 return
1357 end
1358
1359 # get obj class
1360 var objcla = v.get_mclass(self, "Object")
1361 if objcla == null then return
1362
1363 # check iterator method
1364 var itdef = v.build_callsite_by_name(self, mtype, "iterator", n_expr isa ASelfExpr)
1365 if itdef == null then
1366 v.error(self, "Type Error: `for` expects a type providing an `iterator` method, got `{mtype}`.")
1367 return
1368 end
1369 self.method_iterator = itdef
1370
1371 # check that iterator return something
1372 var ittype = itdef.msignature.return_mtype
1373 if ittype == null then
1374 v.error(self, "Type Error: `for` expects the method `iterator` to return an `Iterator` or `MapIterator` type.")
1375 return
1376 end
1377
1378 # get iterator type
1379 var colit_cla = v.try_get_mclass(self, "Iterator")
1380 var mapit_cla = v.try_get_mclass(self, "MapIterator")
1381 var is_col = false
1382 var is_map = false
1383
1384 if colit_cla != null and v.is_subtype(ittype, colit_cla.get_mtype([objcla.mclass_type.as_nullable])) then
1385 # Iterator
1386 var coltype = ittype.supertype_to(v.mmodule, v.anchor, colit_cla)
1387 var variables = self.variables
1388 if variables.length != 1 then
1389 v.error(self, "Type Error: `for` expects only one variable when using `Iterator`.")
1390 else
1391 variables.first.declared_type = coltype.arguments.first
1392 end
1393 is_col = true
1394 end
1395
1396 if mapit_cla != null and v.is_subtype(ittype, mapit_cla.get_mtype([objcla.mclass_type.as_nullable, objcla.mclass_type.as_nullable])) then
1397 # Map Iterator
1398 var coltype = ittype.supertype_to(v.mmodule, v.anchor, mapit_cla)
1399 var variables = self.variables
1400 if variables.length != 2 then
1401 v.error(self, "Type Error: `for` expects two variables when using `MapIterator`.")
1402 else
1403 variables[0].declared_type = coltype.arguments[0]
1404 variables[1].declared_type = coltype.arguments[1]
1405 end
1406 is_map = true
1407 end
1408
1409 if not is_col and not is_map then
1410 v.error(self, "Type Error: `for` expects the method `iterator` to return an `Iterator` or `MapIterator` type.")
1411 return
1412 end
1413
1414 # anchor formal and virtual types
1415 if mtype.need_anchor then mtype = v.anchor_to(mtype)
1416
1417 mtype = mtype.undecorate
1418 self.coltype = mtype.as(MClassType)
1419
1420 # get methods is_ok, next, item
1421 var ikdef = v.build_callsite_by_name(self, ittype, "is_ok", false)
1422 if ikdef == null then
1423 v.error(self, "Type Error: `for` expects a method `is_ok` in type `{ittype}`.")
1424 return
1425 end
1426 self.method_is_ok = ikdef
1427
1428 var itemdef = v.build_callsite_by_name(self, ittype, "item", false)
1429 if itemdef == null then
1430 v.error(self, "Type Error: `for` expects a method `item` in type `{ittype}`.")
1431 return
1432 end
1433 self.method_item = itemdef
1434
1435 var nextdef = v.build_callsite_by_name(self, ittype, "next", false)
1436 if nextdef == null then
1437 v.error(self, "Type Error: `for` expects a method `next` in type {ittype}.")
1438 return
1439 end
1440 self.method_next = nextdef
1441
1442 self.method_finish = v.try_build_callsite_by_name(self, ittype, "finish", false)
1443
1444 if is_map then
1445 var keydef = v.build_callsite_by_name(self, ittype, "key", false)
1446 if keydef == null then
1447 v.error(self, "Type Error: `for` expects a method `key` in type `{ittype}`.")
1448 return
1449 end
1450 self.method_key = keydef
1451 end
1452
1453 if self.variables.length == 1 and n_expr isa ARangeExpr then
1454 var variable = variables.first
1455 var vtype = variable.declared_type.as(not null)
1456
1457 if n_expr isa AOrangeExpr then
1458 self.method_lt = v.build_callsite_by_name(self, vtype, "<", false)
1459 else
1460 self.method_lt = v.build_callsite_by_name(self, vtype, "<=", false)
1461 end
1462
1463 self.method_successor = v.build_callsite_by_name(self, vtype, "successor", false)
1464 end
1465 end
1466 end
1467
1468 redef class AWithExpr
1469 var method_start: nullable CallSite
1470 var method_finish: nullable CallSite
1471
1472 redef fun accept_typing(v: TypeVisitor)
1473 do
1474 var mtype = v.visit_expr(n_expr)
1475 if mtype == null then return
1476
1477 method_start = v.build_callsite_by_name(self, mtype, "start", n_expr isa ASelfExpr)
1478 method_finish = v.build_callsite_by_name(self, mtype, "finish", n_expr isa ASelfExpr)
1479
1480 v.visit_stmt(n_block)
1481 self.mtype = n_block.mtype
1482 self.is_typed = true
1483 end
1484 end
1485
1486 redef class AAssertExpr
1487 redef fun accept_typing(v)
1488 do
1489 v.visit_expr_bool(n_expr)
1490
1491 v.visit_stmt(n_else)
1492 self.is_typed = true
1493 end
1494 end
1495
1496 redef class AOrExpr
1497 redef fun accept_typing(v)
1498 do
1499 v.visit_expr_bool(n_expr)
1500 v.visit_expr_bool(n_expr2)
1501 self.mtype = v.type_bool(self)
1502 end
1503 end
1504
1505 redef class AImpliesExpr
1506 redef fun accept_typing(v)
1507 do
1508 v.visit_expr_bool(n_expr)
1509 v.visit_expr_bool(n_expr2)
1510 self.mtype = v.type_bool(self)
1511 end
1512 end
1513
1514 redef class AAndExpr
1515 redef fun accept_typing(v)
1516 do
1517 v.visit_expr_bool(n_expr)
1518 v.visit_expr_bool(n_expr2)
1519 self.mtype = v.type_bool(self)
1520 end
1521 end
1522
1523 redef class ANotExpr
1524 redef fun accept_typing(v)
1525 do
1526 v.visit_expr_bool(n_expr)
1527 self.mtype = v.type_bool(self)
1528 end
1529 end
1530
1531 redef class AOrElseExpr
1532 redef fun accept_typing(v)
1533 do
1534 var t1 = v.visit_expr(n_expr)
1535 var t2 = v.visit_expr(n_expr2)
1536
1537 if t1 == null or t2 == null then
1538 return # Skip error
1539 end
1540
1541 if t1 isa MNullType then
1542 self.mtype = t2
1543 return
1544 else if v.can_be_null(t1) then
1545 t1 = t1.as_notnull
1546 end
1547
1548 var t = v.merge_types(self, [t1, t2])
1549 if t == null then
1550 var c = v.get_mclass(self, "Object")
1551 if c == null then return # forward error
1552 t = c.mclass_type
1553 if v.can_be_null(t2) then
1554 t = t.as_nullable
1555 end
1556 #v.error(self, "Type Error: ambiguous type {t1} vs {t2}")
1557 end
1558 self.mtype = t
1559 end
1560
1561 redef fun accept_post_typing(v)
1562 do
1563 var t1 = n_expr.mtype
1564 if t1 == null then
1565 return
1566 else
1567 v.check_can_be_null(n_expr, t1)
1568 end
1569 end
1570 end
1571
1572 redef class ATrueExpr
1573 redef fun accept_typing(v)
1574 do
1575 self.mtype = v.type_bool(self)
1576 end
1577 end
1578
1579 redef class AFalseExpr
1580 redef fun accept_typing(v)
1581 do
1582 self.mtype = v.type_bool(self)
1583 end
1584 end
1585
1586 redef class AIntegerExpr
1587 redef fun accept_typing(v)
1588 do
1589 var mclass: nullable MClass = null
1590 if value isa Byte then
1591 mclass = v.get_mclass(self, "Byte")
1592 else if value isa Int then
1593 mclass = v.get_mclass(self, "Int")
1594 else if value isa Int8 then
1595 mclass = v.get_mclass(self, "Int8")
1596 else if value isa Int16 then
1597 mclass = v.get_mclass(self, "Int16")
1598 else if value isa UInt16 then
1599 mclass = v.get_mclass(self, "UInt16")
1600 else if value isa Int32 then
1601 mclass = v.get_mclass(self, "Int32")
1602 else if value isa UInt32 then
1603 mclass = v.get_mclass(self, "UInt32")
1604 end
1605 if mclass == null then return # Forward error
1606 self.mtype = mclass.mclass_type
1607 end
1608 end
1609
1610 redef class AFloatExpr
1611 redef fun accept_typing(v)
1612 do
1613 var mclass = v.get_mclass(self, "Float")
1614 if mclass == null then return # Forward error
1615 self.mtype = mclass.mclass_type
1616 end
1617 end
1618
1619 redef class ACharExpr
1620 redef fun accept_typing(v) do
1621 var mclass: nullable MClass = null
1622 if is_code_point then
1623 mclass = v.get_mclass(self, "Int")
1624 else
1625 mclass = v.get_mclass(self, "Char")
1626 end
1627 if mclass == null then return # Forward error
1628 self.mtype = mclass.mclass_type
1629 end
1630 end
1631
1632 redef class AugmentedStringFormExpr
1633 super AExpr
1634
1635 # Text::to_re, used for prefix `re`
1636 var to_re: nullable CallSite = null
1637 # Regex::ignore_case, used for suffix `i` on `re`
1638 var ignore_case: nullable CallSite = null
1639 # Regex::newline, used for suffix `m` on `re`
1640 var newline: nullable CallSite = null
1641 # Regex::extended, used for suffix `b` on `re`
1642 var extended: nullable CallSite = null
1643 # CString::to_bytes_with_copy, used for prefix `b`
1644 var to_bytes_with_copy: nullable CallSite = null
1645
1646 redef fun accept_typing(v) do
1647 var mclass = v.get_mclass(self, "String")
1648 if mclass == null then return # Forward error
1649 if is_bytestring then
1650 to_bytes_with_copy = v.build_callsite_by_name(self, v.mmodule.c_string_type, "to_bytes_with_copy", false)
1651 mclass = v.get_mclass(self, "Bytes")
1652 else if is_re then
1653 to_re = v.build_callsite_by_name(self, mclass.mclass_type, "to_re", false)
1654 for i in suffix.chars do
1655 mclass = v.get_mclass(self, "Regex")
1656 if mclass == null then
1657 v.error(self, "Error: `Regex` class unknown")
1658 return
1659 end
1660 var service = ""
1661 if i == 'i' then
1662 service = "ignore_case="
1663 ignore_case = v.build_callsite_by_name(self, mclass.mclass_type, service, false)
1664 else if i == 'm' then
1665 service = "newline="
1666 newline = v.build_callsite_by_name(self, mclass.mclass_type, service, false)
1667 else if i == 'b' then
1668 service = "extended="
1669 extended = v.build_callsite_by_name(self, mclass.mclass_type, service, false)
1670 else
1671 v.error(self, "Type Error: Unrecognized suffix {i} in prefixed Regex")
1672 abort
1673 end
1674 end
1675 end
1676 if mclass == null then return # Forward error
1677 mtype = mclass.mclass_type
1678 end
1679 end
1680
1681 redef class ASuperstringExpr
1682 redef fun accept_typing(v)
1683 do
1684 super
1685 var objclass = v.get_mclass(self, "Object")
1686 if objclass == null then return # Forward error
1687 var objtype = objclass.mclass_type
1688 for nexpr in self.n_exprs do
1689 v.visit_expr_subtype(nexpr, objtype)
1690 end
1691 end
1692 end
1693
1694 redef class AArrayExpr
1695 # The `with_capacity` method on Array
1696 var with_capacity_callsite: nullable CallSite
1697
1698 # The `push` method on arrays
1699 var push_callsite: nullable CallSite
1700
1701 # The element of each type
1702 var element_mtype: nullable MType
1703
1704 # Set that `self` is a part of comprehension array `na`
1705 # If `self` is a `for`, or a `if`, then `set_comprehension` is recursively applied.
1706 private fun set_comprehension(n: nullable AExpr)
1707 do
1708 if n == null then
1709 return
1710 else if n isa AForExpr then
1711 set_comprehension(n.n_block)
1712 else if n isa AIfExpr then
1713 set_comprehension(n.n_then)
1714 set_comprehension(n.n_else)
1715 else
1716 # is a leave
1717 n.comprehension = self
1718 end
1719 end
1720 redef fun accept_typing(v)
1721 do
1722 var mtype: nullable MType = null
1723 var ntype = self.n_type
1724 if ntype != null then
1725 mtype = v.resolve_mtype(ntype)
1726 if mtype == null then return # Skip error
1727 end
1728 var mtypes = new Array[nullable MType]
1729 var useless = false
1730 for e in self.n_exprs do
1731 var t = v.visit_expr(e)
1732 if t == null then
1733 return # Skip error
1734 end
1735 set_comprehension(e)
1736 if mtype != null then
1737 if v.check_subtype(e, t, mtype, false) == null then return # Forward error
1738 if t == mtype then useless = true
1739 else
1740 mtypes.add(t)
1741 end
1742 end
1743 if mtype == null then
1744 # Ensure monotony for type adaptation on loops
1745 if self.element_mtype != null then mtypes.add self.element_mtype
1746 mtype = v.merge_types(self, mtypes)
1747 end
1748 if mtype == null or mtype isa MNullType then
1749 v.error(self, "Type Error: ambiguous array type {mtypes.join(" ")}")
1750 return
1751 end
1752 if useless then
1753 assert ntype != null
1754 v.modelbuilder.warning(ntype, "useless-type", "Warning: useless type declaration `{mtype}` in literal Array since it can be inferred from the elements type.")
1755 end
1756
1757 self.element_mtype = mtype
1758
1759 var mclass = v.get_mclass(self, "Array")
1760 if mclass == null then return # Forward error
1761 var array_mtype = mclass.get_mtype([mtype])
1762
1763 with_capacity_callsite = v.build_callsite_by_name(self, array_mtype, "with_capacity", false)
1764 push_callsite = v.build_callsite_by_name(self, array_mtype, "push", false)
1765
1766 self.mtype = array_mtype
1767 end
1768 end
1769
1770 redef class ARangeExpr
1771 var init_callsite: nullable CallSite
1772
1773 redef fun accept_typing(v)
1774 do
1775 var discrete_class = v.get_mclass(self, "Discrete")
1776 if discrete_class == null then return # Forward error
1777 var discrete_type = discrete_class.intro.bound_mtype
1778 var t1 = v.visit_expr_subtype(self.n_expr, discrete_type)
1779 var t2 = v.visit_expr_subtype(self.n_expr2, discrete_type)
1780 if t1 == null or t2 == null then return
1781 var mclass = v.get_mclass(self, "Range")
1782 if mclass == null then return # Forward error
1783 var mtype
1784 if v.is_subtype(t1, t2) then
1785 mtype = mclass.get_mtype([t2])
1786 else if v.is_subtype(t2, t1) then
1787 mtype = mclass.get_mtype([t1])
1788 else
1789 v.error(self, "Type Error: cannot create range: `{t1}` vs `{t2}`.")
1790 return
1791 end
1792
1793 self.mtype = mtype
1794
1795 # get the constructor
1796 var callsite
1797 if self isa ACrangeExpr then
1798 callsite = v.build_callsite_by_name(self, mtype, "defaultinit", false)
1799 else if self isa AOrangeExpr then
1800 callsite = v.build_callsite_by_name(self, mtype, "without_last", false)
1801 else
1802 abort
1803 end
1804 init_callsite = callsite
1805 end
1806 end
1807
1808 redef class ANullExpr
1809 redef fun accept_typing(v)
1810 do
1811 self.mtype = v.mmodule.model.null_type
1812 end
1813 end
1814
1815 redef class AIsaExpr
1816 # The static type to cast to.
1817 # (different from the static type of the expression that is `Bool`).
1818 var cast_type: nullable MType
1819 redef fun accept_typing(v)
1820 do
1821 v.visit_expr(n_expr)
1822
1823 var mtype = v.resolve_mtype(n_type)
1824
1825 self.cast_type = mtype
1826
1827 var variable = self.n_expr.its_variable
1828 if variable != null then
1829 var orig = self.n_expr.mtype
1830 #var from = if orig != null then orig.to_s else "invalid"
1831 #var to = if mtype != null then mtype.to_s else "invalid"
1832 #debug("adapt {variable}: {from} -> {to}")
1833
1834 var thentype = v.intersect_types(self, orig, mtype)
1835 if thentype != orig then
1836 self.after_flow_context.when_true.set_var(v, variable, thentype)
1837 #debug "{variable}:{orig or else "?"} isa {mtype or else "?"} -> then {thentype or else "?"}"
1838 end
1839
1840 var elsetype = v.diff_types(self, orig, mtype)
1841 if elsetype != orig then
1842 self.after_flow_context.when_false.set_var(v, variable, elsetype)
1843 #debug "{variable}:{orig or else "?"} isa {mtype or else "?"} -> else {elsetype or else "?"}"
1844 end
1845 end
1846
1847 self.mtype = v.type_bool(self)
1848 end
1849
1850 redef fun accept_post_typing(v)
1851 do
1852 v.check_expr_cast(self, self.n_expr, self.n_type)
1853 end
1854
1855 redef fun dump_info(v) do
1856 var res = super
1857 var mtype = self.cast_type
1858 if mtype != null then
1859 res += v.yellow(".as({mtype})")
1860 end
1861 return res
1862 end
1863
1864 end
1865
1866 redef class AAsCastExpr
1867 redef fun accept_typing(v)
1868 do
1869 v.visit_expr(n_expr)
1870
1871 self.mtype = v.resolve_mtype(n_type)
1872 end
1873
1874 redef fun accept_post_typing(v)
1875 do
1876 v.check_expr_cast(self, self.n_expr, self.n_type)
1877 end
1878 end
1879
1880 redef class AAsNotnullExpr
1881 redef fun accept_typing(v)
1882 do
1883 var mtype = v.visit_expr(self.n_expr)
1884 if mtype == null then return # Forward error
1885
1886 if mtype isa MNullType then
1887 v.error(self, "Type Error: `as(not null)` on `null`.")
1888 return
1889 end
1890
1891 if v.can_be_null(mtype) then
1892 mtype = mtype.as_notnull
1893 end
1894
1895 self.mtype = mtype
1896 end
1897
1898 redef fun accept_post_typing(v)
1899 do
1900 var mtype = n_expr.mtype
1901 if mtype == null then return
1902 v.check_can_be_null(n_expr, mtype)
1903 end
1904 end
1905
1906 redef class AParExpr
1907 redef fun accept_typing(v)
1908 do
1909 self.mtype = v.visit_expr(self.n_expr)
1910 end
1911 end
1912
1913 redef class AOnceExpr
1914 redef fun accept_typing(v)
1915 do
1916 self.mtype = v.visit_expr(self.n_expr)
1917 end
1918 end
1919
1920 redef class ASelfExpr
1921 redef var its_variable: nullable Variable
1922 redef fun accept_typing(v)
1923 do
1924 if v.is_toplevel_context and not self isa AImplicitSelfExpr then
1925 v.error(self, "Error: `self` cannot be used in top-level method.")
1926 end
1927 var variable = v.selfvariable
1928 self.its_variable = variable
1929 self.mtype = v.get_variable(self, variable)
1930 end
1931 end
1932
1933 redef class AImplicitSelfExpr
1934 # Is the implicit receiver `sys`?
1935 #
1936 # By default, the implicit receiver is `self`.
1937 # But when there is not method for `self`, `sys` is used as a fall-back.
1938 # Is this case this flag is set to `true`.
1939 var is_sys = false
1940 end
1941
1942 ## MESSAGE SENDING AND PROPERTY
1943
1944 redef class ASendExpr
1945 # The property invoked by the send.
1946 var callsite: nullable CallSite
1947
1948 # Is self a safe call (with `x?.foo`)?
1949 # If so and the receiver is null, then the arguments won't be evaluated
1950 # and the call skipped (replaced with null).
1951 var is_safe: Bool = false
1952
1953 redef fun bad_expr_message(child)
1954 do
1955 if child == self.n_expr then
1956 return "to be the receiver of `{self.property_name}`"
1957 end
1958 return null
1959 end
1960
1961 redef fun accept_typing(v)
1962 do
1963 var nrecv = self.n_expr
1964 var recvtype = v.visit_expr(nrecv)
1965
1966 if nrecv isa ASafeExpr then
1967 # Has the receiver the form `x?.foo`?
1968 # For parsing "reasons" the `?` is in the receiver node, not the call node.
1969 is_safe = true
1970 end
1971
1972 var name = self.property_name
1973 var node = self.property_node
1974
1975 if recvtype == null then return # Forward error
1976
1977 var callsite = null
1978 var unsafe_type = v.anchor_to(recvtype)
1979 var mproperty = v.try_get_mproperty_by_name2(node, unsafe_type, name)
1980 if mproperty == null and nrecv isa AImplicitSelfExpr then
1981 # Special fall-back search in `sys` when noting found in the implicit receiver.
1982 var sysclass = v.try_get_mclass(node, "Sys")
1983 if sysclass != null then
1984 var systype = sysclass.mclass_type
1985 mproperty = v.try_get_mproperty_by_name2(node, systype, name)
1986 if mproperty != null then
1987 callsite = v.build_callsite_by_name(node, systype, name, false)
1988 if callsite == null then return # Forward error
1989 # Update information, we are looking at `sys` now, not `self`
1990 nrecv.is_sys = true
1991 nrecv.its_variable = null
1992 nrecv.mtype = systype
1993 recvtype = systype
1994 end
1995 end
1996 end
1997 if callsite == null then
1998 # If still nothing, just exit
1999 callsite = v.build_callsite_by_name(node, recvtype, name, nrecv isa ASelfExpr)
2000 if callsite == null then return
2001 end
2002
2003 self.callsite = callsite
2004 var msignature = callsite.msignature
2005
2006 var args = compute_raw_arguments
2007
2008 if not self isa ACallrefExpr then
2009 callsite.check_signature(v, node, args)
2010 end
2011
2012 if callsite.mproperty.is_init then
2013 var vmpropdef = v.mpropdef
2014 if not (vmpropdef isa MMethodDef and vmpropdef.mproperty.is_init) then
2015 v.error(node, "Error: an `init` can only be called from another `init`.")
2016 end
2017 if vmpropdef isa MMethodDef and vmpropdef.mproperty.is_root_init and not callsite.mproperty.is_root_init then
2018 v.error(node, "Error: `{vmpropdef}` cannot call a factory `{callsite.mproperty}`.")
2019 end
2020 end
2021
2022 var ret = msignature.return_mtype
2023 if ret != null then
2024 if is_safe then
2025 # A safe receiver makes that the call is not executed and returns null
2026 ret = ret.as_nullable
2027 end
2028 self.mtype = ret
2029 else
2030 self.is_typed = true
2031 end
2032 end
2033
2034 # The name of the property
2035 # Each subclass simply provide the correct name.
2036 private fun property_name: String is abstract
2037
2038 # The node identifying the name (id, operator, etc) for messages.
2039 #
2040 # Is `self` by default
2041 private fun property_node: ANode do return self
2042
2043 # An array of all arguments (excluding self)
2044 fun raw_arguments: Array[AExpr] do return compute_raw_arguments
2045
2046 private fun compute_raw_arguments: Array[AExpr] is abstract
2047
2048 redef fun dump_info(v) do
2049 var res = super
2050 var callsite = self.callsite
2051 if callsite != null then
2052 res += v.yellow(" call="+callsite.dump_info(v))
2053 end
2054 return res
2055 end
2056 end
2057
2058 redef class ABinopExpr
2059 redef fun compute_raw_arguments do return [n_expr2]
2060 redef fun property_name do return operator
2061 redef fun property_node do return n_op
2062 end
2063
2064 redef class AEqFormExpr
2065 redef fun accept_typing(v)
2066 do
2067 super
2068 v.null_test(self)
2069 end
2070
2071 redef fun accept_post_typing(v)
2072 do
2073 var mtype = n_expr.mtype
2074 var mtype2 = n_expr2.mtype
2075
2076 if mtype == null or mtype2 == null then return
2077
2078 if mtype == v.type_bool(self) and (n_expr2 isa AFalseExpr or n_expr2 isa ATrueExpr) then
2079 v.modelbuilder.warning(self, "useless-truism", "Warning: useless comparison to a Bool literal.")
2080 end
2081
2082 if not mtype2 isa MNullType then return
2083
2084 v.check_can_be_null(n_expr, mtype)
2085 end
2086 end
2087
2088 redef class AUnaryopExpr
2089 redef fun property_name do return "unary {operator}"
2090 redef fun compute_raw_arguments do return new Array[AExpr]
2091 end
2092
2093 redef class ACallExpr
2094 redef fun property_name do return n_qid.n_id.text
2095 redef fun property_node do return n_qid
2096 redef fun compute_raw_arguments do return n_args.to_a
2097 end
2098
2099 redef class ACallAssignExpr
2100 redef fun property_name do return n_qid.n_id.text + "="
2101 redef fun property_node do return n_qid
2102 redef fun compute_raw_arguments
2103 do
2104 var res = n_args.to_a
2105 res.add(n_value)
2106 return res
2107 end
2108 end
2109
2110 redef class ABraExpr
2111 redef fun property_name do return "[]"
2112 redef fun compute_raw_arguments do return n_args.to_a
2113 end
2114
2115 redef class ABraAssignExpr
2116 redef fun property_name do return "[]="
2117 redef fun compute_raw_arguments
2118 do
2119 var res = n_args.to_a
2120 res.add(n_value)
2121 return res
2122 end
2123 end
2124
2125 redef class ASendReassignFormExpr
2126 # The property invoked for the writing
2127 var write_callsite: nullable CallSite
2128
2129 redef fun accept_typing(v)
2130 do
2131 var recvtype = v.visit_expr(self.n_expr)
2132 var name = self.property_name
2133 var node = self.property_node
2134
2135 if recvtype == null then return # Forward error
2136
2137 var for_self = self.n_expr isa ASelfExpr
2138 var callsite = v.build_callsite_by_name(node, recvtype, name, for_self)
2139
2140 if callsite == null then return
2141 self.callsite = callsite
2142
2143 var args = compute_raw_arguments
2144
2145 callsite.check_signature(v, node, args)
2146
2147 var readtype = callsite.msignature.return_mtype
2148 if readtype == null then
2149 v.error(node, "Error: `{name}` is not a function.")
2150 return
2151 end
2152
2153 var wcallsite = v.build_callsite_by_name(node, recvtype, name + "=", self.n_expr isa ASelfExpr)
2154 if wcallsite == null then return
2155 self.write_callsite = wcallsite
2156
2157 var wtype = self.resolve_reassignment(v, readtype, wcallsite.msignature.mparameters.last.mtype)
2158 if wtype == null then return
2159
2160 args = args.to_a # duplicate so raw_arguments keeps only the getter args
2161 args.add(self.n_value)
2162 wcallsite.check_signature(v, node, args)
2163
2164 self.is_typed = true
2165 end
2166 end
2167
2168 redef class ACallReassignExpr
2169 redef fun property_name do return n_qid.n_id.text
2170 redef fun property_node do return n_qid.n_id
2171 redef fun compute_raw_arguments do return n_args.to_a
2172 end
2173
2174 redef class ABraReassignExpr
2175 redef fun property_name do return "[]"
2176 redef fun compute_raw_arguments do return n_args.to_a
2177 end
2178
2179 redef class AInitExpr
2180 redef fun property_name do if n_args.n_exprs.is_empty then return "init" else return "defaultinit"
2181 redef fun property_node do return n_kwinit
2182 redef fun compute_raw_arguments do return n_args.to_a
2183 end
2184
2185 redef class ACallrefExpr
2186 redef fun property_name do return n_qid.n_id.text
2187 redef fun property_node do return n_qid
2188 redef fun compute_raw_arguments do return n_args.to_a
2189
2190 redef fun accept_typing(v)
2191 do
2192 super # do the job as if it was a real call
2193 var res = callsite.mproperty
2194
2195 var msignature = callsite.mpropdef.msignature
2196 var recv = callsite.recv
2197 assert msignature != null
2198 var arity = msignature.mparameters.length
2199
2200 var routine_type_name = "ProcRef"
2201 if msignature.return_mtype != null then
2202 routine_type_name = "FunRef"
2203 end
2204
2205 var target_routine_class = "{routine_type_name}{arity}"
2206 var routine_mclass = v.get_mclass(self, target_routine_class)
2207
2208 if routine_mclass == null then
2209 v.error(self, "Error: missing functional types, try `import functional`")
2210 return
2211 end
2212
2213 var types_list = new Array[MType]
2214 for param in msignature.mparameters do
2215 if param.is_vararg then
2216 types_list.push(v.mmodule.array_type(param.mtype))
2217 else
2218 types_list.push(param.mtype)
2219 end
2220 end
2221 if msignature.return_mtype != null then
2222 types_list.push(msignature.return_mtype.as(not null))
2223 end
2224
2225 # Why we need an anchor :
2226 #
2227 # ~~~~nitish
2228 # class A[E]
2229 # def toto(x: E) do print "{x}"
2230 # end
2231 #
2232 # var a = new A[Int]
2233 # var f = &a.toto # without anchor : ProcRef1[E]
2234 # # with anchor : ProcRef[Int]
2235 # ~~~~
2236 # However, we can only anchor if we can resolve every formal
2237 # parameter, here's an example where we can't.
2238 # ~~~~nitish
2239 # class A[E]
2240 # fun bar: A[E] do return self
2241 # fun foo: Fun0[A[E]] do return &bar # here we can't anchor
2242 # end
2243 # var f1 = a1.foo # when this expression will be evaluated,
2244 # # `a1` will anchor `&bar` returned by `foo`.
2245 # print f1.call
2246 # ~~~~
2247 var routine_type = routine_mclass.get_mtype(types_list)
2248 if not recv.need_anchor then
2249 routine_type = routine_type.anchor_to(v.mmodule, recv.as(MClassType))
2250 end
2251 is_typed = true
2252 self.mtype = routine_type
2253 end
2254 end
2255
2256 redef class AExprs
2257 fun to_a: Array[AExpr] do return self.n_exprs.to_a
2258 end
2259
2260 ###
2261
2262 redef class ASuperExpr
2263 # The method to call if the super is in fact a 'super init call'
2264 # Note: if the super is a normal call-next-method, then this attribute is null
2265 var callsite: nullable CallSite
2266
2267 # The method to call is the super is a standard `call-next-method` super-call
2268 # Note: if the super is a special super-init-call, then this attribute is null
2269 var mpropdef: nullable MMethodDef
2270
2271 redef fun accept_typing(v)
2272 do
2273 var anchor = v.anchor
2274 var recvtype = v.get_variable(self, v.selfvariable)
2275 assert recvtype != null
2276 var mproperty = v.mpropdef.mproperty
2277 if not mproperty isa MMethod then
2278 v.error(self, "Error: `super` only usable in a `method`.")
2279 return
2280 end
2281 var superprops = mproperty.lookup_super_definitions(v.mmodule, anchor)
2282 if superprops.length == 0 then
2283 if mproperty.is_init and v.mpropdef.is_intro then
2284 process_superinit(v)
2285 return
2286 end
2287 v.error(self, "Error: no super method to call for `{mproperty}`.")
2288 return
2289 end
2290 # FIXME: covariance of return type in linear extension?
2291 var superprop = superprops.first
2292
2293 var msignature = superprop.msignature.as(not null)
2294 msignature = v.resolve_for(msignature, recvtype, true).as(MSignature)
2295 var args = self.n_args.to_a
2296 if args.length > 0 then
2297 signaturemap = v.check_signature(self, args, mproperty, msignature)
2298 end
2299 self.mtype = msignature.return_mtype
2300 self.is_typed = true
2301 v.mpropdef.has_supercall = true
2302 mpropdef = v.mpropdef.as(MMethodDef)
2303 end
2304
2305 # The mapping used on the call to associate arguments to parameters.
2306 # If null then no specific association is required.
2307 var signaturemap: nullable SignatureMap
2308
2309 private fun process_superinit(v: TypeVisitor)
2310 do
2311 var anchor = v.anchor
2312 var recvtype = v.get_variable(self, v.selfvariable)
2313 assert recvtype != null
2314 var mpropdef = v.mpropdef
2315 assert mpropdef isa MMethodDef
2316 var mproperty = mpropdef.mproperty
2317 var superprop: nullable MMethodDef = null
2318 for msupertype in mpropdef.mclassdef.supertypes do
2319 msupertype = msupertype.anchor_to(v.mmodule, anchor)
2320 var errcount = v.modelbuilder.toolcontext.error_count
2321 var candidate = v.try_get_mproperty_by_name2(self, msupertype, mproperty.name).as(nullable MMethod)
2322 if candidate == null then
2323 if v.modelbuilder.toolcontext.error_count > errcount then return # Forward error
2324 continue # Try next super-class
2325 end
2326 if superprop != null and candidate.is_root_init then
2327 continue
2328 end
2329 if superprop != null and superprop.mproperty != candidate and not superprop.mproperty.is_root_init then
2330 v.error(self, "Error: conflicting super constructor to call for `{mproperty}`: `{candidate.full_name}`, `{superprop.mproperty.full_name}`")
2331 return
2332 end
2333 var candidatedefs = candidate.lookup_definitions(v.mmodule, anchor)
2334 if superprop != null and superprop.mproperty == candidate then
2335 if superprop == candidatedefs.first then continue
2336 candidatedefs.add(superprop)
2337 end
2338 if candidatedefs.length > 1 then
2339 v.error(self, "Error: conflicting property definitions for property `{mproperty}` in `{recvtype}`: {candidatedefs.join(", ")}")
2340 return
2341 end
2342 superprop = candidatedefs.first
2343 end
2344 if superprop == null then
2345 v.error(self, "Error: no super method to call for `{mproperty}`.")
2346 return
2347 end
2348
2349 var msignature = superprop.msignature.as(not null)
2350 msignature = v.resolve_for(msignature, recvtype, true).as(MSignature)
2351
2352 var callsite = new CallSite(hot_location, recvtype, v.mmodule, v.anchor, true, superprop.mproperty, superprop, msignature, false)
2353 self.callsite = callsite
2354
2355 var args = self.n_args.to_a
2356 if args.length > 0 then
2357 callsite.check_signature(v, self, args)
2358 else
2359 # Check there is at least enough parameters
2360 if mpropdef.msignature.arity < msignature.arity then
2361 v.error(self, "Error: not enough implicit arguments to pass. Got `{mpropdef.msignature.arity}`, expected at least `{msignature.arity}`. Signature is `{msignature}`.")
2362 return
2363 end
2364 # Check that each needed parameter is conform
2365 var i = 0
2366 for sp in msignature.mparameters do
2367 var p = mpropdef.msignature.mparameters[i]
2368 if not v.is_subtype(p.mtype, sp.mtype) then
2369 v.error(self, "Type Error: expected argument #{i} of type `{sp.mtype}`, got implicit argument `{p.name}` of type `{p.mtype}`. Signature is {msignature}")
2370 return
2371 end
2372 i += 1
2373 end
2374 end
2375
2376 self.is_typed = true
2377 end
2378
2379 redef fun dump_info(v) do
2380 var res = super
2381 var callsite = self.callsite
2382 if callsite != null then
2383 res += v.yellow(" super-init="+callsite.dump_info(v))
2384 end
2385 var mpropdef = self.mpropdef
2386 if mpropdef != null then
2387 res += v.yellow(" call-next-method="+mpropdef.to_s)
2388 end
2389 return res
2390 end
2391 end
2392
2393 ####
2394
2395 redef class ANewExpr
2396 # The constructor invoked by the new.
2397 var callsite: nullable CallSite
2398
2399 # The designated type
2400 var recvtype: nullable MClassType
2401
2402 redef fun accept_typing(v)
2403 do
2404 var recvtype = v.resolve_mtype(self.n_type)
2405 if recvtype == null then return
2406
2407 if not recvtype isa MClassType then
2408 if recvtype isa MNullableType then
2409 v.error(self, "Type Error: cannot instantiate the nullable type `{recvtype}`.")
2410 return
2411 else if recvtype isa MFormalType then
2412 v.error(self, "Type Error: cannot instantiate the formal type `{recvtype}`.")
2413 return
2414 else
2415 v.error(self, "Type Error: cannot instantiate the type `{recvtype}`.")
2416 return
2417 end
2418 end
2419
2420 self.recvtype = recvtype
2421 var kind = recvtype.mclass.kind
2422
2423 var name: String
2424 var nqid = self.n_qid
2425 var node: ANode
2426 if nqid != null then
2427 name = nqid.n_id.text
2428 node = nqid
2429 else
2430 name = "new"
2431 node = self.n_kwnew
2432 end
2433 if name == "intern" then
2434 if kind != concrete_kind then
2435 v.error(self, "Type Error: cannot instantiate {kind} {recvtype}.")
2436 return
2437 end
2438 if n_args.n_exprs.not_empty then
2439 v.error(n_args, "Type Error: the intern constructor expects no arguments.")
2440 return
2441 end
2442 # Our job is done
2443 self.mtype = recvtype
2444 return
2445 end
2446
2447 var callsite = v.build_callsite_by_name(node, recvtype, name, false)
2448 if callsite == null then return
2449
2450 if not callsite.mproperty.is_new then
2451 if kind != concrete_kind then
2452 v.error(self, "Type Error: cannot instantiate {kind} `{recvtype}`.")
2453 return
2454 end
2455 self.mtype = recvtype
2456 else
2457 self.mtype = callsite.msignature.return_mtype
2458 assert self.mtype != null
2459 end
2460
2461 self.callsite = callsite
2462
2463 if not callsite.mproperty.is_init_for(recvtype.mclass) then
2464 v.error(self, "Error: `{name}` is not a constructor.")
2465 return
2466 end
2467
2468 var args = n_args.to_a
2469 callsite.check_signature(v, node, args)
2470 end
2471
2472 redef fun dump_info(v) do
2473 var res = super
2474 var callsite = self.callsite
2475 if callsite != null then
2476 res += v.yellow(" call="+callsite.dump_info(v))
2477 end
2478 return res
2479 end
2480 end
2481
2482 ####
2483
2484 redef class AAttrFormExpr
2485 # The attribute accessed.
2486 var mproperty: nullable MAttribute
2487
2488 # The static type of the attribute.
2489 var attr_type: nullable MType
2490
2491 # Resolve the attribute accessed.
2492 private fun resolve_property(v: TypeVisitor)
2493 do
2494 var recvtype = v.visit_expr(self.n_expr)
2495 if recvtype == null then return # Skip error
2496 var node = self.n_id
2497 var name = node.text
2498 if recvtype isa MNullType then
2499 v.error(node, "Error: attribute `{name}` access on `null`.")
2500 return
2501 end
2502
2503 var unsafe_type = v.anchor_to(recvtype)
2504 var mproperty = v.try_get_mproperty_by_name2(node, unsafe_type, name)
2505 if mproperty == null then
2506 v.modelbuilder.error(node, "Error: attribute `{name}` does not exist in `{recvtype}`.")
2507 return
2508 end
2509 assert mproperty isa MAttribute
2510 self.mproperty = mproperty
2511
2512 var mpropdefs = mproperty.lookup_definitions(v.mmodule, unsafe_type)
2513 assert mpropdefs.length == 1
2514 var mpropdef = mpropdefs.first
2515 var attr_type = mpropdef.static_mtype
2516 if attr_type == null then return # skip error
2517 attr_type = v.resolve_for(attr_type, recvtype, self.n_expr isa ASelfExpr)
2518 self.attr_type = attr_type
2519 end
2520
2521 redef fun dump_info(v) do
2522 var res = super
2523 var mproperty = self.mproperty
2524 var attr_type = self.attr_type
2525 if mproperty != null then
2526 res += v.yellow(" attr={mproperty}:{attr_type or else "BROKEN"}")
2527 end
2528 return res
2529 end
2530 end
2531
2532 redef class AAttrExpr
2533 redef fun accept_typing(v)
2534 do
2535 self.resolve_property(v)
2536 self.mtype = self.attr_type
2537 end
2538 end
2539
2540 redef class AAttrAssignExpr
2541 redef fun accept_typing(v)
2542 do
2543 self.resolve_property(v)
2544 var mtype = self.attr_type
2545
2546 v.visit_expr_subtype(self.n_value, mtype)
2547 self.is_typed = mtype != null
2548 end
2549 end
2550
2551 redef class AAttrReassignExpr
2552 redef fun accept_typing(v)
2553 do
2554 self.resolve_property(v)
2555 var mtype = self.attr_type
2556 if mtype == null then return # Skip error
2557
2558 var rettype = self.resolve_reassignment(v, mtype, mtype)
2559
2560 self.is_typed = rettype != null
2561 end
2562 end
2563
2564 redef class AIssetAttrExpr
2565 redef fun accept_typing(v)
2566 do
2567 self.resolve_property(v)
2568 var mtype = self.attr_type
2569 if mtype == null then return # Skip error
2570
2571 var recvtype = self.n_expr.mtype.as(not null)
2572 var bound = v.resolve_for(mtype, recvtype, false)
2573 if bound isa MNullableType then
2574 v.error(n_id, "Type Error: `isset` on a nullable attribute.")
2575 end
2576 self.mtype = v.type_bool(self)
2577 end
2578 end
2579
2580 redef class ASafeExpr
2581 redef fun accept_typing(v)
2582 do
2583 var mtype = v.visit_expr(n_expr)
2584 if mtype == null then return # Skip error
2585
2586 if mtype isa MNullType then
2587 # While `null?.foo` is semantically well defined and should not execute `foo` and just return `null`,
2588 # currently `null.foo` is forbidden so it seems coherent to also forbid `null?.foo`
2589 v.modelbuilder.error(self, "Error: safe operator `?` on `null`.")
2590 return
2591 end
2592
2593 self.mtype = mtype.as_notnull
2594
2595 if not v.can_be_null(mtype) then
2596 v.modelbuilder.warning(self, "useless-safe", "Warning: useless safe operator `?` on non-nullable value.")
2597 return
2598 end
2599 end
2600 end
2601
2602 redef class AVarargExpr
2603 redef fun accept_typing(v)
2604 do
2605 # This kind of pseudo-expression can be only processed trough a signature
2606 # See `check_signature`
2607 # Other cases are a syntax error.
2608 v.error(self, "Syntax Error: unexpected `...`.")
2609 end
2610 end
2611
2612 ###
2613
2614 redef class ADebugTypeExpr
2615 redef fun accept_typing(v)
2616 do
2617 var expr = v.visit_expr(self.n_expr)
2618 if expr == null then return
2619 var unsafe = v.anchor_to(expr)
2620 var ntype = self.n_type
2621 var mtype = v.resolve_mtype(ntype)
2622 if mtype != null and mtype != expr then
2623 var umtype = v.anchor_to(mtype)
2624 v.modelbuilder.warning(self, "debug", "Found type {expr} (-> {unsafe}), expected {mtype} (-> {umtype})")
2625 end
2626 self.is_typed = true
2627 end
2628 end