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