ast: kill AProxyExpr
[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
24 redef class ToolContext
25 var typing_phase: Phase = new TypingPhase(self, [flow_phase, modelize_property_phase, local_var_init_phase])
26 end
27
28 private class TypingPhase
29 super Phase
30 redef fun process_npropdef(npropdef) do npropdef.do_typing(toolcontext.modelbuilder)
31 end
32
33 private class TypeVisitor
34 var modelbuilder: ModelBuilder
35
36 # The module of the analysis
37 # Used to correctly query the model
38 var mmodule: MModule
39
40 # The static type of the receiver
41 # Mainly used for type tests and type resolutions
42 var anchor: nullable MClassType
43
44 # The analyzed mclassdef
45 var mclassdef: nullable MClassDef
46
47 # The analyzed property
48 var mpropdef: nullable MPropDef
49
50 var selfvariable: Variable = new Variable("self")
51
52 # Is `self` use restricted?
53 # * no explicit `self`
54 # * method called on the implicit self must be top-level
55 var is_toplevel_context = false
56
57 init(modelbuilder: ModelBuilder, mmodule: MModule, mpropdef: nullable MPropDef)
58 do
59 self.modelbuilder = modelbuilder
60 self.mmodule = mmodule
61
62 if mpropdef != null then
63 self.mpropdef = mpropdef
64 var mclassdef = mpropdef.mclassdef
65 self.mclassdef = mclassdef
66 self.anchor = mclassdef.bound_mtype
67
68 var mclass = mclassdef.mclass
69
70 var selfvariable = new Variable("self")
71 self.selfvariable = selfvariable
72 selfvariable.declared_type = mclass.mclass_type
73
74 var mprop = mpropdef.mproperty
75 if mprop isa MMethod and mprop.is_toplevel then
76 is_toplevel_context = true
77 end
78 end
79 end
80
81 fun anchor_to(mtype: MType): MType
82 do
83 var anchor = anchor
84 if anchor == null then
85 assert not mtype.need_anchor
86 return mtype
87 end
88 return mtype.anchor_to(mmodule, anchor)
89 end
90
91 fun is_subtype(sub, sup: MType): Bool
92 do
93 return sub.is_subtype(mmodule, anchor, sup)
94 end
95
96 fun resolve_for(mtype, subtype: MType, for_self: Bool): MType
97 do
98 #print "resolve_for {mtype} sub={subtype} forself={for_self} mmodule={mmodule} anchor={anchor}"
99 var res = mtype.resolve_for(subtype, anchor, mmodule, not for_self)
100 return res
101 end
102
103 # Check that `sub` is a subtype of `sup`.
104 # If `sub` is not a valid suptype, then display an error on `node` an return null.
105 # If `sub` is a safe subtype of `sup` then return `sub`.
106 # If `sub` is an unsafe subtype (ie an implicit cast is required), then return `sup`.
107 #
108 # The point of the return type is to determinate the usable type on an expression:
109 # If the suptype is safe, then the return type is the one on the expression typed by `sub`.
110 # Is the subtype is unsafe, then the return type is the one of an implicit cast on `sup`.
111 fun check_subtype(node: ANode, sub, sup: MType): nullable MType
112 do
113 if self.is_subtype(sub, sup) then return sub
114 if self.is_subtype(sub, self.anchor_to(sup)) then
115 # FIXME workaround to the current unsafe typing policy. To remove once fixed virtual types exists.
116 #node.debug("Unsafe typing: expected {sup}, got {sub}")
117 return sup
118 end
119 self.modelbuilder.error(node, "Type error: expected {sup}, got {sub}")
120 return null
121 end
122
123 # Visit an expression and do not care about the return value
124 fun visit_stmt(nexpr: nullable AExpr)
125 do
126 if nexpr == null then return
127 nexpr.accept_typing(self)
128 end
129
130 # Visit an expression and expects that it is not a statement
131 # Return the type of the expression
132 # Display an error and return null if:
133 # * the type cannot be determined or
134 # * `nexpr` is a statement
135 fun visit_expr(nexpr: AExpr): nullable MType
136 do
137 nexpr.accept_typing(self)
138 var mtype = nexpr.mtype
139 if mtype != null then return mtype
140 if not nexpr.is_typed then
141 if not self.modelbuilder.toolcontext.error_count > 0 then # check that there is really an error
142 if self.modelbuilder.toolcontext.verbose_level > 1 then
143 nexpr.debug("No return type but no error.")
144 end
145 end
146 return null # forward error
147 end
148 self.error(nexpr, "Type error: expected expression.")
149 return null
150 end
151
152 # Visit an expression and expect its static type is a least a `sup`
153 # Return the type of the expression or null if
154 # * the type cannot be determined or
155 # * `nexpr` is a statement or
156 # * `nexpr` is not a `sup`
157 fun visit_expr_subtype(nexpr: AExpr, sup: nullable MType): nullable MType
158 do
159 var sub = visit_expr(nexpr)
160 if sub == null then return null # Forward error
161
162 if sup == null then return null # Forward error
163
164 var res = check_subtype(nexpr, sub, sup)
165 if res != sub then
166 nexpr.implicit_cast_to = res
167 end
168 return res
169 end
170
171 # Visit an expression and expect its static type is a `Bool`
172 # Return the type of the expression or null if
173 # * the type cannot be determined or
174 # * `nexpr` is a statement or
175 # * `nexpr` is not a `Bool`
176 fun visit_expr_bool(nexpr: AExpr): nullable MType
177 do
178 return self.visit_expr_subtype(nexpr, self.type_bool(nexpr))
179 end
180
181
182 private fun visit_expr_cast(node: ANode, nexpr: AExpr, ntype: AType): nullable MType
183 do
184 var sub = visit_expr(nexpr)
185 if sub == null then return null # Forward error
186
187 var sup = self.resolve_mtype(ntype)
188 if sup == null then return null # Forward error
189
190 if sup == sub then
191 self.modelbuilder.warning(node, "useless-type-test", "Warning: Expression is already a {sup}.")
192 else if self.is_subtype(sub, sup) then
193 self.modelbuilder.warning(node, "useless-type-test", "Warning: Expression is already a {sup} since it is a {sub}.")
194 end
195 return sup
196 end
197
198 fun try_get_mproperty_by_name2(anode: ANode, mtype: MType, name: String): nullable MProperty
199 do
200 return self.modelbuilder.try_get_mproperty_by_name2(anode, mmodule, mtype, name)
201 end
202
203 fun resolve_mtype(node: AType): nullable MType
204 do
205 return self.modelbuilder.resolve_mtype(mmodule, mclassdef, node)
206 end
207
208 fun try_get_mclass(node: ANode, name: String): nullable MClass
209 do
210 var mclass = modelbuilder.try_get_mclass_by_name(node, mmodule, name)
211 return mclass
212 end
213
214 fun get_mclass(node: ANode, name: String): nullable MClass
215 do
216 var mclass = modelbuilder.try_get_mclass_by_name(node, mmodule, name)
217 if mclass == null then
218 self.modelbuilder.error(node, "Type Error: missing primitive class `{name}'.")
219 end
220 return mclass
221 end
222
223 fun type_bool(node: ANode): nullable MType
224 do
225 var mclass = self.get_mclass(node, "Bool")
226 if mclass == null then return null
227 return mclass.mclass_type
228 end
229
230 fun get_method(node: ANode, recvtype: MType, name: String, recv_is_self: Bool): nullable CallSite
231 do
232 var unsafe_type = self.anchor_to(recvtype)
233
234 #debug("recv: {recvtype} (aka {unsafe_type})")
235 if recvtype isa MNullType then
236 self.error(node, "Error: Method '{name}' call on 'null'.")
237 return null
238 end
239
240 var mproperty = self.try_get_mproperty_by_name2(node, unsafe_type, name)
241 if mproperty == null then
242 #self.modelbuilder.error(node, "Type error: property {name} not found in {unsafe_type} (ie {recvtype})")
243 if recv_is_self then
244 self.modelbuilder.error(node, "Error: Method or variable '{name}' unknown in {recvtype}.")
245 else
246 self.modelbuilder.error(node, "Error: Method '{name}' doesn't exists in {recvtype}.")
247 end
248 return null
249 end
250
251 assert mproperty isa MMethod
252
253 if is_toplevel_context and recv_is_self and not mproperty.is_toplevel then
254 error(node, "Error: '{name}' is not a top-level method, thus need a receiver.")
255 end
256 if not recv_is_self and mproperty.is_toplevel then
257 error(node, "Error: cannot call '{name}', a top-level method, with a receiver.")
258 end
259
260 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
261 self.modelbuilder.error(node, "Error: Method '{name}' is protected and can only acceded by self.")
262 return null
263 end
264
265 var info = mproperty.deprecation
266 if info != null and self.mpropdef.mproperty.deprecation == null then
267 var mdoc = info.mdoc
268 if mdoc != null then
269 self.modelbuilder.warning(node, "deprecated-method", "Deprecation Warning: Method '{name}' is deprecated: {mdoc.content.first}")
270 else
271 self.modelbuilder.warning(node, "deprecated-method", "Deprecation Warning: Method '{name}' is deprecated.")
272 end
273 end
274
275 var propdefs = mproperty.lookup_definitions(self.mmodule, unsafe_type)
276 var mpropdef
277 if propdefs.length == 0 then
278 self.modelbuilder.error(node, "Type error: no definition found for property {name} in {unsafe_type}")
279 return null
280 else if propdefs.length == 1 then
281 mpropdef = propdefs.first
282 else
283 self.modelbuilder.warning(node, "property-conflict", "Warning: conflicting property definitions for property {name} in {unsafe_type}: {propdefs.join(" ")}")
284 mpropdef = mproperty.intro
285 end
286
287
288 var msignature = mpropdef.new_msignature or else mpropdef.msignature.as(not null)
289 msignature = resolve_for(msignature, recvtype, recv_is_self).as(MSignature)
290
291 var erasure_cast = false
292 var rettype = mpropdef.msignature.return_mtype
293 if not recv_is_self and rettype != null then
294 rettype = rettype.as_notnullable
295 if rettype isa MParameterType then
296 var erased_rettype = msignature.return_mtype
297 assert erased_rettype != null
298 #node.debug("Erasure cast: Really a {rettype} but unsafely a {erased_rettype}")
299 erasure_cast = true
300 end
301 end
302
303 var callsite = new CallSite(node, recvtype, mmodule, anchor, recv_is_self, mproperty, mpropdef, msignature, erasure_cast)
304 return callsite
305 end
306
307 # Visit the expressions of args and check their conformity with the corresponding type in signature
308 # The point of this method is to handle varargs correctly
309 # Note: The signature must be correctly adapted
310 fun check_signature(node: ANode, args: Array[AExpr], name: String, msignature: MSignature): Bool
311 do
312 var vararg_rank = msignature.vararg_rank
313 if vararg_rank >= 0 then
314 if args.length < msignature.arity then
315 #self.modelbuilder.error(node, "Error: Incorrect number of parameters. Got {args.length}, expected at least {msignature.arity}. Signature is {msignature}")
316 self.modelbuilder.error(node, "Error: arity mismatch; prototype is '{name}{msignature}'")
317 return false
318 end
319 else if args.length != msignature.arity then
320 self.modelbuilder.error(node, "Error: Incorrect number of parameters. Got {args.length}, expected {msignature.arity}. Signature is {msignature}")
321 return false
322 end
323
324 #debug("CALL {unsafe_type}.{msignature}")
325
326 var vararg_decl = args.length - msignature.arity
327 for i in [0..msignature.arity[ do
328 var j = i
329 if i == vararg_rank then continue # skip the vararg
330 if i > vararg_rank then
331 j = i + vararg_decl
332 end
333 var paramtype = msignature.mparameters[i].mtype
334 self.visit_expr_subtype(args[j], paramtype)
335 end
336 if vararg_rank >= 0 then
337 var varargs = new Array[AExpr]
338 var paramtype = msignature.mparameters[vararg_rank].mtype
339 for j in [vararg_rank..vararg_rank+vararg_decl] do
340 varargs.add(args[j])
341 self.visit_expr_subtype(args[j], paramtype)
342 end
343 end
344 return true
345 end
346
347 fun error(node: ANode, message: String)
348 do
349 self.modelbuilder.toolcontext.error(node.hot_location, message)
350 end
351
352 fun get_variable(node: AExpr, variable: Variable): nullable MType
353 do
354 var flow = node.after_flow_context
355 if flow == null then
356 self.error(node, "No context!")
357 return null
358 end
359
360 if flow.vars.has_key(variable) then
361 return flow.vars[variable]
362 else
363 #node.debug("*** START Collected for {variable}")
364 var mtypes = flow.collect_types(variable)
365 #node.debug("**** END Collected for {variable}")
366 if mtypes == null or mtypes.length == 0 then
367 return variable.declared_type
368 else if mtypes.length == 1 then
369 return mtypes.first
370 else
371 var res = merge_types(node,mtypes)
372 if res == null then res = variable.declared_type
373 return res
374 end
375 end
376 end
377
378 fun set_variable(node: AExpr, variable: Variable, mtype: nullable MType)
379 do
380 var flow = node.after_flow_context
381 assert flow != null
382
383 flow.set_var(variable, mtype)
384 end
385
386 fun merge_types(node: ANode, col: Array[nullable MType]): nullable MType
387 do
388 if col.length == 1 then return col.first
389 var res = new Array[nullable MType]
390 for t1 in col do
391 if t1 == null then continue # return null
392 var found = true
393 for t2 in col do
394 if t2 == null then continue # return null
395 if t2 isa MNullableType or t2 isa MNullType then
396 t1 = t1.as_nullable
397 end
398 if not is_subtype(t2, t1) then found = false
399 end
400 if found then
401 #print "merge {col.join(" ")} -> {t1}"
402 return t1
403 end
404 end
405 #self.modelbuilder.warning(node, "Type Error: {col.length} conflicting types: <{col.join(", ")}>")
406 return null
407 end
408 end
409
410 # A specific method call site with its associated informations.
411 class CallSite
412 # The associated node for location
413 var node: ANode
414
415 # The static type of the receiver (possibly unresolved)
416 var recv: MType
417
418 # The module where the callsite is present
419 var mmodule: MModule
420
421 # The anchor to use with `recv` or `msignature`
422 var anchor: nullable MClassType
423
424 # Is the receiver self?
425 # If "for_self", virtual types of the signature are kept
426 # If "not_for_self", virtual type are erased
427 var recv_is_self: Bool
428
429 # The designated method
430 var mproperty: MMethod
431
432 # The statically designated method definition
433 # The most specif one, it is.
434 var mpropdef: MMethodDef
435
436 # The resolved signature for the receiver
437 var msignature: MSignature
438
439 # Is a implicit cast required on erasure typing policy?
440 var erasure_cast: Bool
441
442 private fun check_signature(v: TypeVisitor, args: Array[AExpr]): Bool
443 do
444 return v.check_signature(self.node, args, self.mproperty.name, self.msignature)
445 end
446 end
447
448 redef class Variable
449 # The declared type of the variable
450 var declared_type: nullable MType
451 end
452
453 redef class FlowContext
454 # Store changes of types because of type evolution
455 private var vars: HashMap[Variable, nullable MType] = new HashMap[Variable, nullable MType]
456 private var cache: HashMap[Variable, nullable Array[nullable MType]] = new HashMap[Variable, nullable Array[nullable MType]]
457
458 # Adapt the variable to a static type
459 # Warning1: do not modify vars directly.
460 # Warning2: sub-flow may have cached a unadapted variable
461 private fun set_var(variable: Variable, mtype: nullable MType)
462 do
463 self.vars[variable] = mtype
464 self.cache.keys.remove(variable)
465 end
466
467 private fun collect_types(variable: Variable): nullable Array[nullable MType]
468 do
469 if cache.has_key(variable) then
470 return cache[variable]
471 end
472 var res: nullable Array[nullable MType] = null
473 if vars.has_key(variable) then
474 var mtype = vars[variable]
475 res = [mtype]
476 else if self.previous.is_empty then
477 # Root flow
478 res = [variable.declared_type]
479 else
480 for flow in self.previous do
481 if flow.is_unreachable then continue
482 var r2 = flow.collect_types(variable)
483 if r2 == null then continue
484 if res == null then
485 res = r2.to_a
486 else
487 for t in r2 do
488 if not res.has(t) then res.add(t)
489 end
490 end
491 end
492 end
493 cache[variable] = res
494 return res
495 end
496 end
497
498 redef class APropdef
499 # The entry point of the whole typing analysis
500 fun do_typing(modelbuilder: ModelBuilder)
501 do
502 end
503
504 # The variable associated to the receiver (if any)
505 var selfvariable: nullable Variable
506 end
507
508 redef class AMethPropdef
509 redef fun do_typing(modelbuilder: ModelBuilder)
510 do
511 var nblock = self.n_block
512 if nblock == null then return
513
514 var mpropdef = self.mpropdef.as(not null)
515 var v = new TypeVisitor(modelbuilder, mpropdef.mclassdef.mmodule, mpropdef)
516 self.selfvariable = v.selfvariable
517
518 var mmethoddef = self.mpropdef.as(not null)
519 for i in [0..mmethoddef.msignature.arity[ do
520 var mtype = mmethoddef.msignature.mparameters[i].mtype
521 if mmethoddef.msignature.vararg_rank == i then
522 var arrayclass = v.get_mclass(self.n_signature.n_params[i], "Array")
523 if arrayclass == null then return # Skip error
524 mtype = arrayclass.get_mtype([mtype])
525 end
526 var variable = self.n_signature.n_params[i].variable
527 assert variable != null
528 variable.declared_type = mtype
529 end
530 v.visit_stmt(nblock)
531
532 if not nblock.after_flow_context.is_unreachable and mmethoddef.msignature.return_mtype != null then
533 # We reach the end of the function without having a return, it is bad
534 v.error(self, "Control error: Reached end of function (a 'return' with a value was expected).")
535 end
536 end
537 end
538
539 redef class AAttrPropdef
540 redef fun do_typing(modelbuilder: ModelBuilder)
541 do
542 var mpropdef = self.mpropdef.as(not null)
543 var v = new TypeVisitor(modelbuilder, mpropdef.mclassdef.mmodule, mpropdef)
544 self.selfvariable = v.selfvariable
545
546 var nexpr = self.n_expr
547 if nexpr != null then
548 var mtype = self.mpropdef.static_mtype
549 v.visit_expr_subtype(nexpr, mtype)
550 end
551 end
552 end
553
554 ###
555
556 redef class AExpr
557 # The static type of the expression.
558 # null if self is a statement or in case of error
559 var mtype: nullable MType = null
560
561 # Is the statement correctly typed?
562 # Used to distinguish errors and statements when `mtype == null`
563 var is_typed: Bool = false
564
565 # If required, the following implicit cast `.as(XXX)`
566 # Such a cast may by required after evaluating the expression when
567 # a unsafe operation is detected (silently accepted by the Nit language).
568 # The attribute is computed by `check_subtype`
569 var implicit_cast_to: nullable MType = null
570
571 # Return the variable read (if any)
572 # Used to perform adaptive typing
573 fun its_variable: nullable Variable do return null
574
575 private fun accept_typing(v: TypeVisitor)
576 do
577 v.error(self, "no implemented accept_typing for {self.class_name}")
578 end
579 end
580
581 redef class ABlockExpr
582 redef fun accept_typing(v)
583 do
584 for e in self.n_expr do v.visit_stmt(e)
585 self.is_typed = true
586 end
587
588 # The type of a blockexpr is the one of the last expression (or null if empty)
589 redef fun mtype
590 do
591 if self.n_expr.is_empty then return null
592 return self.n_expr.last.mtype
593 end
594 end
595
596 redef class AVardeclExpr
597 redef fun accept_typing(v)
598 do
599 var variable = self.variable
600 if variable == null then return # Skip error
601
602 var ntype = self.n_type
603 var mtype: nullable MType
604 if ntype == null then
605 mtype = null
606 else
607 mtype = v.resolve_mtype(ntype)
608 if mtype == null then return # Skip error
609 end
610
611 var nexpr = self.n_expr
612 if nexpr != null then
613 if mtype != null then
614 v.visit_expr_subtype(nexpr, mtype)
615 else
616 mtype = v.visit_expr(nexpr)
617 if mtype == null then return # Skip error
618 end
619 end
620
621 var decltype = mtype
622 if mtype == null or mtype isa MNullType then
623 decltype = v.get_mclass(self, "Object").mclass_type.as_nullable
624 if mtype == null then mtype = decltype
625 end
626
627 variable.declared_type = decltype
628 v.set_variable(self, variable, mtype)
629
630 #debug("var {variable}: {mtype}")
631
632 self.is_typed = true
633 end
634 end
635
636 redef class AVarExpr
637 redef fun its_variable do return self.variable
638 redef fun accept_typing(v)
639 do
640 var variable = self.variable
641 if variable == null then return # Skip error
642
643 var mtype = v.get_variable(self, variable)
644 if mtype != null then
645 #debug("{variable} is {mtype}")
646 else
647 #debug("{variable} is untyped")
648 end
649
650 self.mtype = mtype
651 end
652 end
653
654 redef class AVarAssignExpr
655 redef fun accept_typing(v)
656 do
657 var variable = self.variable
658 assert variable != null
659
660 var mtype = v.visit_expr_subtype(n_value, variable.declared_type)
661
662 v.set_variable(self, variable, mtype)
663
664 self.is_typed = true
665 end
666 end
667
668 redef class AReassignFormExpr
669 # The method designed by the reassign operator.
670 var reassign_callsite: nullable CallSite
671
672 var read_type: nullable MType = null
673
674 # Determine the `reassign_property`
675 # `readtype` is the type of the reading of the left value.
676 # `writetype` is the type of the writing of the left value.
677 # (Because of `ACallReassignExpr`, both can be different.
678 # Return the static type of the value to store.
679 private fun resolve_reassignment(v: TypeVisitor, readtype, writetype: MType): nullable MType
680 do
681 var reassign_name: String
682 if self.n_assign_op isa APlusAssignOp then
683 reassign_name = "+"
684 else if self.n_assign_op isa AMinusAssignOp then
685 reassign_name = "-"
686 else
687 abort
688 end
689
690 self.read_type = readtype
691
692 if readtype isa MNullType then
693 v.error(self, "Error: Method '{reassign_name}' call on 'null'.")
694 return null
695 end
696
697 var callsite = v.get_method(self, readtype, reassign_name, false)
698 if callsite == null then return null # Skip error
699 self.reassign_callsite = callsite
700
701 var msignature = callsite.msignature
702 var rettype = msignature.return_mtype
703 assert msignature.arity == 1 and rettype != null
704
705 var value_type = v.visit_expr_subtype(self.n_value, msignature.mparameters.first.mtype)
706 if value_type == null then return null # Skip error
707
708 v.check_subtype(self, rettype, writetype)
709 return rettype
710 end
711 end
712
713 redef class AVarReassignExpr
714 redef fun accept_typing(v)
715 do
716 var variable = self.variable
717 assert variable != null
718
719 var readtype = v.get_variable(self, variable)
720 if readtype == null then return
721
722 read_type = readtype
723
724 var writetype = variable.declared_type
725 if writetype == null then return
726
727 var rettype = self.resolve_reassignment(v, readtype, writetype)
728
729 v.set_variable(self, variable, rettype)
730
731 self.is_typed = true
732 end
733 end
734
735
736 redef class AContinueExpr
737 redef fun accept_typing(v)
738 do
739 var nexpr = self.n_expr
740 if nexpr != null then
741 var mtype = v.visit_expr(nexpr)
742 end
743 self.is_typed = true
744 end
745 end
746
747 redef class ABreakExpr
748 redef fun accept_typing(v)
749 do
750 var nexpr = self.n_expr
751 if nexpr != null then
752 var mtype = v.visit_expr(nexpr)
753 end
754 self.is_typed = true
755 end
756 end
757
758 redef class AReturnExpr
759 redef fun accept_typing(v)
760 do
761 var nexpr = self.n_expr
762 var ret_type = v.mpropdef.as(MMethodDef).msignature.return_mtype
763 if nexpr != null then
764 if ret_type != null then
765 var mtype = v.visit_expr_subtype(nexpr, ret_type)
766 else
767 var mtype = v.visit_expr(nexpr)
768 v.error(self, "Error: Return with value in a procedure.")
769 end
770 else if ret_type != null then
771 v.error(self, "Error: Return without value in a function.")
772 end
773 self.is_typed = true
774 end
775 end
776
777 redef class AAbortExpr
778 redef fun accept_typing(v)
779 do
780 self.is_typed = true
781 end
782 end
783
784 redef class AIfExpr
785 redef fun accept_typing(v)
786 do
787 v.visit_expr_bool(n_expr)
788
789 v.visit_stmt(n_then)
790 v.visit_stmt(n_else)
791 self.is_typed = true
792 end
793 end
794
795 redef class AIfexprExpr
796 redef fun accept_typing(v)
797 do
798 v.visit_expr_bool(n_expr)
799
800 var t1 = v.visit_expr(n_then)
801 var t2 = v.visit_expr(n_else)
802
803 if t1 == null or t2 == null then
804 return # Skip error
805 end
806
807 var t = v.merge_types(self, [t1, t2])
808 if t == null then
809 v.error(self, "Type Error: ambiguous type {t1} vs {t2}")
810 end
811 self.mtype = t
812 end
813 end
814
815 redef class ADoExpr
816 redef fun accept_typing(v)
817 do
818 v.visit_stmt(n_block)
819 self.is_typed = true
820 end
821 end
822
823 redef class AWhileExpr
824 redef fun accept_typing(v)
825 do
826 v.visit_expr_bool(n_expr)
827
828 v.visit_stmt(n_block)
829 self.is_typed = true
830 end
831 end
832
833 redef class ALoopExpr
834 redef fun accept_typing(v)
835 do
836 v.visit_stmt(n_block)
837 self.is_typed = true
838 end
839 end
840
841 redef class AForExpr
842 var coltype: nullable MClassType
843
844 var method_iterator: nullable CallSite
845 var method_is_ok: nullable CallSite
846 var method_item: nullable CallSite
847 var method_next: nullable CallSite
848 var method_key: nullable CallSite
849
850 private fun do_type_iterator(v: TypeVisitor, mtype: MType)
851 do
852 if mtype isa MNullType then
853 v.error(self, "Type error: 'for' cannot iterate over 'null'")
854 return
855 end
856
857 # get obj class
858 var objcla = v.get_mclass(self, "Object")
859 if objcla == null then return
860
861 # check iterator method
862 var itdef = v.get_method(self, mtype, "iterator", n_expr isa ASelfExpr)
863 if itdef == null then
864 v.error(self, "Type Error: 'for' expects a type providing 'iterator' method, got '{mtype}'.")
865 return
866 end
867 self.method_iterator = itdef
868
869 # check that iterator return something
870 var ittype = itdef.msignature.return_mtype
871 if ittype == null then
872 v.error(self, "Type Error: 'for' expects method 'iterator' to return an 'Iterator' or 'MapIterator' type'.")
873 return
874 end
875
876 # get iterator type
877 var colit_cla = v.try_get_mclass(self, "Iterator")
878 var mapit_cla = v.try_get_mclass(self, "MapIterator")
879 var is_col = false
880 var is_map = false
881
882 if colit_cla != null and v.is_subtype(ittype, colit_cla.get_mtype([objcla.mclass_type.as_nullable])) then
883 # Iterator
884 var coltype = ittype.supertype_to(v.mmodule, v.anchor, colit_cla)
885 var variables = self.variables
886 if variables.length != 1 then
887 v.error(self, "Type Error: 'for' expects only one variable when using 'Iterator'.")
888 else
889 variables.first.declared_type = coltype.arguments.first
890 end
891 is_col = true
892 end
893
894 if mapit_cla != null and v.is_subtype(ittype, mapit_cla.get_mtype([objcla.mclass_type, objcla.mclass_type.as_nullable])) then
895 # Map Iterator
896 var coltype = ittype.supertype_to(v.mmodule, v.anchor, mapit_cla)
897 var variables = self.variables
898 if variables.length != 2 then
899 v.error(self, "Type Error: 'for' expects two variables when using 'MapIterator'.")
900 else
901 variables[0].declared_type = coltype.arguments[0]
902 variables[1].declared_type = coltype.arguments[1]
903 end
904 is_map = true
905 end
906
907 if not is_col and not is_map then
908 v.error(self, "Type Error: 'for' expects method 'iterator' to return an 'Iterator' or 'MapIterator' type'.")
909 return
910 end
911
912 # anchor formal and virtual types
913 if mtype.need_anchor then mtype = v.anchor_to(mtype)
914
915 mtype = mtype.as_notnullable
916 self.coltype = mtype.as(MClassType)
917
918 # get methods is_ok, next, item
919 var ikdef = v.get_method(self, ittype, "is_ok", false)
920 if ikdef == null then
921 v.error(self, "Type Error: 'for' expects a method 'is_ok' in 'Iterator' type {ittype}.")
922 return
923 end
924 self.method_is_ok = ikdef
925
926 var itemdef = v.get_method(self, ittype, "item", false)
927 if itemdef == null then
928 v.error(self, "Type Error: 'for' expects a method 'item' in 'Iterator' type {ittype}.")
929 return
930 end
931 self.method_item = itemdef
932
933 var nextdef = v.get_method(self, ittype, "next", false)
934 if nextdef == null then
935 v.error(self, "Type Error: 'for' expects a method 'next' in 'Iterator' type {ittype}.")
936 return
937 end
938 self.method_next = nextdef
939
940 if is_map then
941 var keydef = v.get_method(self, ittype, "key", false)
942 if keydef == null then
943 v.error(self, "Type Error: 'for' expects a method 'key' in 'Iterator' type {ittype}.")
944 return
945 end
946 self.method_key = keydef
947 end
948 end
949
950 redef fun accept_typing(v)
951 do
952 var mtype = v.visit_expr(n_expr)
953 if mtype == null then return
954
955 self.do_type_iterator(v, mtype)
956
957 v.visit_stmt(n_block)
958 self.is_typed = true
959 end
960 end
961
962 redef class AAssertExpr
963 redef fun accept_typing(v)
964 do
965 v.visit_expr_bool(n_expr)
966
967 v.visit_stmt(n_else)
968 self.is_typed = true
969 end
970 end
971
972 redef class AOrExpr
973 redef fun accept_typing(v)
974 do
975 v.visit_expr_bool(n_expr)
976 v.visit_expr_bool(n_expr2)
977 self.mtype = v.type_bool(self)
978 end
979 end
980
981 redef class AImpliesExpr
982 redef fun accept_typing(v)
983 do
984 v.visit_expr_bool(n_expr)
985 v.visit_expr_bool(n_expr2)
986 self.mtype = v.type_bool(self)
987 end
988 end
989
990 redef class AAndExpr
991 redef fun accept_typing(v)
992 do
993 v.visit_expr_bool(n_expr)
994 v.visit_expr_bool(n_expr2)
995 self.mtype = v.type_bool(self)
996 end
997 end
998
999
1000 redef class ANotExpr
1001 redef fun accept_typing(v)
1002 do
1003 v.visit_expr_bool(n_expr)
1004 self.mtype = v.type_bool(self)
1005 end
1006 end
1007
1008 redef class AOrElseExpr
1009 redef fun accept_typing(v)
1010 do
1011 var t1 = v.visit_expr(n_expr)
1012 var t2 = v.visit_expr(n_expr2)
1013
1014 if t1 == null or t2 == null then
1015 return # Skip error
1016 end
1017
1018 t1 = t1.as_notnullable
1019
1020 var t = v.merge_types(self, [t1, t2])
1021 if t == null then
1022 t = v.mmodule.object_type
1023 if t2 isa MNullableType then
1024 t = t.as_nullable
1025 end
1026 #v.error(self, "Type Error: ambiguous type {t1} vs {t2}")
1027 end
1028 self.mtype = t
1029 end
1030 end
1031
1032 redef class ATrueExpr
1033 redef fun accept_typing(v)
1034 do
1035 self.mtype = v.type_bool(self)
1036 end
1037 end
1038
1039 redef class AFalseExpr
1040 redef fun accept_typing(v)
1041 do
1042 self.mtype = v.type_bool(self)
1043 end
1044 end
1045
1046 redef class AIntExpr
1047 redef fun accept_typing(v)
1048 do
1049 var mclass = v.get_mclass(self, "Int")
1050 if mclass == null then return # Forward error
1051 self.mtype = mclass.mclass_type
1052 end
1053 end
1054
1055 redef class AFloatExpr
1056 redef fun accept_typing(v)
1057 do
1058 var mclass = v.get_mclass(self, "Float")
1059 if mclass == null then return # Forward error
1060 self.mtype = mclass.mclass_type
1061 end
1062 end
1063
1064 redef class ACharExpr
1065 redef fun accept_typing(v)
1066 do
1067 var mclass = v.get_mclass(self, "Char")
1068 if mclass == null then return # Forward error
1069 self.mtype = mclass.mclass_type
1070 end
1071 end
1072
1073 redef class AStringFormExpr
1074 redef fun accept_typing(v)
1075 do
1076 var mclass = v.get_mclass(self, "String")
1077 if mclass == null then return # Forward error
1078 self.mtype = mclass.mclass_type
1079 end
1080 end
1081
1082 redef class ASuperstringExpr
1083 redef fun accept_typing(v)
1084 do
1085 var mclass = v.get_mclass(self, "String")
1086 if mclass == null then return # Forward error
1087 self.mtype = mclass.mclass_type
1088 for nexpr in self.n_exprs do
1089 v.visit_expr_subtype(nexpr, v.mmodule.object_type)
1090 end
1091 end
1092 end
1093
1094 redef class AArrayExpr
1095 var with_capacity_callsite: nullable CallSite
1096 var push_callsite: nullable CallSite
1097
1098 redef fun accept_typing(v)
1099 do
1100 var mtype: nullable MType = null
1101 var ntype = self.n_type
1102 if ntype != null then
1103 mtype = v.resolve_mtype(ntype)
1104 if mtype == null then return # Skip error
1105 end
1106 var mtypes = new Array[nullable MType]
1107 var useless = false
1108 for e in self.n_exprs.n_exprs do
1109 var t = v.visit_expr(e)
1110 if t == null then
1111 return # Skip error
1112 end
1113 if mtype != null then
1114 if v.check_subtype(e, t, mtype) == null then return # Skip error
1115 if t == mtype then useless = true
1116 else
1117 mtypes.add(t)
1118 end
1119 end
1120 if mtype == null then
1121 mtype = v.merge_types(self, mtypes)
1122 end
1123 if mtype == null then
1124 v.error(self, "Type Error: ambiguous array type {mtypes.join(" ")}")
1125 return
1126 end
1127 if useless then
1128 assert ntype != null
1129 v.modelbuilder.warning(ntype, "useless-type", "Warning: useless type declaration `{mtype}` in literal Array since it can be inferred from the elements type.")
1130 end
1131 var mclass = v.get_mclass(self, "Array")
1132 if mclass == null then return # Forward error
1133 var array_mtype = mclass.get_mtype([mtype])
1134
1135 with_capacity_callsite = v.get_method(self, array_mtype, "with_capacity", false)
1136 push_callsite = v.get_method(self, array_mtype, "push", false)
1137
1138 self.mtype = array_mtype
1139 end
1140 end
1141
1142 redef class ARangeExpr
1143 var init_callsite: nullable CallSite
1144
1145 redef fun accept_typing(v)
1146 do
1147 var discrete_class = v.get_mclass(self, "Discrete")
1148 if discrete_class == null then return # Forward error
1149 var discrete_type = discrete_class.intro.bound_mtype
1150 var t1 = v.visit_expr_subtype(self.n_expr, discrete_type)
1151 var t2 = v.visit_expr_subtype(self.n_expr2, discrete_type)
1152 if t1 == null or t2 == null then return
1153 var mclass = v.get_mclass(self, "Range")
1154 if mclass == null then return # Forward error
1155 var mtype
1156 if v.is_subtype(t1, t2) then
1157 mtype = mclass.get_mtype([t2])
1158 else if v.is_subtype(t2, t1) then
1159 mtype = mclass.get_mtype([t1])
1160 else
1161 v.error(self, "Type Error: Cannot create range: {t1} vs {t2}")
1162 return
1163 end
1164
1165 self.mtype = mtype
1166
1167 # get the constructor
1168 var callsite
1169 if self isa ACrangeExpr then
1170 callsite = v.get_method(self, mtype, "init", false)
1171 else if self isa AOrangeExpr then
1172 callsite = v.get_method(self, mtype, "without_last", false)
1173 else
1174 abort
1175 end
1176 init_callsite = callsite
1177 end
1178 end
1179
1180 redef class ANullExpr
1181 redef fun accept_typing(v)
1182 do
1183 self.mtype = v.mmodule.model.null_type
1184 end
1185 end
1186
1187 redef class AIsaExpr
1188 # The static type to cast to.
1189 # (different from the static type of the expression that is `Bool`).
1190 var cast_type: nullable MType
1191 redef fun accept_typing(v)
1192 do
1193 var mtype = v.visit_expr_cast(self, self.n_expr, self.n_type)
1194 self.cast_type = mtype
1195
1196 var variable = self.n_expr.its_variable
1197 if variable != null then
1198 var orig = self.n_expr.mtype
1199 var from = if orig != null then orig.to_s else "invalid"
1200 var to = if mtype != null then mtype.to_s else "invalid"
1201 #debug("adapt {variable}: {from} -> {to}")
1202 self.after_flow_context.when_true.set_var(variable, mtype)
1203 end
1204
1205 self.mtype = v.type_bool(self)
1206 end
1207 end
1208
1209 redef class AAsCastExpr
1210 redef fun accept_typing(v)
1211 do
1212 self.mtype = v.visit_expr_cast(self, self.n_expr, self.n_type)
1213 end
1214 end
1215
1216 redef class AAsNotnullExpr
1217 redef fun accept_typing(v)
1218 do
1219 var mtype = v.visit_expr(self.n_expr)
1220 if mtype == null then return # Forward error
1221
1222 if mtype isa MNullType then
1223 v.error(self, "Type error: as(not null) on null")
1224 return
1225 end
1226 if mtype isa MNullableType then
1227 self.mtype = mtype.mtype
1228 return
1229 end
1230 self.mtype = mtype
1231
1232 if mtype isa MClassType then
1233 v.modelbuilder.warning(self, "useless-type-test", "Warning: expression is already not null, since it is a `{mtype}`.")
1234 return
1235 end
1236 assert mtype.need_anchor
1237 var u = v.anchor_to(mtype)
1238 if not u isa MNullableType then
1239 v.modelbuilder.warning(self, "useless-type-test", "Warning: expression is already not null, since it is a `{mtype}: {u}`.")
1240 return
1241 end
1242 end
1243 end
1244
1245 redef class AParExpr
1246 redef fun accept_typing(v)
1247 do
1248 self.mtype = v.visit_expr(self.n_expr)
1249 end
1250 end
1251
1252 redef class AOnceExpr
1253 redef fun accept_typing(v)
1254 do
1255 self.mtype = v.visit_expr(self.n_expr)
1256 end
1257 end
1258
1259 redef class ASelfExpr
1260 redef var its_variable: nullable Variable
1261 redef fun accept_typing(v)
1262 do
1263 if v.is_toplevel_context and not self isa AImplicitSelfExpr then
1264 v.error(self, "Error: self cannot be used in top-level method.")
1265 end
1266 var variable = v.selfvariable
1267 self.its_variable = variable
1268 self.mtype = v.get_variable(self, variable)
1269 end
1270 end
1271
1272 ## MESSAGE SENDING AND PROPERTY
1273
1274 redef class ASendExpr
1275 # The property invoked by the send.
1276 var callsite: nullable CallSite
1277
1278 redef fun accept_typing(v)
1279 do
1280 var recvtype = v.visit_expr(self.n_expr)
1281 var name = self.property_name
1282
1283 if recvtype == null then return # Forward error
1284 if recvtype isa MNullType then
1285 v.error(self, "Error: Method '{name}' call on 'null'.")
1286 return
1287 end
1288
1289 var callsite = v.get_method(self, recvtype, name, self.n_expr isa ASelfExpr)
1290 if callsite == null then return
1291 self.callsite = callsite
1292 var msignature = callsite.msignature
1293
1294 var args = compute_raw_arguments
1295
1296 callsite.check_signature(v, args)
1297
1298 if callsite.mproperty.is_init then
1299 var vmpropdef = v.mpropdef
1300 if not (vmpropdef isa MMethodDef and vmpropdef.mproperty.is_init) then
1301 v.error(self, "Can call a init only in another init")
1302 end
1303 if vmpropdef isa MMethodDef and vmpropdef.mproperty.is_root_init and not callsite.mproperty.is_root_init then
1304 v.error(self, "Error: {vmpropdef} cannot call a factory {callsite.mproperty}")
1305 end
1306 end
1307
1308 var ret = msignature.return_mtype
1309 if ret != null then
1310 self.mtype = ret
1311 else
1312 self.is_typed = true
1313 end
1314 end
1315
1316 # The name of the property
1317 # Each subclass simply provide the correct name.
1318 private fun property_name: String is abstract
1319
1320 # An array of all arguments (excluding self)
1321 fun raw_arguments: Array[AExpr] do return compute_raw_arguments
1322
1323 private fun compute_raw_arguments: Array[AExpr] is abstract
1324 end
1325
1326 redef class ABinopExpr
1327 redef fun compute_raw_arguments do return [n_expr2]
1328 end
1329 redef class AEqExpr
1330 redef fun property_name do return "=="
1331 redef fun accept_typing(v)
1332 do
1333 super
1334
1335 var variable = self.n_expr.its_variable
1336 if variable == null then return
1337 var mtype = self.n_expr2.mtype
1338 if not mtype isa MNullType then return
1339 var vartype = v.get_variable(self, variable)
1340 if not vartype isa MNullableType then return
1341 self.after_flow_context.when_true.set_var(variable, mtype)
1342 self.after_flow_context.when_false.set_var(variable, vartype.mtype)
1343 #debug("adapt {variable}:{vartype} ; true->{mtype} false->{vartype.mtype}")
1344 end
1345 end
1346 redef class ANeExpr
1347 redef fun property_name do return "!="
1348 redef fun accept_typing(v)
1349 do
1350 super
1351
1352 var variable = self.n_expr.its_variable
1353 if variable == null then return
1354 var mtype = self.n_expr2.mtype
1355 if not mtype isa MNullType then return
1356 var vartype = v.get_variable(self, variable)
1357 if not vartype isa MNullableType then return
1358 self.after_flow_context.when_false.set_var(variable, mtype)
1359 self.after_flow_context.when_true.set_var(variable, vartype.mtype)
1360 #debug("adapt {variable}:{vartype} ; true->{vartype.mtype} false->{mtype}")
1361 end
1362 end
1363 redef class ALtExpr
1364 redef fun property_name do return "<"
1365 end
1366 redef class ALeExpr
1367 redef fun property_name do return "<="
1368 end
1369 redef class ALlExpr
1370 redef fun property_name do return "<<"
1371 end
1372 redef class AGtExpr
1373 redef fun property_name do return ">"
1374 end
1375 redef class AGeExpr
1376 redef fun property_name do return ">="
1377 end
1378 redef class AGgExpr
1379 redef fun property_name do return ">>"
1380 end
1381 redef class APlusExpr
1382 redef fun property_name do return "+"
1383 end
1384 redef class AMinusExpr
1385 redef fun property_name do return "-"
1386 end
1387 redef class AStarshipExpr
1388 redef fun property_name do return "<=>"
1389 end
1390 redef class AStarExpr
1391 redef fun property_name do return "*"
1392 end
1393 redef class AStarstarExpr
1394 redef fun property_name do return "**"
1395 end
1396 redef class ASlashExpr
1397 redef fun property_name do return "/"
1398 end
1399 redef class APercentExpr
1400 redef fun property_name do return "%"
1401 end
1402
1403 redef class AUminusExpr
1404 redef fun property_name do return "unary -"
1405 redef fun compute_raw_arguments do return new Array[AExpr]
1406 end
1407
1408
1409 redef class ACallExpr
1410 redef fun property_name do return n_id.text
1411 redef fun compute_raw_arguments do return n_args.to_a
1412 end
1413
1414 redef class ACallAssignExpr
1415 redef fun property_name do return n_id.text + "="
1416 redef fun compute_raw_arguments
1417 do
1418 var res = n_args.to_a
1419 res.add(n_value)
1420 return res
1421 end
1422 end
1423
1424 redef class ABraExpr
1425 redef fun property_name do return "[]"
1426 redef fun compute_raw_arguments do return n_args.to_a
1427 end
1428
1429 redef class ABraAssignExpr
1430 redef fun property_name do return "[]="
1431 redef fun compute_raw_arguments
1432 do
1433 var res = n_args.to_a
1434 res.add(n_value)
1435 return res
1436 end
1437 end
1438
1439 redef class ASendReassignFormExpr
1440 # The property invoked for the writing
1441 var write_callsite: nullable CallSite
1442
1443 redef fun accept_typing(v)
1444 do
1445 var recvtype = v.visit_expr(self.n_expr)
1446 var name = self.property_name
1447
1448 if recvtype == null then return # Forward error
1449 if recvtype isa MNullType then
1450 v.error(self, "Error: Method '{name}' call on 'null'.")
1451 return
1452 end
1453
1454 var for_self = self.n_expr isa ASelfExpr
1455 var callsite = v.get_method(self, recvtype, name, for_self)
1456
1457 if callsite == null then return
1458 self.callsite = callsite
1459
1460 var args = compute_raw_arguments
1461
1462 callsite.check_signature(v, args)
1463
1464 var readtype = callsite.msignature.return_mtype
1465 if readtype == null then
1466 v.error(self, "Error: {name} is not a function")
1467 return
1468 end
1469
1470 var wcallsite = v.get_method(self, recvtype, name + "=", self.n_expr isa ASelfExpr)
1471 if wcallsite == null then return
1472 self.write_callsite = wcallsite
1473
1474 var wtype = self.resolve_reassignment(v, readtype, wcallsite.msignature.mparameters.last.mtype)
1475 if wtype == null then return
1476
1477 args = args.to_a # duplicate so raw_arguments keeps only the getter args
1478 args.add(self.n_value)
1479 wcallsite.check_signature(v, args)
1480
1481 self.is_typed = true
1482 end
1483 end
1484
1485 redef class ACallReassignExpr
1486 redef fun property_name do return n_id.text
1487 redef fun compute_raw_arguments do return n_args.to_a
1488 end
1489
1490 redef class ABraReassignExpr
1491 redef fun property_name do return "[]"
1492 redef fun compute_raw_arguments do return n_args.to_a
1493 end
1494
1495 redef class AInitExpr
1496 redef fun property_name do return "init"
1497 redef fun compute_raw_arguments do return n_args.to_a
1498 end
1499
1500 redef class AExprs
1501 fun to_a: Array[AExpr] do return self.n_exprs.to_a
1502 end
1503
1504 ###
1505
1506 redef class ASuperExpr
1507 # The method to call if the super is in fact a 'super init call'
1508 # Note: if the super is a normal call-next-method, then this attribute is null
1509 var callsite: nullable CallSite
1510
1511 # The method to call is the super is a standard `call-next-method` super-call
1512 # Note: if the super is a special super-init-call, then this attribute is null
1513 var mpropdef: nullable MMethodDef
1514
1515 redef fun accept_typing(v)
1516 do
1517 var anchor = v.anchor
1518 assert anchor != null
1519 var recvtype = v.get_variable(self, v.selfvariable)
1520 assert recvtype != null
1521 var mproperty = v.mpropdef.mproperty
1522 if not mproperty isa MMethod then
1523 v.error(self, "Error: super only usable in a method")
1524 return
1525 end
1526 var superprops = mproperty.lookup_super_definitions(v.mmodule, anchor)
1527 if superprops.length == 0 then
1528 if mproperty.is_init and v.mpropdef.is_intro then
1529 process_superinit(v)
1530 return
1531 end
1532 v.error(self, "Error: No super method to call for {mproperty}.")
1533 return
1534 end
1535 # FIXME: covariance of return type in linear extension?
1536 var superprop = superprops.first
1537
1538 var msignature = superprop.msignature.as(not null)
1539 msignature = v.resolve_for(msignature, recvtype, true).as(MSignature)
1540 var args = self.n_args.to_a
1541 if args.length > 0 then
1542 v.check_signature(self, args, mproperty.name, msignature)
1543 end
1544 self.mtype = msignature.return_mtype
1545 self.is_typed = true
1546 v.mpropdef.has_supercall = true
1547 mpropdef = v.mpropdef.as(MMethodDef)
1548 end
1549
1550 private fun process_superinit(v: TypeVisitor)
1551 do
1552 var anchor = v.anchor
1553 assert anchor != null
1554 var recvtype = v.get_variable(self, v.selfvariable)
1555 assert recvtype != null
1556 var mpropdef = v.mpropdef
1557 assert mpropdef isa MMethodDef
1558 var mproperty = mpropdef.mproperty
1559 var superprop: nullable MMethodDef = null
1560 for msupertype in mpropdef.mclassdef.supertypes do
1561 msupertype = msupertype.anchor_to(v.mmodule, anchor)
1562 var errcount = v.modelbuilder.toolcontext.error_count
1563 var candidate = v.try_get_mproperty_by_name2(self, msupertype, mproperty.name).as(nullable MMethod)
1564 if candidate == null then
1565 if v.modelbuilder.toolcontext.error_count > errcount then return # Forward error
1566 continue # Try next super-class
1567 end
1568 if superprop != null and candidate.is_root_init then
1569 continue
1570 end
1571 if superprop != null and superprop.mproperty != candidate and not superprop.mproperty.is_root_init then
1572 v.error(self, "Error: conflicting super constructor to call for {mproperty}: {candidate.full_name}, {superprop.mproperty.full_name}")
1573 return
1574 end
1575 var candidatedefs = candidate.lookup_definitions(v.mmodule, anchor)
1576 if superprop != null and superprop.mproperty == candidate then
1577 if superprop == candidatedefs.first then continue
1578 candidatedefs.add(superprop)
1579 end
1580 if candidatedefs.length > 1 then
1581 v.error(self, "Error: conflicting property definitions for property {mproperty} in {recvtype}: {candidatedefs.join(", ")}")
1582 return
1583 end
1584 superprop = candidatedefs.first
1585 end
1586 if superprop == null then
1587 v.error(self, "Error: No super method to call for {mproperty}.")
1588 return
1589 end
1590
1591 var msignature = superprop.new_msignature or else superprop.msignature.as(not null)
1592 msignature = v.resolve_for(msignature, recvtype, true).as(MSignature)
1593
1594 var callsite = new CallSite(self, recvtype, v.mmodule, v.anchor, true, superprop.mproperty, superprop, msignature, false)
1595 self.callsite = callsite
1596
1597 var args = self.n_args.to_a
1598 if args.length > 0 then
1599 callsite.check_signature(v, args)
1600 else
1601 # Check there is at least enough parameters
1602 if mpropdef.msignature.arity < msignature.arity then
1603 v.error(self, "Error: Not enough implicit arguments to pass. Got {mpropdef.msignature.arity}, expected at least {msignature.arity}. Signature is {msignature}")
1604 return
1605 end
1606 # Check that each needed parameter is conform
1607 var i = 0
1608 for sp in msignature.mparameters do
1609 var p = mpropdef.msignature.mparameters[i]
1610 if not v.is_subtype(p.mtype, sp.mtype) then
1611 v.error(self, "Type error: expected argument #{i} of type {sp.mtype}, got implicit argument {p.name} of type {p.mtype}. Signature is {msignature}")
1612 return
1613 end
1614 i += 1
1615 end
1616 end
1617
1618 self.is_typed = true
1619 end
1620 end
1621
1622 ####
1623
1624 redef class ANewExpr
1625 # The constructor invoked by the new.
1626 var callsite: nullable CallSite
1627
1628 redef fun accept_typing(v)
1629 do
1630 var recvtype = v.resolve_mtype(self.n_type)
1631 if recvtype == null then return
1632 self.mtype = recvtype
1633
1634 if not recvtype isa MClassType then
1635 if recvtype isa MNullableType then
1636 v.error(self, "Type error: cannot instantiate the nullable type {recvtype}.")
1637 return
1638 else
1639 v.error(self, "Type error: cannot instantiate the formal type {recvtype}.")
1640 return
1641 end
1642 else
1643 if recvtype.mclass.kind == abstract_kind then
1644 v.error(self, "Cannot instantiate abstract class {recvtype}.")
1645 return
1646 else if recvtype.mclass.kind == interface_kind then
1647 v.error(self, "Cannot instantiate interface {recvtype}.")
1648 return
1649 end
1650 end
1651
1652 var name: String
1653 var nid = self.n_id
1654 if nid != null then
1655 name = nid.text
1656 else
1657 name = "init"
1658 end
1659 var callsite = v.get_method(self, recvtype, name, false)
1660 if callsite == null then return
1661
1662 self.callsite = callsite
1663
1664 if not callsite.mproperty.is_init_for(recvtype.mclass) then
1665 v.error(self, "Error: {name} is not a constructor.")
1666 return
1667 end
1668
1669 var args = n_args.to_a
1670 callsite.check_signature(v, args)
1671 end
1672 end
1673
1674 ####
1675
1676 redef class AAttrFormExpr
1677 # The attribute acceded.
1678 var mproperty: nullable MAttribute
1679
1680 # The static type of the attribute.
1681 var attr_type: nullable MType
1682
1683 # Resolve the attribute acceded.
1684 private fun resolve_property(v: TypeVisitor)
1685 do
1686 var recvtype = v.visit_expr(self.n_expr)
1687 if recvtype == null then return # Skip error
1688 var name = self.n_id.text
1689 if recvtype isa MNullType then
1690 v.error(self, "Error: Attribute '{name}' access on 'null'.")
1691 return
1692 end
1693
1694 var unsafe_type = v.anchor_to(recvtype)
1695 var mproperty = v.try_get_mproperty_by_name2(self, unsafe_type, name)
1696 if mproperty == null then
1697 v.modelbuilder.error(self, "Error: Attribute {name} doesn't exists in {recvtype}.")
1698 return
1699 end
1700 assert mproperty isa MAttribute
1701 self.mproperty = mproperty
1702
1703 var mpropdefs = mproperty.lookup_definitions(v.mmodule, unsafe_type)
1704 assert mpropdefs.length == 1
1705 var mpropdef = mpropdefs.first
1706 var attr_type = mpropdef.static_mtype.as(not null)
1707 attr_type = v.resolve_for(attr_type, recvtype, self.n_expr isa ASelfExpr)
1708 self.attr_type = attr_type
1709 end
1710 end
1711
1712 redef class AAttrExpr
1713 redef fun accept_typing(v)
1714 do
1715 self.resolve_property(v)
1716 self.mtype = self.attr_type
1717 end
1718 end
1719
1720
1721 redef class AAttrAssignExpr
1722 redef fun accept_typing(v)
1723 do
1724 self.resolve_property(v)
1725 var mtype = self.attr_type
1726
1727 v.visit_expr_subtype(self.n_value, mtype)
1728 self.is_typed = true
1729 end
1730 end
1731
1732 redef class AAttrReassignExpr
1733 redef fun accept_typing(v)
1734 do
1735 self.resolve_property(v)
1736 var mtype = self.attr_type
1737 if mtype == null then return # Skip error
1738
1739 self.resolve_reassignment(v, mtype, mtype)
1740
1741 self.is_typed = true
1742 end
1743 end
1744
1745 redef class AIssetAttrExpr
1746 redef fun accept_typing(v)
1747 do
1748 self.resolve_property(v)
1749 var mtype = self.attr_type
1750 if mtype == null then return # Skip error
1751
1752 var recvtype = self.n_expr.mtype.as(not null)
1753 var bound = v.resolve_for(mtype, recvtype, false)
1754 if bound isa MNullableType then
1755 v.error(self, "Error: isset on a nullable attribute.")
1756 end
1757 self.mtype = v.type_bool(self)
1758 end
1759 end
1760
1761 ###
1762
1763 redef class ADebugTypeExpr
1764 redef fun accept_typing(v)
1765 do
1766 var expr = v.visit_expr(self.n_expr)
1767 if expr == null then return
1768 var unsafe = v.anchor_to(expr)
1769 var ntype = self.n_type
1770 var mtype = v.resolve_mtype(ntype)
1771 if mtype != null and mtype != expr then
1772 var umtype = v.anchor_to(mtype)
1773 v.modelbuilder.warning(self, "debug", "Found type {expr} (-> {unsafe}), expected {mtype} (-> {umtype})")
1774 end
1775 self.is_typed = true
1776 end
1777 end