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