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