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