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