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