Doc review on newmodel.
[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 end
381
382 redef class AConcreteMethPropdef
383 redef fun do_typing(modelbuilder: ModelBuilder)
384 do
385 var nclassdef = self.parent.as(AClassdef)
386 var mpropdef = self.mpropdef.as(not null)
387 var v = new TypeVisitor(modelbuilder, nclassdef, mpropdef)
388
389 var nblock = self.n_block
390 if nblock == null then return
391
392 var mmethoddef = self.mpropdef.as(not null)
393 for i in [0..mmethoddef.msignature.arity[ do
394 var mtype = mmethoddef.msignature.parameter_mtypes[i]
395 if mmethoddef.msignature.vararg_rank == i then
396 var arrayclass = v.get_mclass(self.n_signature.n_params[i], "Array")
397 if arrayclass == null then return # Skip error
398 mtype = arrayclass.get_mtype([mtype])
399 end
400 var variable = self.n_signature.n_params[i].variable
401 assert variable != null
402 variable.declared_type = mtype
403 end
404 v.visit_stmt(nblock)
405
406 if not nblock.after_flow_context.is_unreachable and mmethoddef.msignature.return_mtype != null then
407 # We reach the end of the function without having a return, it is bad
408 v.error(self, "Control error: Reached end of function (a 'return' with a value was expected).")
409 end
410 end
411 end
412
413 redef class AAttrPropdef
414 redef fun do_typing(modelbuilder: ModelBuilder)
415 do
416 var nclassdef = self.parent.as(AClassdef)
417 var v = new TypeVisitor(modelbuilder, nclassdef, self.mpropdef.as(not null))
418
419 var nexpr = self.n_expr
420 if nexpr != null then
421 var mtype = self.mpropdef.static_mtype
422 v.visit_expr_subtype(nexpr, mtype)
423 end
424 end
425 end
426
427 ###
428
429 redef class AExpr
430 # The static type of the expression.
431 # null if self is a statement of in case of error
432 var mtype: nullable MType = null
433
434 # Is the statement correctly typed?
435 # Used to distinguish errors and statements when `mtype' == null
436 var is_typed: Bool = false
437
438 # Return the variable read (if any)
439 # Used to perform adaptive typing
440 fun its_variable: nullable Variable do return null
441
442 private fun accept_typing(v: TypeVisitor)
443 do
444 v.error(self, "no implemented accept_typing for {self.class_name}")
445 end
446 end
447
448 redef class ABlockExpr
449 redef fun accept_typing(v)
450 do
451 for e in self.n_expr do v.visit_stmt(e)
452 self.is_typed = true
453 end
454 end
455
456 redef class AVardeclExpr
457 redef fun accept_typing(v)
458 do
459 var variable = self.variable
460 if variable == null then return # Skip error
461
462 var ntype = self.n_type
463 var mtype: nullable MType
464 if ntype == null then
465 mtype = null
466 else
467 mtype = v.resolve_mtype(ntype)
468 if mtype == null then return # Skip error
469 end
470
471 var nexpr = self.n_expr
472 if nexpr != null then
473 if mtype != null then
474 v.visit_expr_subtype(nexpr, mtype)
475 else
476 mtype = v.visit_expr(nexpr)
477 if mtype == null then return # Skip error
478 end
479 end
480
481 if mtype == null then
482 mtype = v.get_mclass(self, "Object").mclass_type
483 end
484
485 variable.declared_type = mtype
486 v.set_variable(self, variable, mtype)
487
488 #debug("var {variable}: {mtype}")
489
490 self.is_typed = true
491 end
492 end
493
494 redef class AVarExpr
495 redef fun its_variable do return self.variable
496 redef fun accept_typing(v)
497 do
498 var variable = self.variable
499 if variable == null then return # Skip error
500
501 var mtype = v.get_variable(self, variable)
502 if mtype != null then
503 #debug("{variable} is {mtype}")
504 else
505 #debug("{variable} is untyped")
506 end
507
508 self.mtype = mtype
509 end
510 end
511
512 redef class AVarAssignExpr
513 redef fun accept_typing(v)
514 do
515 var variable = self.variable
516 assert variable != null
517
518 var mtype = v.visit_expr_subtype(n_value, variable.declared_type)
519
520 v.set_variable(self, variable, mtype)
521
522 self.is_typed = true
523 end
524 end
525
526 redef class AReassignFormExpr
527 # The method designed by the reassign operator.
528 var reassign_property: nullable MMethodDef = null
529
530 var read_type: nullable MType = null
531
532 # Determine the `reassign_property'
533 # `readtype' is the type of the reading of the left value.
534 # `writetype' is the type of the writing of the left value.
535 # (Because of ACallReassignExpr, both can be different.
536 # Return the static type of the value to store.
537 private fun resolve_reassignment(v: TypeVisitor, readtype, writetype: MType): nullable MType
538 do
539 var reassign_name: String
540 if self.n_assign_op isa APlusAssignOp then
541 reassign_name = "+"
542 else if self.n_assign_op isa AMinusAssignOp then
543 reassign_name = "-"
544 else
545 abort
546 end
547
548 self.read_type = readtype
549
550 if readtype isa MNullType then
551 v.error(self, "Error: Method '{reassign_name}' call on 'null'.")
552 return null
553 end
554
555 var mpropdef = v.get_method(self, readtype, reassign_name, false)
556 if mpropdef == null then return null # Skip error
557
558 self.reassign_property = mpropdef
559
560 var msignature = mpropdef.msignature
561 assert msignature!= null
562 msignature = v.resolve_signature_for(msignature, readtype, false)
563
564 var rettype = msignature.return_mtype
565 assert msignature.arity == 1 and rettype != null
566
567 var value_type = v.visit_expr_subtype(self.n_value, msignature.parameter_mtypes.first)
568 if value_type == null then return null # Skip error
569
570 v.check_subtype(self, rettype, writetype)
571 return rettype
572 end
573 end
574
575 redef class AVarReassignExpr
576 redef fun accept_typing(v)
577 do
578 var variable = self.variable
579 assert variable != null
580
581 var readtype = v.get_variable(self, variable)
582 if readtype == null then return
583
584 var writetype = variable.declared_type
585 if writetype == null then return
586
587 var rettype = self.resolve_reassignment(v, readtype, writetype)
588
589 v.set_variable(self, variable, rettype)
590
591 self.is_typed = true
592 end
593 end
594
595
596 redef class AContinueExpr
597 redef fun accept_typing(v)
598 do
599 var nexpr = self.n_expr
600 if nexpr != null then
601 var mtype = v.visit_expr(nexpr)
602 end
603 self.is_typed = true
604 end
605 end
606
607 redef class ABreakExpr
608 redef fun accept_typing(v)
609 do
610 var nexpr = self.n_expr
611 if nexpr != null then
612 var mtype = v.visit_expr(nexpr)
613 end
614 self.is_typed = true
615 end
616 end
617
618 redef class AReturnExpr
619 redef fun accept_typing(v)
620 do
621 var nexpr = self.n_expr
622 var ret_type = v.mpropdef.as(MMethodDef).msignature.return_mtype
623 if nexpr != null then
624 if ret_type != null then
625 var mtype = v.visit_expr_subtype(nexpr, ret_type)
626 else
627 var mtype = v.visit_expr(nexpr)
628 v.error(self, "Error: Return with value in a procedure.")
629 end
630 else if ret_type != null then
631 v.error(self, "Error: Return without value in a function.")
632 end
633 self.is_typed = true
634 end
635 end
636
637 redef class AAbortExpr
638 redef fun accept_typing(v)
639 do
640 self.is_typed = true
641 end
642 end
643
644 redef class AIfExpr
645 redef fun accept_typing(v)
646 do
647 v.visit_expr_bool(n_expr)
648
649 v.visit_stmt(n_then)
650 v.visit_stmt(n_else)
651 self.is_typed = true
652 end
653 end
654
655 redef class AIfexprExpr
656 redef fun accept_typing(v)
657 do
658 v.visit_expr_bool(n_expr)
659
660 var t1 = v.visit_expr(n_then)
661 var t2 = v.visit_expr(n_else)
662
663 if t1 == null or t2 == null then
664 return # Skip error
665 end
666
667 var t = v.merge_types(self, [t1, t2])
668 if t == null then
669 v.error(self, "Type Error: ambiguous type {t1} vs {t2}")
670 end
671 self.mtype = t
672 end
673 end
674
675 redef class ADoExpr
676 redef fun accept_typing(v)
677 do
678 v.visit_stmt(n_block)
679 self.is_typed = true
680 end
681 end
682
683 redef class AWhileExpr
684 redef fun accept_typing(v)
685 do
686 v.visit_expr_bool(n_expr)
687
688 v.visit_stmt(n_block)
689 self.is_typed = true
690 end
691 end
692
693 redef class ALoopExpr
694 redef fun accept_typing(v)
695 do
696 v.visit_stmt(n_block)
697 self.is_typed = true
698 end
699 end
700
701 redef class AForExpr
702 redef fun accept_typing(v)
703 do
704 var mtype = v.visit_expr(n_expr)
705 if mtype == null then return
706
707 var colcla = v.get_mclass(self, "Collection")
708 if colcla == null then return
709 var objcla = v.get_mclass(self, "Object")
710 if objcla == null then return
711 if v.is_subtype(mtype, colcla.get_mtype([objcla.mclass_type.as_nullable])) then
712 var coltype = mtype.supertype_to(v.mmodule, v.anchor, colcla)
713 assert coltype isa MGenericType
714 var variables = self.variables
715 if variables.length != 1 then
716 v.error(self, "Type Error: Expected one variable")
717 else
718 variables.first.declared_type = coltype.arguments.first
719 end
720 else
721 v.modelbuilder.error(self, "TODO: Do 'for' on {mtype}")
722 end
723
724 v.visit_stmt(n_block)
725 self.is_typed = true
726 end
727 end
728
729 redef class AAssertExpr
730 redef fun accept_typing(v)
731 do
732 v.visit_expr_bool(n_expr)
733
734 v.visit_stmt(n_else)
735 self.is_typed = true
736 end
737 end
738
739 redef class AOrExpr
740 redef fun accept_typing(v)
741 do
742 v.visit_expr_bool(n_expr)
743 v.visit_expr_bool(n_expr2)
744 self.mtype = v.type_bool(self)
745 end
746 end
747
748 redef class AAndExpr
749 redef fun accept_typing(v)
750 do
751 v.visit_expr_bool(n_expr)
752 v.visit_expr_bool(n_expr2)
753 self.mtype = v.type_bool(self)
754 end
755 end
756
757
758 redef class ANotExpr
759 redef fun accept_typing(v)
760 do
761 v.visit_expr_bool(n_expr)
762 self.mtype = v.type_bool(self)
763 end
764 end
765
766 redef class AOrElseExpr
767 redef fun accept_typing(v)
768 do
769 var t1 = v.visit_expr(n_expr)
770 var t2 = v.visit_expr(n_expr2)
771
772 if t1 == null or t2 == null then
773 return # Skip error
774 end
775
776 if t1 isa MNullableType then
777 t1 = t1.mtype
778 end
779
780 var t = v.merge_types(self, [t1, t2])
781 if t == null then
782 v.error(self, "Type Error: ambiguous type {t1} vs {t2}")
783 end
784 self.mtype = t
785 end
786 end
787
788 redef class AEeExpr
789 redef fun accept_typing(v)
790 do
791 v.visit_expr(n_expr)
792 v.visit_expr(n_expr2)
793 self.mtype = v.type_bool(self)
794 end
795 end
796
797 redef class ATrueExpr
798 redef fun accept_typing(v)
799 do
800 self.mtype = v.type_bool(self)
801 end
802 end
803
804 redef class AFalseExpr
805 redef fun accept_typing(v)
806 do
807 self.mtype = v.type_bool(self)
808 end
809 end
810
811 redef class AIntExpr
812 redef fun accept_typing(v)
813 do
814 var mclass = v.get_mclass(self, "Int")
815 if mclass == null then return # Forward error
816 self.mtype = mclass.mclass_type
817 end
818 end
819
820 redef class AFloatExpr
821 redef fun accept_typing(v)
822 do
823 var mclass = v.get_mclass(self, "Float")
824 if mclass == null then return # Forward error
825 self.mtype = mclass.mclass_type
826 end
827 end
828
829 redef class ACharExpr
830 redef fun accept_typing(v)
831 do
832 var mclass = v.get_mclass(self, "Char")
833 if mclass == null then return # Forward error
834 self.mtype = mclass.mclass_type
835 end
836 end
837
838 redef class AStringFormExpr
839 redef fun accept_typing(v)
840 do
841 var mclass = v.get_mclass(self, "String")
842 if mclass == null then return # Forward error
843 self.mtype = mclass.mclass_type
844 end
845 end
846
847 redef class ASuperstringExpr
848 redef fun accept_typing(v)
849 do
850 var mclass = v.get_mclass(self, "String")
851 if mclass == null then return # Forward error
852 self.mtype = mclass.mclass_type
853 for nexpr in self.n_exprs do
854 var t = v.visit_expr(nexpr)
855 end
856 end
857 end
858
859 redef class AArrayExpr
860 redef fun accept_typing(v)
861 do
862 var mtypes = new Array[nullable MType]
863 for e in self.n_exprs.n_exprs do
864 var t = v.visit_expr(e)
865 if t == null then
866 return # Skip error
867 end
868 mtypes.add(t)
869 end
870 var mtype = v.merge_types(self, mtypes)
871 if mtype == null then
872 v.error(self, "Type Error: ambiguous array type {mtypes.join(" ")}")
873 return
874 end
875 var mclass = v.get_mclass(self, "Array")
876 if mclass == null then return # Forward error
877 self.mtype = mclass.get_mtype([mtype])
878 end
879 end
880
881 redef class ARangeExpr
882 redef fun accept_typing(v)
883 do
884 var t1 = v.visit_expr(self.n_expr)
885 var t2 = v.visit_expr(self.n_expr2)
886 if t1 == null or t2 == null then return
887 var mclass = v.get_mclass(self, "Range")
888 if mclass == null then return # Forward error
889 if v.is_subtype(t1, t2) then
890 self.mtype = mclass.get_mtype([t2])
891 else if v.is_subtype(t2, t1) then
892 self.mtype = mclass.get_mtype([t1])
893 else
894 v.error(self, "Type Error: Cannot create range: {t1} vs {t2}")
895 end
896 end
897 end
898
899 redef class ANullExpr
900 redef fun accept_typing(v)
901 do
902 self.mtype = v.mmodule.model.null_type
903 end
904 end
905
906 redef class AIsaExpr
907 # The static type to cast to.
908 # (different from the static type of the expression that is Bool).
909 var cast_type: nullable MType
910 redef fun accept_typing(v)
911 do
912 var mtype = v.visit_expr_cast(self, self.n_expr, self.n_type)
913 self.cast_type = mtype
914
915 var variable = self.n_expr.its_variable
916 if variable != null then
917 var orig = self.n_expr.mtype
918 var from = if orig != null then orig.to_s else "invalid"
919 var to = if mtype != null then mtype.to_s else "invalid"
920 #debug("adapt {variable}: {from} -> {to}")
921 self.after_flow_context.when_true.set_var(variable, mtype)
922 end
923
924 self.mtype = v.type_bool(self)
925 end
926 end
927
928 redef class AAsCastExpr
929 redef fun accept_typing(v)
930 do
931 self.mtype = v.visit_expr_cast(self, self.n_expr, self.n_type)
932 end
933 end
934
935 redef class AAsNotnullExpr
936 redef fun accept_typing(v)
937 do
938 var mtype = v.visit_expr(self.n_expr)
939 if mtype isa MNullType then
940 v.error(self, "Type error: as(not null) on null")
941 return
942 end
943 if mtype isa MNullableType then
944 self.mtype = mtype.mtype
945 return
946 end
947 # TODO: warn on useless as not null
948 self.mtype = mtype
949 end
950 end
951
952 redef class AProxyExpr
953 redef fun accept_typing(v)
954 do
955 self.mtype = v.visit_expr(self.n_expr)
956 end
957 end
958
959 redef class ASelfExpr
960 redef var its_variable: nullable Variable
961 redef fun accept_typing(v)
962 do
963 var variable = v.selfvariable
964 self.its_variable = variable
965 self.mtype = v.get_variable(self, variable)
966 end
967 end
968
969 ## MESSAGE SENDING AND PROPERTY
970
971 redef class ASendExpr
972 # The property invoked by the send.
973 var mproperty: nullable MMethod
974
975 redef fun accept_typing(v)
976 do
977 var recvtype = v.visit_expr(self.n_expr)
978 var name = self.property_name
979
980 if recvtype == null then return # Forward error
981 if recvtype isa MNullType then
982 v.error(self, "Error: Method '{name}' call on 'null'.")
983 return
984 end
985
986 var propdef = v.get_method(self, recvtype, name, self.n_expr isa ASelfExpr)
987 if propdef == null then return
988 var mproperty = propdef.mproperty
989 self.mproperty = mproperty
990 var msignature = propdef.msignature
991 if msignature == null then abort # Forward error
992
993 var for_self = self.n_expr isa ASelfExpr
994 msignature = v.resolve_signature_for(msignature, recvtype, for_self)
995
996 var args = compute_raw_arguments
997
998 v.check_signature(self, args, name, msignature)
999
1000 if mproperty.is_init then
1001 var vmpropdef = v.mpropdef
1002 if not (vmpropdef isa MMethodDef and vmpropdef.mproperty.is_init) then
1003 v.error(self, "Can call a init only in another init")
1004 end
1005 end
1006
1007 var ret = msignature.return_mtype
1008 if ret != null then
1009 self.mtype = ret
1010 else
1011 self.is_typed = true
1012 end
1013 end
1014
1015 # The name of the property
1016 # Each subclass simply provide the correct name.
1017 private fun property_name: String is abstract
1018
1019 # An array of all arguments (excluding self)
1020 fun compute_raw_arguments: Array[AExpr] is abstract
1021 end
1022
1023 redef class ABinopExpr
1024 redef fun compute_raw_arguments do return [n_expr2]
1025 end
1026 redef class AEqExpr
1027 redef fun property_name do return "=="
1028 redef fun accept_typing(v)
1029 do
1030 super
1031
1032 var variable = self.n_expr.its_variable
1033 if variable == null then return
1034 var mtype = self.n_expr2.mtype
1035 if not mtype isa MNullType then return
1036 var vartype = v.get_variable(self, variable)
1037 if not vartype isa MNullableType then return
1038 self.after_flow_context.when_true.set_var(variable, mtype)
1039 self.after_flow_context.when_false.set_var(variable, vartype.mtype)
1040 #debug("adapt {variable}:{vartype} ; true->{mtype} false->{vartype.mtype}")
1041 end
1042 end
1043 redef class ANeExpr
1044 redef fun property_name do return "!="
1045 redef fun accept_typing(v)
1046 do
1047 super
1048
1049 var variable = self.n_expr.its_variable
1050 if variable == null then return
1051 var mtype = self.n_expr2.mtype
1052 if not mtype isa MNullType then return
1053 var vartype = v.get_variable(self, variable)
1054 if not vartype isa MNullableType then return
1055 self.after_flow_context.when_false.set_var(variable, mtype)
1056 self.after_flow_context.when_true.set_var(variable, vartype.mtype)
1057 #debug("adapt {variable}:{vartype} ; true->{vartype.mtype} false->{mtype}")
1058 end
1059 end
1060 redef class ALtExpr
1061 redef fun property_name do return "<"
1062 end
1063 redef class ALeExpr
1064 redef fun property_name do return "<="
1065 end
1066 redef class ALlExpr
1067 redef fun property_name do return "<<"
1068 end
1069 redef class AGtExpr
1070 redef fun property_name do return ">"
1071 end
1072 redef class AGeExpr
1073 redef fun property_name do return ">="
1074 end
1075 redef class AGgExpr
1076 redef fun property_name do return ">>"
1077 end
1078 redef class APlusExpr
1079 redef fun property_name do return "+"
1080 end
1081 redef class AMinusExpr
1082 redef fun property_name do return "-"
1083 end
1084 redef class AStarshipExpr
1085 redef fun property_name do return "<=>"
1086 end
1087 redef class AStarExpr
1088 redef fun property_name do return "*"
1089 end
1090 redef class ASlashExpr
1091 redef fun property_name do return "/"
1092 end
1093 redef class APercentExpr
1094 redef fun property_name do return "%"
1095 end
1096
1097 redef class AUminusExpr
1098 redef fun property_name do return "unary -"
1099 redef fun compute_raw_arguments do return new Array[AExpr]
1100 end
1101
1102
1103 redef class ACallExpr
1104 redef fun property_name do return n_id.text
1105 redef fun compute_raw_arguments do return n_args.to_a
1106 end
1107
1108 redef class ACallAssignExpr
1109 redef fun property_name do return n_id.text + "="
1110 redef fun compute_raw_arguments
1111 do
1112 var res = n_args.to_a
1113 res.add(n_value)
1114 return res
1115 end
1116 end
1117
1118 redef class ABraExpr
1119 redef fun property_name do return "[]"
1120 redef fun compute_raw_arguments do return n_args.to_a
1121 end
1122
1123 redef class ABraAssignExpr
1124 redef fun property_name do return "[]="
1125 redef fun compute_raw_arguments
1126 do
1127 var res = n_args.to_a
1128 res.add(n_value)
1129 return res
1130 end
1131 end
1132
1133 redef class ASendReassignFormExpr
1134 # The property invoked for the writing
1135 var write_mproperty: nullable MMethod = null
1136
1137 redef fun accept_typing(v)
1138 do
1139 var recvtype = v.visit_expr(self.n_expr)
1140 var name = self.property_name
1141
1142 if recvtype == null then return # Forward error
1143 if recvtype isa MNullType then
1144 v.error(self, "Error: Method '{name}' call on 'null'.")
1145 return
1146 end
1147
1148 var propdef = v.get_method(self, recvtype, name, self.n_expr isa ASelfExpr)
1149 if propdef == null then return
1150 var mproperty = propdef.mproperty
1151 self.mproperty = mproperty
1152 var msignature = propdef.msignature
1153 if msignature == null then abort # Forward error
1154 var for_self = self.n_expr isa ASelfExpr
1155 msignature = v.resolve_signature_for(msignature, recvtype, for_self)
1156
1157 var args = compute_raw_arguments
1158
1159 v.check_signature(self, args, name, msignature)
1160
1161 var readtype = msignature.return_mtype
1162 if readtype == null then
1163 v.error(self, "Error: {name} is not a function")
1164 return
1165 end
1166
1167 var wpropdef = v.get_method(self, recvtype, name + "=", self.n_expr isa ASelfExpr)
1168 if wpropdef == null then return
1169 var wmproperty = wpropdef.mproperty
1170 self.write_mproperty = wmproperty
1171 var wmsignature = wpropdef.msignature
1172 if wmsignature == null then abort # Forward error
1173 wmsignature = v.resolve_signature_for(wmsignature, recvtype, for_self)
1174
1175 var wtype = self.resolve_reassignment(v, readtype, wmsignature.parameter_mtypes.last)
1176 if wtype == null then return
1177
1178 args.add(self.n_value)
1179 v.check_signature(self, args, name + "=", wmsignature)
1180
1181 self.is_typed = true
1182 end
1183 end
1184
1185 redef class ACallReassignExpr
1186 redef fun property_name do return n_id.text
1187 redef fun compute_raw_arguments do return n_args.to_a
1188 end
1189
1190 redef class ABraReassignExpr
1191 redef fun property_name do return "[]"
1192 redef fun compute_raw_arguments do return n_args.to_a
1193 end
1194
1195 redef class AInitExpr
1196 redef fun property_name do return "init"
1197 redef fun compute_raw_arguments do return n_args.to_a
1198 end
1199
1200 redef class AExprs
1201 fun to_a: Array[AExpr] do return self.n_exprs.to_a
1202 end
1203
1204 ###
1205
1206 redef class ASuperExpr
1207 # The method to call if the super is in fact a 'super init call'
1208 # Note: if the super is a normal call-next-method, then this attribute is null
1209 var mproperty: nullable MMethod
1210
1211 redef fun accept_typing(v)
1212 do
1213 var recvtype = v.nclassdef.mclassdef.bound_mtype
1214 var mproperty = v.mpropdef.mproperty
1215 if not mproperty isa MMethod then
1216 v.error(self, "Error: super only usable in a method")
1217 return
1218 end
1219 var superprops = mproperty.lookup_super_definitions(v.mmodule, recvtype)
1220 if superprops.length == 0 then
1221 if mproperty.is_init and v.mpropdef.is_intro then
1222 process_superinit(v)
1223 return
1224 end
1225 v.error(self, "Error: No super method to call for {mproperty}.")
1226 return
1227 else if superprops.length > 1 then
1228 v.modelbuilder.warning(self, "Error: Conflicting super method to call for {mproperty}: {superprops.join(", ")}.")
1229 return
1230 end
1231 var superprop = superprops.first
1232 assert superprop isa MMethodDef
1233
1234 var msignature = superprop.msignature.as(not null)
1235 msignature = v.resolve_signature_for(msignature, recvtype, true)
1236 var args = self.n_args.to_a
1237 if args.length > 0 then
1238 v.check_signature(self, args, mproperty.name, msignature)
1239 end
1240 self.mtype = msignature.return_mtype
1241 end
1242
1243 private fun process_superinit(v: TypeVisitor)
1244 do
1245 var recvtype = v.nclassdef.mclassdef.bound_mtype
1246 var mproperty = v.mpropdef.mproperty
1247 var superprop: nullable MMethodDef = null
1248 for msupertype in v.nclassdef.mclassdef.supertypes do
1249 msupertype = msupertype.anchor_to(v.mmodule, recvtype)
1250 var errcount = v.modelbuilder.toolcontext.error_count
1251 var candidate = v.try_get_mproperty_by_name2(self, msupertype, mproperty.name).as(nullable MMethod)
1252 if candidate == null then
1253 if v.modelbuilder.toolcontext.error_count > errcount then return # Forard error
1254 continue # Try next super-class
1255 end
1256 if superprop != null and superprop.mproperty != candidate then
1257 v.error(self, "Error: conflicting super constructor to call for {mproperty}: {candidate.full_name}, {superprop.mproperty.full_name}")
1258 return
1259 end
1260 var candidatedefs = candidate.lookup_definitions(v.mmodule, recvtype)
1261 if superprop != null then
1262 if superprop == candidatedefs.first then continue
1263 candidatedefs.add(superprop)
1264 end
1265 if candidatedefs.length > 1 then
1266 v.error(self, "Error: confliting property definitions for property {mproperty} in {recvtype}: {candidatedefs.join(", ")}")
1267 return
1268 end
1269 superprop = candidatedefs.first
1270 end
1271 if superprop == null then
1272 v.error(self, "Error: No super method to call for {mproperty}.")
1273 return
1274 end
1275 self.mproperty = superprop.mproperty
1276
1277 var args = self.n_args.to_a
1278 var msignature = superprop.msignature.as(not null)
1279 msignature = v.resolve_signature_for(msignature, recvtype, true)
1280 if args.length > 0 then
1281 v.check_signature(self, args, mproperty.name, msignature)
1282 else
1283 # TODO: Check signature
1284 end
1285
1286 self.is_typed = true
1287 end
1288 end
1289
1290 ####
1291
1292 redef class ANewExpr
1293 # The constructor invoked by the new.
1294 var mproperty: nullable MMethod
1295
1296 redef fun accept_typing(v)
1297 do
1298 var recvtype = v.resolve_mtype(self.n_type)
1299 if recvtype == null then return
1300 self.mtype = recvtype
1301
1302 if not recvtype isa MClassType then
1303 if recvtype isa MNullableType then
1304 v.error(self, "Type error: cannot instantiate the nullable type {recvtype}.")
1305 return
1306 else
1307 v.error(self, "Type error: cannot instantiate the formal type {recvtype}.")
1308 return
1309 end
1310 end
1311
1312 var name: String
1313 var nid = self.n_id
1314 if nid != null then
1315 name = nid.text
1316 else
1317 name = "init"
1318 end
1319 var propdef = v.get_method(self, recvtype, name, false)
1320 if propdef == null then return
1321
1322 self.mproperty = propdef.mproperty
1323
1324 if not propdef.mproperty.is_init_for(recvtype.mclass) then
1325 v.error(self, "Error: {name} is not a constructor.")
1326 return
1327 end
1328
1329 var msignature = propdef.msignature.as(not null)
1330 msignature = v.resolve_signature_for(msignature, recvtype, false)
1331
1332 var args = n_args.to_a
1333 v.check_signature(self, args, name, msignature)
1334 end
1335 end
1336
1337 ####
1338
1339 redef class AAttrFormExpr
1340 # The attribute acceded.
1341 var mproperty: nullable MAttribute
1342
1343 # The static type of the attribute.
1344 var attr_type: nullable MType
1345
1346 # Resolve the attribute acceded.
1347 private fun resolve_property(v: TypeVisitor)
1348 do
1349 var recvtype = v.visit_expr(self.n_expr)
1350 if recvtype == null then return # Skip error
1351 var name = self.n_id.text
1352 if recvtype isa MNullType then
1353 v.error(self, "Error: Attribute '{name}' access on 'null'.")
1354 return
1355 end
1356
1357 var unsafe_type = v.anchor_to(recvtype)
1358 var mproperty = v.try_get_mproperty_by_name2(self, unsafe_type, name)
1359 if mproperty == null then
1360 v.modelbuilder.error(self, "Error: Attribute {name} doesn't exists in {recvtype}.")
1361 return
1362 end
1363 assert mproperty isa MAttribute
1364 self.mproperty = mproperty
1365
1366 var mpropdefs = mproperty.lookup_definitions(v.mmodule, unsafe_type)
1367 assert mpropdefs.length == 1
1368 var mpropdef = mpropdefs.first
1369 var attr_type = mpropdef.static_mtype.as(not null)
1370 attr_type = v.resolve_for(attr_type, recvtype, self.n_expr isa ASelfExpr)
1371 self.attr_type = attr_type
1372 end
1373 end
1374
1375 redef class AAttrExpr
1376 redef fun accept_typing(v)
1377 do
1378 self.resolve_property(v)
1379 self.mtype = self.attr_type
1380 end
1381 end
1382
1383
1384 redef class AAttrAssignExpr
1385 redef fun accept_typing(v)
1386 do
1387 self.resolve_property(v)
1388 var mtype = self.attr_type
1389
1390 v.visit_expr_subtype(self.n_value, mtype)
1391 self.is_typed = true
1392 end
1393 end
1394
1395 redef class AAttrReassignExpr
1396 redef fun accept_typing(v)
1397 do
1398 self.resolve_property(v)
1399 var mtype = self.attr_type
1400 if mtype == null then return # Skip error
1401
1402 self.resolve_reassignment(v, mtype, mtype)
1403
1404 self.is_typed = true
1405 end
1406 end
1407
1408 redef class AIssetAttrExpr
1409 redef fun accept_typing(v)
1410 do
1411 self.resolve_property(v)
1412 var mtype = self.attr_type
1413 if mtype == null then return # Skip error
1414
1415 var recvtype = self.n_expr.mtype.as(not null)
1416 var bound = v.resolve_for(mtype, recvtype, false)
1417 if bound isa MNullableType then
1418 v.error(self, "Error: isset on a nullable attribute.")
1419 end
1420 self.mtype = v.type_bool(self)
1421 end
1422 end
1423
1424 ###
1425
1426 redef class AClosureCallExpr
1427 redef fun accept_typing(v)
1428 do
1429 #TODO
1430 end
1431 end
1432
1433 ###
1434
1435 redef class ADebugTypeExpr
1436 redef fun accept_typing(v)
1437 do
1438 var expr = v.visit_expr(self.n_expr)
1439 if expr == null then return
1440 var unsafe = v.anchor_to(expr)
1441 var ntype = self.n_type
1442 var mtype = v.resolve_mtype(ntype)
1443 if mtype != null and mtype != expr then
1444 var umtype = v.anchor_to(mtype)
1445 v.modelbuilder.warning(self, "Found type {expr} (-> {unsafe}), expected {mtype} (-> {umtype})")
1446 end
1447 end
1448 end