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