rta: rename and document runtime_type.nit
[nit.git] / src / 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 flow
22 import modelbuilder
23
24 private class TypeVisitor
25 var modelbuilder: ModelBuilder
26 var nclassdef: AClassdef
27 var mpropdef: MPropDef
28
29 var selfvariable: Variable = new Variable("self")
30
31 init(modelbuilder: ModelBuilder, nclassdef: AClassdef, mpropdef: MPropDef)
32 do
33 self.modelbuilder = modelbuilder
34 self.nclassdef = nclassdef
35 self.mpropdef = mpropdef
36
37 var mclass = nclassdef.mclassdef.mclass
38
39 var selfvariable = new Variable("self")
40 self.selfvariable = selfvariable
41 selfvariable.declared_type = mclass.mclass_type
42 end
43
44 fun mmodule: MModule do return self.nclassdef.mclassdef.mmodule
45
46 fun anchor: MClassType do return self.nclassdef.mclassdef.bound_mtype
47
48 fun anchor_to(mtype: MType): MType
49 do
50 var mmodule = self.nclassdef.mclassdef.mmodule
51 var anchor = self.nclassdef.mclassdef.bound_mtype
52 return mtype.anchor_to(mmodule, anchor)
53 end
54
55 fun is_subtype(sub, sup: MType): Bool
56 do
57 var mmodule = self.nclassdef.mclassdef.mmodule
58 var anchor = self.nclassdef.mclassdef.bound_mtype
59 return sub.is_subtype(mmodule, anchor, sup)
60 end
61
62 fun resolve_for(mtype, subtype: MType, for_self: Bool): MType
63 do
64 var mmodule = self.nclassdef.mclassdef.mmodule
65 var anchor = self.nclassdef.mclassdef.bound_mtype
66 #print "resolve_for {mtype} sub={subtype} forself={for_self} mmodule={mmodule} anchor={anchor}"
67 var res = mtype.resolve_for(subtype, anchor, mmodule, not for_self)
68 return res
69 end
70
71 fun resolve_signature_for(msignature: MSignature, recv: MType, for_self: Bool): MSignature
72 do
73 return self.resolve_for(msignature, recv, for_self).as(MSignature)
74 end
75
76 fun check_subtype(node: ANode, sub, sup: MType): Bool
77 do
78 if self.is_subtype(sub, sup) then return true
79 if self.is_subtype(sub, self.anchor_to(sup)) then
80 # FIXME workarround to the current unsafe typing policy. To remove once fixed virtual types exists.
81 #node.debug("Unsafe typing: expected {sup}, got {sub}")
82 return true
83 end
84 self.modelbuilder.error(node, "Type error: expected {sup}, got {sub}")
85 return false
86 end
87
88 # Visit an expression and do not care about the return value
89 fun visit_stmt(nexpr: nullable AExpr)
90 do
91 if nexpr == null then return
92 nexpr.accept_typing(self)
93 end
94
95 # Visit an expression and expects that it is not a statement
96 # Return the type of the expression
97 # Display an error and return null if:
98 # * the type cannot be determined or
99 # * `nexpr' is a statement
100 fun visit_expr(nexpr: AExpr): nullable MType
101 do
102 nexpr.accept_typing(self)
103 var mtype = nexpr.mtype
104 if mtype != null then return mtype
105 if not nexpr.is_typed then
106 if not self.modelbuilder.toolcontext.error_count > 0 then # check that there is really an error
107 if self.modelbuilder.toolcontext.verbose_level > 1 then
108 nexpr.debug("No return type but no error.")
109 end
110 end
111 return null # forward error
112 end
113 self.error(nexpr, "Type error: expected expression.")
114 return null
115 end
116
117 # Visit an expression and expect its static type is a least a `sup'
118 # Return the type of the expression
119 # * the type cannot be determined or
120 # * `nexpr' is a statement
121 # * `nexpt' is not a `sup'
122 fun visit_expr_subtype(nexpr: AExpr, sup: nullable MType): nullable MType
123 do
124 var sub = visit_expr(nexpr)
125 if sub == null then return null # Forward error
126
127 if sup == null then return null # Forward error
128
129 if not check_subtype(nexpr, sub, sup) then
130 return null
131 end
132 return sub
133 end
134
135 # Visit an expression and expect its static type is a bool
136 # Return the type of the expression
137 # * the type cannot be determined or
138 # * `nexpr' is a statement
139 # * `nexpt' is not a `sup'
140 fun visit_expr_bool(nexpr: AExpr): nullable MType
141 do
142 return self.visit_expr_subtype(nexpr, self.type_bool(nexpr))
143 end
144
145
146 private fun visit_expr_cast(node: ANode, nexpr: AExpr, ntype: AType): nullable MType
147 do
148 var sub = visit_expr(nexpr)
149 if sub == null then return null # Forward error
150
151 var sup = self.resolve_mtype(ntype)
152 if sup == null then return null # Forward error
153
154 var mmodule = self.nclassdef.mclassdef.mmodule
155 var anchor = self.nclassdef.mclassdef.bound_mtype
156 if sup == sub then
157 self.modelbuilder.warning(node, "Warning: Expression is already a {sup}.")
158 else if self.is_subtype(sub, sup) and not sup.need_anchor then
159 self.modelbuilder.warning(node, "Warning: Expression is already a {sup} since it is a {sub}.")
160 end
161 return sup
162 end
163
164 fun try_get_mproperty_by_name2(anode: ANode, mtype: MType, name: String): nullable MProperty
165 do
166 return self.modelbuilder.try_get_mproperty_by_name2(anode, self.nclassdef.mclassdef.mmodule, mtype, name)
167 end
168
169 fun resolve_mtype(node: AType): nullable MType
170 do
171 return self.modelbuilder.resolve_mtype(self.nclassdef, node)
172 end
173
174 fun get_mclass(node: ANode, name: String): nullable MClass
175 do
176 var mmodule = self.nclassdef.mclassdef.mmodule
177 var mclass = modelbuilder.try_get_mclass_by_name(node, mmodule, name)
178 if mclass == null then
179 self.modelbuilder.error(node, "Type Error: missing primitive class `{name}'.")
180 end
181 return mclass
182 end
183
184 fun type_bool(node: ANode): nullable MType
185 do
186 var mclass = self.get_mclass(node, "Bool")
187 if mclass == null then return null
188 return mclass.mclass_type
189 end
190
191 fun get_method(node: ANode, recvtype: MType, name: String, recv_is_self: Bool): nullable MMethodDef
192 do
193 var unsafe_type = self.anchor_to(recvtype)
194
195 #debug("recv: {recvtype} (aka {unsafe_type})")
196
197 var mproperty = self.try_get_mproperty_by_name2(node, unsafe_type, name)
198 if mproperty == null then
199 #self.modelbuilder.error(node, "Type error: property {name} not found in {unsafe_type} (ie {recvtype})")
200 if recv_is_self then
201 self.modelbuilder.error(node, "Error: Method or variable '{name}' unknown in {recvtype}.")
202 else
203 self.modelbuilder.error(node, "Error: Method '{name}' doesn't exists in {recvtype}.")
204 end
205 return null
206 end
207
208 var propdefs = mproperty.lookup_definitions(self.mmodule, unsafe_type)
209 if propdefs.length == 0 then
210 self.modelbuilder.error(node, "Type error: no definition found for property {name} in {unsafe_type}")
211 return null
212 else if propdefs.length > 1 then
213 self.modelbuilder.error(node, "Error: confliting property definitions for property {name} in {unsafe_type}: {propdefs.join(" ")}")
214 return null
215 end
216
217 var propdef = propdefs.first
218 assert propdef isa MMethodDef
219 return propdef
220 end
221
222 # Visit the expressions of args and cheik their conformity with the corresponding typi in signature
223 # The point of this method is to handle varargs correctly
224 # Note: The signature must be correctly adapted
225 fun check_signature(node: ANode, args: Array[AExpr], name: String, msignature: MSignature): Bool
226 do
227 var vararg_rank = msignature.vararg_rank
228 if vararg_rank >= 0 then
229 if args.length < msignature.arity then
230 #self.modelbuilder.error(node, "Error: Incorrect number of parameters. Got {args.length}, expected at least {msignature.arity}. Signature is {msignature}")
231 self.modelbuilder.error(node, "Error: arity mismatch; prototype is '{name}{msignature}'")
232 return false
233 end
234 else if args.length != msignature.arity then
235 self.modelbuilder.error(node, "Error: Incorrect number of parameters. Got {args.length}, expected {msignature.arity}. Signature is {msignature}")
236 return false
237 end
238
239 #debug("CALL {unsafe_type}.{msignature}")
240
241 var vararg_decl = args.length - msignature.arity
242 for i in [0..msignature.arity[ do
243 var j = i
244 if i == vararg_rank then continue # skip the vararg
245 if i > vararg_rank then
246 j = i + vararg_decl
247 end
248 var paramtype = msignature.parameter_mtypes[i]
249 self.visit_expr_subtype(args[j], paramtype)
250 end
251 if vararg_rank >= 0 then
252 var varargs = new Array[AExpr]
253 var paramtype = msignature.parameter_mtypes[vararg_rank]
254 for j in [vararg_rank..vararg_rank+vararg_decl] do
255 varargs.add(args[j])
256 self.visit_expr_subtype(args[j], paramtype)
257 end
258 end
259 return true
260 end
261
262 fun error(node: ANode, message: String)
263 do
264 self.modelbuilder.toolcontext.error(node.hot_location, message)
265 end
266
267 fun get_variable(node: AExpr, variable: Variable): nullable MType
268 do
269 var flow = node.after_flow_context
270 if flow == null then
271 self.error(node, "No context!")
272 return null
273 end
274
275 if flow.vars.has_key(variable) then
276 return flow.vars[variable]
277 else
278 #node.debug("*** START Collected for {variable}")
279 var mtypes = flow.collect_types(variable)
280 #node.debug("**** END Collected for {variable}")
281 if mtypes == null or mtypes.length == 0 then
282 return variable.declared_type
283 else if mtypes.length == 1 then
284 return mtypes.first
285 else
286 var res = merge_types(node,mtypes)
287 if res == null then res = variable.declared_type
288 return res
289 end
290 end
291 end
292
293 fun set_variable(node: AExpr, variable: Variable, mtype: nullable MType)
294 do
295 var flow = node.after_flow_context
296 assert flow != null
297
298 flow.set_var(variable, mtype)
299 end
300
301 fun merge_types(node: ANode, col: Array[nullable MType]): nullable MType
302 do
303 if col.length == 1 then return col.first
304 var res = new Array[nullable MType]
305 for t1 in col do
306 if t1 == null then continue # return null
307 var found = true
308 for t2 in col do
309 if t2 == null then continue # return null
310 if t2 isa MNullableType or t2 isa MNullType then
311 t1 = t1.as_nullable
312 end
313 if not is_subtype(t2, t1) then found = false
314 end
315 if found then
316 #print "merge {col.join(" ")} -> {t1}"
317 return t1
318 end
319 end
320 #self.modelbuilder.warning(node, "Type Error: {col.length} conflicting types: <{col.join(", ")}>")
321 return null
322 end
323 end
324
325 redef class Variable
326 # The declared type of the variable
327 var declared_type: nullable MType
328 end
329
330 redef class FlowContext
331 # Store changes of types because of type evolution
332 private var vars: HashMap[Variable, nullable MType] = new HashMap[Variable, nullable MType]
333 private var cache: HashMap[Variable, nullable Array[nullable MType]] = new HashMap[Variable, nullable Array[nullable MType]]
334
335 # Adapt the variable to a static type
336 # Warning1: do not modify vars directly.
337 # Warning2: sub-flow may have cached a unadapted variabial
338 private fun set_var(variable: Variable, mtype: nullable MType)
339 do
340 self.vars[variable] = mtype
341 self.cache.keys.remove(variable)
342 end
343
344 private fun collect_types(variable: Variable): nullable Array[nullable MType]
345 do
346 if cache.has_key(variable) then
347 return cache[variable]
348 end
349 var res: nullable Array[nullable MType] = null
350 if vars.has_key(variable) then
351 var mtype = vars[variable]
352 res = [mtype]
353 else if self.previous.is_empty then
354 # Root flow
355 res = [variable.declared_type]
356 else
357 for flow in self.previous do
358 if flow.is_unreachable then continue
359 var r2 = flow.collect_types(variable)
360 if r2 == null then continue
361 if res == null then
362 res = r2.to_a
363 else
364 for t in r2 do
365 if not res.has(t) then res.add(t)
366 end
367 end
368 end
369 end
370 cache[variable] = res
371 return res
372 end
373 end
374
375 redef class APropdef
376 # The entry point of the whole typing analysis
377 fun do_typing(modelbuilder: ModelBuilder)
378 do
379 end
380
381 # The variable associated to the reciever (if any)
382 var selfvariable: nullable Variable
383 end
384
385 redef class AConcreteMethPropdef
386 redef fun do_typing(modelbuilder: ModelBuilder)
387 do
388 var nclassdef = self.parent.as(AClassdef)
389 var mpropdef = self.mpropdef.as(not null)
390 var v = new TypeVisitor(modelbuilder, nclassdef, mpropdef)
391 self.selfvariable = v.selfvariable
392
393 var nblock = self.n_block
394 if nblock == null then return
395
396 var mmethoddef = self.mpropdef.as(not null)
397 for i in [0..mmethoddef.msignature.arity[ do
398 var mtype = mmethoddef.msignature.parameter_mtypes[i]
399 if mmethoddef.msignature.vararg_rank == i then
400 var arrayclass = v.get_mclass(self.n_signature.n_params[i], "Array")
401 if arrayclass == null then return # Skip error
402 mtype = arrayclass.get_mtype([mtype])
403 end
404 var variable = self.n_signature.n_params[i].variable
405 assert variable != null
406 variable.declared_type = mtype
407 end
408 v.visit_stmt(nblock)
409
410 if not nblock.after_flow_context.is_unreachable and mmethoddef.msignature.return_mtype != null then
411 # We reach the end of the function without having a return, it is bad
412 v.error(self, "Control error: Reached end of function (a 'return' with a value was expected).")
413 end
414 end
415 end
416
417 redef class AAttrPropdef
418 redef fun do_typing(modelbuilder: ModelBuilder)
419 do
420 var nclassdef = self.parent.as(AClassdef)
421 var v = new TypeVisitor(modelbuilder, nclassdef, self.mpropdef.as(not null))
422 self.selfvariable = v.selfvariable
423
424 var nexpr = self.n_expr
425 if nexpr != null then
426 var mtype = self.mpropdef.static_mtype
427 v.visit_expr_subtype(nexpr, mtype)
428 end
429 end
430 end
431
432 ###
433
434 redef class AExpr
435 # The static type of the expression.
436 # null if self is a statement of in case of error
437 var mtype: nullable MType = null
438
439 # Is the statement correctly typed?
440 # Used to distinguish errors and statements when `mtype' == null
441 var is_typed: Bool = false
442
443 # Return the variable read (if any)
444 # Used to perform adaptive typing
445 fun its_variable: nullable Variable do return null
446
447 private fun accept_typing(v: TypeVisitor)
448 do
449 v.error(self, "no implemented accept_typing for {self.class_name}")
450 end
451 end
452
453 redef class ABlockExpr
454 redef fun accept_typing(v)
455 do
456 for e in self.n_expr do v.visit_stmt(e)
457 self.is_typed = true
458 end
459 end
460
461 redef class AVardeclExpr
462 redef fun accept_typing(v)
463 do
464 var variable = self.variable
465 if variable == null then return # Skip error
466
467 var ntype = self.n_type
468 var mtype: nullable MType
469 if ntype == null then
470 mtype = null
471 else
472 mtype = v.resolve_mtype(ntype)
473 if mtype == null then return # Skip error
474 end
475
476 var nexpr = self.n_expr
477 if nexpr != null then
478 if mtype != null then
479 v.visit_expr_subtype(nexpr, mtype)
480 else
481 mtype = v.visit_expr(nexpr)
482 if mtype == null then return # Skip error
483 end
484 end
485
486 if mtype == null then
487 mtype = v.get_mclass(self, "Object").mclass_type.as_nullable
488 end
489
490 variable.declared_type = mtype
491 v.set_variable(self, variable, mtype)
492
493 #debug("var {variable}: {mtype}")
494
495 self.is_typed = true
496 end
497 end
498
499 redef class AVarExpr
500 redef fun its_variable do return self.variable
501 redef fun accept_typing(v)
502 do
503 var variable = self.variable
504 if variable == null then return # Skip error
505
506 var mtype = v.get_variable(self, variable)
507 if mtype != null then
508 #debug("{variable} is {mtype}")
509 else
510 #debug("{variable} is untyped")
511 end
512
513 self.mtype = mtype
514 end
515 end
516
517 redef class AVarAssignExpr
518 redef fun accept_typing(v)
519 do
520 var variable = self.variable
521 assert variable != null
522
523 var mtype = v.visit_expr_subtype(n_value, variable.declared_type)
524
525 v.set_variable(self, variable, mtype)
526
527 self.is_typed = true
528 end
529 end
530
531 redef class AReassignFormExpr
532 # The method designed by the reassign operator.
533 var reassign_property: nullable MMethodDef = null
534
535 var read_type: nullable MType = null
536
537 # Determine the `reassign_property'
538 # `readtype' is the type of the reading of the left value.
539 # `writetype' is the type of the writing of the left value.
540 # (Because of ACallReassignExpr, both can be different.
541 # Return the static type of the value to store.
542 private fun resolve_reassignment(v: TypeVisitor, readtype, writetype: MType): nullable MType
543 do
544 var reassign_name: String
545 if self.n_assign_op isa APlusAssignOp then
546 reassign_name = "+"
547 else if self.n_assign_op isa AMinusAssignOp then
548 reassign_name = "-"
549 else
550 abort
551 end
552
553 self.read_type = readtype
554
555 if readtype isa MNullType then
556 v.error(self, "Error: Method '{reassign_name}' call on 'null'.")
557 return null
558 end
559
560 var mpropdef = v.get_method(self, readtype, reassign_name, false)
561 if mpropdef == null then return null # Skip error
562
563 self.reassign_property = mpropdef
564
565 var msignature = mpropdef.msignature
566 assert msignature!= null
567 msignature = v.resolve_signature_for(msignature, readtype, false)
568
569 var rettype = msignature.return_mtype
570 assert msignature.arity == 1 and rettype != null
571
572 var value_type = v.visit_expr_subtype(self.n_value, msignature.parameter_mtypes.first)
573 if value_type == null then return null # Skip error
574
575 v.check_subtype(self, rettype, writetype)
576 return rettype
577 end
578 end
579
580 redef class AVarReassignExpr
581 redef fun accept_typing(v)
582 do
583 var variable = self.variable
584 assert variable != null
585
586 var readtype = v.get_variable(self, variable)
587 if readtype == null then return
588
589 var writetype = variable.declared_type
590 if writetype == null then return
591
592 var rettype = self.resolve_reassignment(v, readtype, writetype)
593
594 v.set_variable(self, variable, rettype)
595
596 self.is_typed = true
597 end
598 end
599
600
601 redef class AContinueExpr
602 redef fun accept_typing(v)
603 do
604 var nexpr = self.n_expr
605 if nexpr != null then
606 var mtype = v.visit_expr(nexpr)
607 end
608 self.is_typed = true
609 end
610 end
611
612 redef class ABreakExpr
613 redef fun accept_typing(v)
614 do
615 var nexpr = self.n_expr
616 if nexpr != null then
617 var mtype = v.visit_expr(nexpr)
618 end
619 self.is_typed = true
620 end
621 end
622
623 redef class AReturnExpr
624 redef fun accept_typing(v)
625 do
626 var nexpr = self.n_expr
627 var ret_type = v.mpropdef.as(MMethodDef).msignature.return_mtype
628 if nexpr != null then
629 if ret_type != null then
630 var mtype = v.visit_expr_subtype(nexpr, ret_type)
631 else
632 var mtype = v.visit_expr(nexpr)
633 v.error(self, "Error: Return with value in a procedure.")
634 end
635 else if ret_type != null then
636 v.error(self, "Error: Return without value in a function.")
637 end
638 self.is_typed = true
639 end
640 end
641
642 redef class AAbortExpr
643 redef fun accept_typing(v)
644 do
645 self.is_typed = true
646 end
647 end
648
649 redef class AIfExpr
650 redef fun accept_typing(v)
651 do
652 v.visit_expr_bool(n_expr)
653
654 v.visit_stmt(n_then)
655 v.visit_stmt(n_else)
656 self.is_typed = true
657 end
658 end
659
660 redef class AIfexprExpr
661 redef fun accept_typing(v)
662 do
663 v.visit_expr_bool(n_expr)
664
665 var t1 = v.visit_expr(n_then)
666 var t2 = v.visit_expr(n_else)
667
668 if t1 == null or t2 == null then
669 return # Skip error
670 end
671
672 var t = v.merge_types(self, [t1, t2])
673 if t == null then
674 v.error(self, "Type Error: ambiguous type {t1} vs {t2}")
675 end
676 self.mtype = t
677 end
678 end
679
680 redef class ADoExpr
681 redef fun accept_typing(v)
682 do
683 v.visit_stmt(n_block)
684 self.is_typed = true
685 end
686 end
687
688 redef class AWhileExpr
689 redef fun accept_typing(v)
690 do
691 v.visit_expr_bool(n_expr)
692
693 v.visit_stmt(n_block)
694 self.is_typed = true
695 end
696 end
697
698 redef class ALoopExpr
699 redef fun accept_typing(v)
700 do
701 v.visit_stmt(n_block)
702 self.is_typed = true
703 end
704 end
705
706 redef class AForExpr
707 redef fun accept_typing(v)
708 do
709 var mtype = v.visit_expr(n_expr)
710 if mtype == null then return
711
712 var colcla = v.get_mclass(self, "Collection")
713 if colcla == null then return
714 var objcla = v.get_mclass(self, "Object")
715 if objcla == null then return
716 if v.is_subtype(mtype, colcla.get_mtype([objcla.mclass_type.as_nullable])) then
717 var coltype = mtype.supertype_to(v.mmodule, v.anchor, colcla)
718 assert coltype isa MGenericType
719 var variables = self.variables
720 if variables.length != 1 then
721 v.error(self, "Type Error: Expected one variable")
722 else
723 variables.first.declared_type = coltype.arguments.first
724 end
725 else
726 v.modelbuilder.error(self, "TODO: Do 'for' on {mtype}")
727 end
728
729 v.visit_stmt(n_block)
730 self.is_typed = true
731 end
732 end
733
734 redef class AAssertExpr
735 redef fun accept_typing(v)
736 do
737 v.visit_expr_bool(n_expr)
738
739 v.visit_stmt(n_else)
740 self.is_typed = true
741 end
742 end
743
744 redef class AOrExpr
745 redef fun accept_typing(v)
746 do
747 v.visit_expr_bool(n_expr)
748 v.visit_expr_bool(n_expr2)
749 self.mtype = v.type_bool(self)
750 end
751 end
752
753 redef class AAndExpr
754 redef fun accept_typing(v)
755 do
756 v.visit_expr_bool(n_expr)
757 v.visit_expr_bool(n_expr2)
758 self.mtype = v.type_bool(self)
759 end
760 end
761
762
763 redef class ANotExpr
764 redef fun accept_typing(v)
765 do
766 v.visit_expr_bool(n_expr)
767 self.mtype = v.type_bool(self)
768 end
769 end
770
771 redef class AOrElseExpr
772 redef fun accept_typing(v)
773 do
774 var t1 = v.visit_expr(n_expr)
775 var t2 = v.visit_expr(n_expr2)
776
777 if t1 == null or t2 == null then
778 return # Skip error
779 end
780
781 if t1 isa MNullableType then
782 t1 = t1.mtype
783 end
784
785 var t = v.merge_types(self, [t1, t2])
786 if t == null then
787 v.error(self, "Type Error: ambiguous type {t1} vs {t2}")
788 end
789 self.mtype = t
790 end
791 end
792
793 redef class AEeExpr
794 redef fun accept_typing(v)
795 do
796 v.visit_expr(n_expr)
797 v.visit_expr(n_expr2)
798 self.mtype = v.type_bool(self)
799 end
800 end
801
802 redef class ATrueExpr
803 redef fun accept_typing(v)
804 do
805 self.mtype = v.type_bool(self)
806 end
807 end
808
809 redef class AFalseExpr
810 redef fun accept_typing(v)
811 do
812 self.mtype = v.type_bool(self)
813 end
814 end
815
816 redef class AIntExpr
817 redef fun accept_typing(v)
818 do
819 var mclass = v.get_mclass(self, "Int")
820 if mclass == null then return # Forward error
821 self.mtype = mclass.mclass_type
822 end
823 end
824
825 redef class AFloatExpr
826 redef fun accept_typing(v)
827 do
828 var mclass = v.get_mclass(self, "Float")
829 if mclass == null then return # Forward error
830 self.mtype = mclass.mclass_type
831 end
832 end
833
834 redef class ACharExpr
835 redef fun accept_typing(v)
836 do
837 var mclass = v.get_mclass(self, "Char")
838 if mclass == null then return # Forward error
839 self.mtype = mclass.mclass_type
840 end
841 end
842
843 redef class AStringFormExpr
844 redef fun accept_typing(v)
845 do
846 var mclass = v.get_mclass(self, "String")
847 if mclass == null then return # Forward error
848 self.mtype = mclass.mclass_type
849 end
850 end
851
852 redef class ASuperstringExpr
853 redef fun accept_typing(v)
854 do
855 var mclass = v.get_mclass(self, "String")
856 if mclass == null then return # Forward error
857 self.mtype = mclass.mclass_type
858 for nexpr in self.n_exprs do
859 var t = v.visit_expr(nexpr)
860 end
861 end
862 end
863
864 redef class AArrayExpr
865 redef fun accept_typing(v)
866 do
867 var mtypes = new Array[nullable MType]
868 for e in self.n_exprs.n_exprs do
869 var t = v.visit_expr(e)
870 if t == null then
871 return # Skip error
872 end
873 mtypes.add(t)
874 end
875 var mtype = v.merge_types(self, mtypes)
876 if mtype == null then
877 v.error(self, "Type Error: ambiguous array type {mtypes.join(" ")}")
878 return
879 end
880 var mclass = v.get_mclass(self, "Array")
881 if mclass == null then return # Forward error
882 self.mtype = mclass.get_mtype([mtype])
883 end
884 end
885
886 redef class ARangeExpr
887 redef fun accept_typing(v)
888 do
889 var t1 = v.visit_expr(self.n_expr)
890 var t2 = v.visit_expr(self.n_expr2)
891 if t1 == null or t2 == null then return
892 var mclass = v.get_mclass(self, "Range")
893 if mclass == null then return # Forward error
894 if v.is_subtype(t1, t2) then
895 self.mtype = mclass.get_mtype([t2])
896 else if v.is_subtype(t2, t1) then
897 self.mtype = mclass.get_mtype([t1])
898 else
899 v.error(self, "Type Error: Cannot create range: {t1} vs {t2}")
900 end
901 end
902 end
903
904 redef class ANullExpr
905 redef fun accept_typing(v)
906 do
907 self.mtype = v.mmodule.model.null_type
908 end
909 end
910
911 redef class AIsaExpr
912 # The static type to cast to.
913 # (different from the static type of the expression that is Bool).
914 var cast_type: nullable MType
915 redef fun accept_typing(v)
916 do
917 var mtype = v.visit_expr_cast(self, self.n_expr, self.n_type)
918 self.cast_type = mtype
919
920 var variable = self.n_expr.its_variable
921 if variable != null then
922 var orig = self.n_expr.mtype
923 var from = if orig != null then orig.to_s else "invalid"
924 var to = if mtype != null then mtype.to_s else "invalid"
925 #debug("adapt {variable}: {from} -> {to}")
926 self.after_flow_context.when_true.set_var(variable, mtype)
927 end
928
929 self.mtype = v.type_bool(self)
930 end
931 end
932
933 redef class AAsCastExpr
934 redef fun accept_typing(v)
935 do
936 self.mtype = v.visit_expr_cast(self, self.n_expr, self.n_type)
937 end
938 end
939
940 redef class AAsNotnullExpr
941 redef fun accept_typing(v)
942 do
943 var mtype = v.visit_expr(self.n_expr)
944 if mtype isa MNullType then
945 v.error(self, "Type error: as(not null) on null")
946 return
947 end
948 if mtype isa MNullableType then
949 self.mtype = mtype.mtype
950 return
951 end
952 # TODO: warn on useless as not null
953 self.mtype = mtype
954 end
955 end
956
957 redef class AProxyExpr
958 redef fun accept_typing(v)
959 do
960 self.mtype = v.visit_expr(self.n_expr)
961 end
962 end
963
964 redef class ASelfExpr
965 redef var its_variable: nullable Variable
966 redef fun accept_typing(v)
967 do
968 var variable = v.selfvariable
969 self.its_variable = variable
970 self.mtype = v.get_variable(self, variable)
971 end
972 end
973
974 ## MESSAGE SENDING AND PROPERTY
975
976 redef class ASendExpr
977 # The property invoked by the send.
978 var mproperty: nullable MMethod
979
980 redef fun accept_typing(v)
981 do
982 var recvtype = v.visit_expr(self.n_expr)
983 var name = self.property_name
984
985 if recvtype == null then return # Forward error
986 if recvtype isa MNullType then
987 v.error(self, "Error: Method '{name}' call on 'null'.")
988 return
989 end
990
991 var propdef = v.get_method(self, recvtype, name, self.n_expr isa ASelfExpr)
992 if propdef == null then return
993 var mproperty = propdef.mproperty
994 self.mproperty = mproperty
995 var msignature = propdef.msignature
996 if msignature == null then abort # Forward error
997
998 var for_self = self.n_expr isa ASelfExpr
999 msignature = v.resolve_signature_for(msignature, recvtype, for_self)
1000
1001 var args = compute_raw_arguments
1002
1003 v.check_signature(self, args, name, msignature)
1004
1005 if mproperty.is_init then
1006 var vmpropdef = v.mpropdef
1007 if not (vmpropdef isa MMethodDef and vmpropdef.mproperty.is_init) then
1008 v.error(self, "Can call a init only in another init")
1009 end
1010 end
1011
1012 var ret = msignature.return_mtype
1013 if ret != null then
1014 self.mtype = ret
1015 else
1016 self.is_typed = true
1017 end
1018 end
1019
1020 # The name of the property
1021 # Each subclass simply provide the correct name.
1022 private fun property_name: String is abstract
1023
1024 # An array of all arguments (excluding self)
1025 fun compute_raw_arguments: Array[AExpr] is abstract
1026 end
1027
1028 redef class ABinopExpr
1029 redef fun compute_raw_arguments do return [n_expr2]
1030 end
1031 redef class AEqExpr
1032 redef fun property_name do return "=="
1033 redef fun accept_typing(v)
1034 do
1035 super
1036
1037 var variable = self.n_expr.its_variable
1038 if variable == null then return
1039 var mtype = self.n_expr2.mtype
1040 if not mtype isa MNullType then return
1041 var vartype = v.get_variable(self, variable)
1042 if not vartype isa MNullableType then return
1043 self.after_flow_context.when_true.set_var(variable, mtype)
1044 self.after_flow_context.when_false.set_var(variable, vartype.mtype)
1045 #debug("adapt {variable}:{vartype} ; true->{mtype} false->{vartype.mtype}")
1046 end
1047 end
1048 redef class ANeExpr
1049 redef fun property_name do return "!="
1050 redef fun accept_typing(v)
1051 do
1052 super
1053
1054 var variable = self.n_expr.its_variable
1055 if variable == null then return
1056 var mtype = self.n_expr2.mtype
1057 if not mtype isa MNullType then return
1058 var vartype = v.get_variable(self, variable)
1059 if not vartype isa MNullableType then return
1060 self.after_flow_context.when_false.set_var(variable, mtype)
1061 self.after_flow_context.when_true.set_var(variable, vartype.mtype)
1062 #debug("adapt {variable}:{vartype} ; true->{vartype.mtype} false->{mtype}")
1063 end
1064 end
1065 redef class ALtExpr
1066 redef fun property_name do return "<"
1067 end
1068 redef class ALeExpr
1069 redef fun property_name do return "<="
1070 end
1071 redef class ALlExpr
1072 redef fun property_name do return "<<"
1073 end
1074 redef class AGtExpr
1075 redef fun property_name do return ">"
1076 end
1077 redef class AGeExpr
1078 redef fun property_name do return ">="
1079 end
1080 redef class AGgExpr
1081 redef fun property_name do return ">>"
1082 end
1083 redef class APlusExpr
1084 redef fun property_name do return "+"
1085 end
1086 redef class AMinusExpr
1087 redef fun property_name do return "-"
1088 end
1089 redef class AStarshipExpr
1090 redef fun property_name do return "<=>"
1091 end
1092 redef class AStarExpr
1093 redef fun property_name do return "*"
1094 end
1095 redef class ASlashExpr
1096 redef fun property_name do return "/"
1097 end
1098 redef class APercentExpr
1099 redef fun property_name do return "%"
1100 end
1101
1102 redef class AUminusExpr
1103 redef fun property_name do return "unary -"
1104 redef fun compute_raw_arguments do return new Array[AExpr]
1105 end
1106
1107
1108 redef class ACallExpr
1109 redef fun property_name do return n_id.text
1110 redef fun compute_raw_arguments do return n_args.to_a
1111 end
1112
1113 redef class ACallAssignExpr
1114 redef fun property_name do return n_id.text + "="
1115 redef fun compute_raw_arguments
1116 do
1117 var res = n_args.to_a
1118 res.add(n_value)
1119 return res
1120 end
1121 end
1122
1123 redef class ABraExpr
1124 redef fun property_name do return "[]"
1125 redef fun compute_raw_arguments do return n_args.to_a
1126 end
1127
1128 redef class ABraAssignExpr
1129 redef fun property_name do return "[]="
1130 redef fun compute_raw_arguments
1131 do
1132 var res = n_args.to_a
1133 res.add(n_value)
1134 return res
1135 end
1136 end
1137
1138 redef class ASendReassignFormExpr
1139 # The property invoked for the writing
1140 var write_mproperty: nullable MMethod = null
1141
1142 redef fun accept_typing(v)
1143 do
1144 var recvtype = v.visit_expr(self.n_expr)
1145 var name = self.property_name
1146
1147 if recvtype == null then return # Forward error
1148 if recvtype isa MNullType then
1149 v.error(self, "Error: Method '{name}' call on 'null'.")
1150 return
1151 end
1152
1153 var propdef = v.get_method(self, recvtype, name, self.n_expr isa ASelfExpr)
1154 if propdef == null then return
1155 var mproperty = propdef.mproperty
1156 self.mproperty = mproperty
1157 var msignature = propdef.msignature
1158 if msignature == null then abort # Forward error
1159 var for_self = self.n_expr isa ASelfExpr
1160 msignature = v.resolve_signature_for(msignature, recvtype, for_self)
1161
1162 var args = compute_raw_arguments
1163
1164 v.check_signature(self, args, name, msignature)
1165
1166 var readtype = msignature.return_mtype
1167 if readtype == null then
1168 v.error(self, "Error: {name} is not a function")
1169 return
1170 end
1171
1172 var wpropdef = v.get_method(self, recvtype, name + "=", self.n_expr isa ASelfExpr)
1173 if wpropdef == null then return
1174 var wmproperty = wpropdef.mproperty
1175 self.write_mproperty = wmproperty
1176 var wmsignature = wpropdef.msignature
1177 if wmsignature == null then abort # Forward error
1178 wmsignature = v.resolve_signature_for(wmsignature, recvtype, for_self)
1179
1180 var wtype = self.resolve_reassignment(v, readtype, wmsignature.parameter_mtypes.last)
1181 if wtype == null then return
1182
1183 args.add(self.n_value)
1184 v.check_signature(self, args, name + "=", wmsignature)
1185
1186 self.is_typed = true
1187 end
1188 end
1189
1190 redef class ACallReassignExpr
1191 redef fun property_name do return n_id.text
1192 redef fun compute_raw_arguments do return n_args.to_a
1193 end
1194
1195 redef class ABraReassignExpr
1196 redef fun property_name do return "[]"
1197 redef fun compute_raw_arguments do return n_args.to_a
1198 end
1199
1200 redef class AInitExpr
1201 redef fun property_name do return "init"
1202 redef fun compute_raw_arguments do return n_args.to_a
1203 end
1204
1205 redef class AExprs
1206 fun to_a: Array[AExpr] do return self.n_exprs.to_a
1207 end
1208
1209 ###
1210
1211 redef class ASuperExpr
1212 # The method to call if the super is in fact a 'super init call'
1213 # Note: if the super is a normal call-next-method, then this attribute is null
1214 var mproperty: nullable MMethod
1215
1216 redef fun accept_typing(v)
1217 do
1218 var recvtype = v.nclassdef.mclassdef.bound_mtype
1219 var mproperty = v.mpropdef.mproperty
1220 if not mproperty isa MMethod then
1221 v.error(self, "Error: super only usable in a method")
1222 return
1223 end
1224 var superprops = mproperty.lookup_super_definitions(v.mmodule, recvtype)
1225 if superprops.length == 0 then
1226 if mproperty.is_init and v.mpropdef.is_intro then
1227 process_superinit(v)
1228 return
1229 end
1230 v.error(self, "Error: No super method to call for {mproperty}.")
1231 return
1232 else if superprops.length > 1 then
1233 v.modelbuilder.warning(self, "Error: Conflicting super method to call for {mproperty}: {superprops.join(", ")}.")
1234 return
1235 end
1236 var superprop = superprops.first
1237 assert superprop isa MMethodDef
1238
1239 var msignature = superprop.msignature.as(not null)
1240 msignature = v.resolve_signature_for(msignature, recvtype, true)
1241 var args = self.n_args.to_a
1242 if args.length > 0 then
1243 v.check_signature(self, args, mproperty.name, msignature)
1244 end
1245 self.mtype = msignature.return_mtype
1246 end
1247
1248 private fun process_superinit(v: TypeVisitor)
1249 do
1250 var recvtype = v.nclassdef.mclassdef.bound_mtype
1251 var mproperty = v.mpropdef.mproperty
1252 var superprop: nullable MMethodDef = null
1253 for msupertype in v.nclassdef.mclassdef.supertypes do
1254 msupertype = msupertype.anchor_to(v.mmodule, recvtype)
1255 var errcount = v.modelbuilder.toolcontext.error_count
1256 var candidate = v.try_get_mproperty_by_name2(self, msupertype, mproperty.name).as(nullable MMethod)
1257 if candidate == null then
1258 if v.modelbuilder.toolcontext.error_count > errcount then return # Forard error
1259 continue # Try next super-class
1260 end
1261 if superprop != null and superprop.mproperty != candidate then
1262 v.error(self, "Error: conflicting super constructor to call for {mproperty}: {candidate.full_name}, {superprop.mproperty.full_name}")
1263 return
1264 end
1265 var candidatedefs = candidate.lookup_definitions(v.mmodule, recvtype)
1266 if superprop != null then
1267 if superprop == candidatedefs.first then continue
1268 candidatedefs.add(superprop)
1269 end
1270 if candidatedefs.length > 1 then
1271 v.error(self, "Error: confliting property definitions for property {mproperty} in {recvtype}: {candidatedefs.join(", ")}")
1272 return
1273 end
1274 superprop = candidatedefs.first
1275 end
1276 if superprop == null then
1277 v.error(self, "Error: No super method to call for {mproperty}.")
1278 return
1279 end
1280 self.mproperty = superprop.mproperty
1281
1282 var args = self.n_args.to_a
1283 var msignature = superprop.msignature.as(not null)
1284 msignature = v.resolve_signature_for(msignature, recvtype, true)
1285 if args.length > 0 then
1286 v.check_signature(self, args, mproperty.name, msignature)
1287 else
1288 # TODO: Check signature
1289 end
1290
1291 self.is_typed = true
1292 end
1293 end
1294
1295 ####
1296
1297 redef class ANewExpr
1298 # The constructor invoked by the new.
1299 var mproperty: nullable MMethod
1300
1301 redef fun accept_typing(v)
1302 do
1303 var recvtype = v.resolve_mtype(self.n_type)
1304 if recvtype == null then return
1305 self.mtype = recvtype
1306
1307 if not recvtype isa MClassType then
1308 if recvtype isa MNullableType then
1309 v.error(self, "Type error: cannot instantiate the nullable type {recvtype}.")
1310 return
1311 else
1312 v.error(self, "Type error: cannot instantiate the formal type {recvtype}.")
1313 return
1314 end
1315 end
1316
1317 var name: String
1318 var nid = self.n_id
1319 if nid != null then
1320 name = nid.text
1321 else
1322 name = "init"
1323 end
1324 var propdef = v.get_method(self, recvtype, name, false)
1325 if propdef == null then return
1326
1327 self.mproperty = propdef.mproperty
1328
1329 if not propdef.mproperty.is_init_for(recvtype.mclass) then
1330 v.error(self, "Error: {name} is not a constructor.")
1331 return
1332 end
1333
1334 var msignature = propdef.msignature.as(not null)
1335 msignature = v.resolve_signature_for(msignature, recvtype, false)
1336
1337 var args = n_args.to_a
1338 v.check_signature(self, args, name, msignature)
1339 end
1340 end
1341
1342 ####
1343
1344 redef class AAttrFormExpr
1345 # The attribute acceded.
1346 var mproperty: nullable MAttribute
1347
1348 # The static type of the attribute.
1349 var attr_type: nullable MType
1350
1351 # Resolve the attribute acceded.
1352 private fun resolve_property(v: TypeVisitor)
1353 do
1354 var recvtype = v.visit_expr(self.n_expr)
1355 if recvtype == null then return # Skip error
1356 var name = self.n_id.text
1357 if recvtype isa MNullType then
1358 v.error(self, "Error: Attribute '{name}' access on 'null'.")
1359 return
1360 end
1361
1362 var unsafe_type = v.anchor_to(recvtype)
1363 var mproperty = v.try_get_mproperty_by_name2(self, unsafe_type, name)
1364 if mproperty == null then
1365 v.modelbuilder.error(self, "Error: Attribute {name} doesn't exists in {recvtype}.")
1366 return
1367 end
1368 assert mproperty isa MAttribute
1369 self.mproperty = mproperty
1370
1371 var mpropdefs = mproperty.lookup_definitions(v.mmodule, unsafe_type)
1372 assert mpropdefs.length == 1
1373 var mpropdef = mpropdefs.first
1374 var attr_type = mpropdef.static_mtype.as(not null)
1375 attr_type = v.resolve_for(attr_type, recvtype, self.n_expr isa ASelfExpr)
1376 self.attr_type = attr_type
1377 end
1378 end
1379
1380 redef class AAttrExpr
1381 redef fun accept_typing(v)
1382 do
1383 self.resolve_property(v)
1384 self.mtype = self.attr_type
1385 end
1386 end
1387
1388
1389 redef class AAttrAssignExpr
1390 redef fun accept_typing(v)
1391 do
1392 self.resolve_property(v)
1393 var mtype = self.attr_type
1394
1395 v.visit_expr_subtype(self.n_value, mtype)
1396 self.is_typed = true
1397 end
1398 end
1399
1400 redef class AAttrReassignExpr
1401 redef fun accept_typing(v)
1402 do
1403 self.resolve_property(v)
1404 var mtype = self.attr_type
1405 if mtype == null then return # Skip error
1406
1407 self.resolve_reassignment(v, mtype, mtype)
1408
1409 self.is_typed = true
1410 end
1411 end
1412
1413 redef class AIssetAttrExpr
1414 redef fun accept_typing(v)
1415 do
1416 self.resolve_property(v)
1417 var mtype = self.attr_type
1418 if mtype == null then return # Skip error
1419
1420 var recvtype = self.n_expr.mtype.as(not null)
1421 var bound = v.resolve_for(mtype, recvtype, false)
1422 if bound isa MNullableType then
1423 v.error(self, "Error: isset on a nullable attribute.")
1424 end
1425 self.mtype = v.type_bool(self)
1426 end
1427 end
1428
1429 ###
1430
1431 redef class AClosureCallExpr
1432 redef fun accept_typing(v)
1433 do
1434 #TODO
1435 end
1436 end
1437
1438 ###
1439
1440 redef class ADebugTypeExpr
1441 redef fun accept_typing(v)
1442 do
1443 var expr = v.visit_expr(self.n_expr)
1444 if expr == null then return
1445 var unsafe = v.anchor_to(expr)
1446 var ntype = self.n_type
1447 var mtype = v.resolve_mtype(ntype)
1448 if mtype != null and mtype != expr then
1449 var umtype = v.anchor_to(mtype)
1450 v.modelbuilder.warning(self, "Found type {expr} (-> {unsafe}), expected {mtype} (-> {umtype})")
1451 end
1452 end
1453 end