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