1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2012 Jean Privat <jean@pryen.org>
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 # Intraprocedural resolution of static types and OO-services
18 # By OO-services we mean message sending, attribute access, instantiation, etc.
24 private class TypeVisitor
25 var modelbuilder
: ModelBuilder
26 var nclassdef
: AClassdef
27 var mpropdef
: MPropDef
29 var selfvariable
: Variable = new Variable("self")
31 init(modelbuilder
: ModelBuilder, nclassdef
: AClassdef, mpropdef
: MPropDef)
33 self.modelbuilder
= modelbuilder
34 self.nclassdef
= nclassdef
35 self.mpropdef
= mpropdef
37 var mclass
= nclassdef
.mclassdef
.mclass
39 var selfvariable
= new Variable("self")
40 self.selfvariable
= selfvariable
41 selfvariable
.declared_type
= mclass
.mclass_type
44 fun mmodule
: MModule do return self.nclassdef
.mclassdef
.mmodule
46 fun anchor
: MClassType do return self.nclassdef
.mclassdef
.bound_mtype
48 fun anchor_to
(mtype
: MType): MType
50 var mmodule
= self.nclassdef
.mclassdef
.mmodule
51 var anchor
= self.nclassdef
.mclassdef
.bound_mtype
52 return mtype
.anchor_to
(mmodule
, anchor
)
55 fun is_subtype
(sub
, sup
: MType): Bool
57 var mmodule
= self.nclassdef
.mclassdef
.mmodule
58 var anchor
= self.nclassdef
.mclassdef
.bound_mtype
59 return sub
.is_subtype
(mmodule
, anchor
, sup
)
62 fun resolve_for
(mtype
, subtype
: MType, for_self
: Bool): MType
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
)
71 # Retrieve the signature of a MMethodDef resolved for a specific call.
72 # This method is an helper to symplify the query on the model.
74 # Note: `for_self` indicates if the reciever is self or not.
75 # If yes, virtual types are not resolved.
76 fun resolve_signature_for
(mmethoddef
: MMethodDef, recv
: MType, for_self
: Bool): MSignature
78 return self.resolve_for
(mmethoddef
.msignature
.as(not null), recv
, for_self
).as(MSignature)
81 # Check that `sub` is a subtype of `sup`.
82 # If `sub` is not a valud suptype, then display an error on `node` an return null.
83 # If `sub` is a safe subtype of `sup` then return `sub`.
84 # If `sun` is an insafe subtype (ie an imlicit cast is required), then return `sup`.
86 # The point of the return type is to determinate the usable type on an expression:
87 # If the suptype is safe, then the return type is the one on the expression typed by `sub`.
88 # Is the subtype is unsafe, then the return type is the one of an implicit cast on `sup`.
89 fun check_subtype
(node
: ANode, sub
, sup
: MType): nullable MType
91 if self.is_subtype
(sub
, sup
) then return sub
92 if self.is_subtype
(sub
, self.anchor_to
(sup
)) then
93 # FIXME workarround to the current unsafe typing policy. To remove once fixed virtual types exists.
94 #node.debug("Unsafe typing: expected {sup}, got {sub}")
97 self.modelbuilder
.error
(node
, "Type error: expected {sup}, got {sub}")
101 # Visit an expression and do not care about the return value
102 fun visit_stmt
(nexpr
: nullable AExpr)
104 if nexpr
== null then return
105 nexpr
.accept_typing
(self)
108 # Visit an expression and expects that it is not a statement
109 # Return the type of the expression
110 # Display an error and return null if:
111 # * the type cannot be determined or
112 # * `nexpr' is a statement
113 fun visit_expr
(nexpr
: AExpr): nullable MType
115 nexpr
.accept_typing
(self)
116 var mtype
= nexpr
.mtype
117 if mtype
!= null then return mtype
118 if not nexpr
.is_typed
then
119 if not self.modelbuilder
.toolcontext
.error_count
> 0 then # check that there is really an error
120 if self.modelbuilder
.toolcontext
.verbose_level
> 1 then
121 nexpr
.debug
("No return type but no error.")
124 return null # forward error
126 self.error
(nexpr
, "Type error: expected expression.")
130 # Visit an expression and expect its static type is a least a `sup'
131 # Return the type of the expression
132 # * the type cannot be determined or
133 # * `nexpr' is a statement
134 # * `nexpt' is not a `sup'
135 fun visit_expr_subtype
(nexpr
: AExpr, sup
: nullable MType): nullable MType
137 var sub
= visit_expr
(nexpr
)
138 if sub
== null then return null # Forward error
140 if sup
== null then return null # Forward error
142 var res
= check_subtype
(nexpr
, sub
, sup
)
144 nexpr
.implicit_cast_to
= res
149 # Visit an expression and expect its static type is a bool
150 # Return the type of the expression
151 # * the type cannot be determined or
152 # * `nexpr' is a statement
153 # * `nexpt' is not a `sup'
154 fun visit_expr_bool
(nexpr
: AExpr): nullable MType
156 return self.visit_expr_subtype
(nexpr
, self.type_bool
(nexpr
))
160 private fun visit_expr_cast
(node
: ANode, nexpr
: AExpr, ntype
: AType): nullable MType
162 var sub
= visit_expr
(nexpr
)
163 if sub
== null then return null # Forward error
165 var sup
= self.resolve_mtype
(ntype
)
166 if sup
== null then return null # Forward error
168 var mmodule
= self.nclassdef
.mclassdef
.mmodule
169 var anchor
= self.nclassdef
.mclassdef
.bound_mtype
171 self.modelbuilder
.warning
(node
, "Warning: Expression is already a {sup}.")
172 else if self.is_subtype
(sub
, sup
) and not sup
.need_anchor
then
173 self.modelbuilder
.warning
(node
, "Warning: Expression is already a {sup} since it is a {sub}.")
178 fun try_get_mproperty_by_name2
(anode
: ANode, mtype
: MType, name
: String): nullable MProperty
180 return self.modelbuilder
.try_get_mproperty_by_name2
(anode
, self.nclassdef
.mclassdef
.mmodule
, mtype
, name
)
183 fun resolve_mtype
(node
: AType): nullable MType
185 return self.modelbuilder
.resolve_mtype
(self.nclassdef
, node
)
188 fun try_get_mclass
(node
: ANode, name
: String): nullable MClass
190 var mmodule
= self.nclassdef
.mclassdef
.mmodule
191 var mclass
= modelbuilder
.try_get_mclass_by_name
(node
, mmodule
, name
)
195 fun get_mclass
(node
: ANode, name
: String): nullable MClass
197 var mmodule
= self.nclassdef
.mclassdef
.mmodule
198 var mclass
= modelbuilder
.try_get_mclass_by_name
(node
, mmodule
, name
)
199 if mclass
== null then
200 self.modelbuilder
.error
(node
, "Type Error: missing primitive class `{name}'.")
205 fun type_bool
(node
: ANode): nullable MType
207 var mclass
= self.get_mclass
(node
, "Bool")
208 if mclass
== null then return null
209 return mclass
.mclass_type
212 fun get_method
(node
: ANode, recvtype
: MType, name
: String, recv_is_self
: Bool): nullable CallSite
214 var unsafe_type
= self.anchor_to
(recvtype
)
216 #debug("recv: {recvtype} (aka {unsafe_type})")
217 if recvtype
isa MNullType then
218 self.error
(node
, "Error: Method '{name}' call on 'null'.")
222 var mproperty
= self.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
223 if mproperty
== null then
224 #self.modelbuilder.error(node, "Type error: property {name} not found in {unsafe_type} (ie {recvtype})")
226 self.modelbuilder
.error
(node
, "Error: Method or variable '{name}' unknown in {recvtype}.")
228 self.modelbuilder
.error
(node
, "Error: Method '{name}' doesn't exists in {recvtype}.")
233 assert mproperty
isa MMethod
234 if mproperty
.visibility
== protected_visibility
and not recv_is_self
and self.mmodule
.visibility_for
(mproperty
.intro_mclassdef
.mmodule
) < intrude_visibility
then
235 self.modelbuilder
.error
(node
, "Error: Method '{name}' is protected and can only acceded by self. {mproperty.intro_mclassdef.mmodule.visibility_for(self.mmodule)}")
239 var propdefs
= mproperty
.lookup_definitions
(self.mmodule
, unsafe_type
)
241 if propdefs
.length
== 0 then
242 self.modelbuilder
.error
(node
, "Type error: no definition found for property {name} in {unsafe_type}")
244 else if propdefs
.length
== 1 then
245 mpropdef
= propdefs
.first
247 self.modelbuilder
.warning
(node
, "Warning: confliting property definitions for property {name} in {unsafe_type}: {propdefs.join(" ")}")
248 mpropdef
= mproperty
.intro
252 var msignature
= self.resolve_signature_for
(mpropdef
, recvtype
, recv_is_self
)
254 var erasure_cast
= false
255 var rettype
= mpropdef
.msignature
.return_mtype
256 if not recv_is_self
and rettype
!= null then
257 if rettype
isa MNullableType then rettype
= rettype
.mtype
258 if rettype
isa MParameterType then
259 var erased_rettype
= msignature
.return_mtype
260 assert erased_rettype
!= null
261 #node.debug("Erasure cast: Really a {rettype} but unsafely a {erased_rettype}")
266 var callsite
= new CallSite(node
, recvtype
, recv_is_self
, mproperty
, mpropdef
, msignature
, erasure_cast
)
270 # Visit the expressions of args and cheik their conformity with the corresponding typi in signature
271 # The point of this method is to handle varargs correctly
272 # Note: The signature must be correctly adapted
273 fun check_signature
(node
: ANode, args
: Array[AExpr], name
: String, msignature
: MSignature): Bool
275 var vararg_rank
= msignature
.vararg_rank
276 if vararg_rank
>= 0 then
277 if args
.length
< msignature
.arity
then
278 #self.modelbuilder.error(node, "Error: Incorrect number of parameters. Got {args.length}, expected at least {msignature.arity}. Signature is {msignature}")
279 self.modelbuilder
.error
(node
, "Error: arity mismatch; prototype is '{name}{msignature}'")
282 else if args
.length
!= msignature
.arity
then
283 self.modelbuilder
.error
(node
, "Error: Incorrect number of parameters. Got {args.length}, expected {msignature.arity}. Signature is {msignature}")
287 #debug("CALL {unsafe_type}.{msignature}")
289 var vararg_decl
= args
.length
- msignature
.arity
290 for i
in [0..msignature
.arity
[ do
292 if i
== vararg_rank
then continue # skip the vararg
293 if i
> vararg_rank
then
296 var paramtype
= msignature
.mparameters
[i
].mtype
297 self.visit_expr_subtype
(args
[j
], paramtype
)
299 if vararg_rank
>= 0 then
300 var varargs
= new Array[AExpr]
301 var paramtype
= msignature
.mparameters
[vararg_rank
].mtype
302 for j
in [vararg_rank
..vararg_rank
+vararg_decl
] do
304 self.visit_expr_subtype
(args
[j
], paramtype
)
310 fun error
(node
: ANode, message
: String)
312 self.modelbuilder
.toolcontext
.error
(node
.hot_location
, message
)
315 fun get_variable
(node
: AExpr, variable
: Variable): nullable MType
317 var flow
= node
.after_flow_context
319 self.error
(node
, "No context!")
323 if flow
.vars
.has_key
(variable
) then
324 return flow
.vars
[variable
]
326 #node.debug("*** START Collected for {variable}")
327 var mtypes
= flow
.collect_types
(variable
)
328 #node.debug("**** END Collected for {variable}")
329 if mtypes
== null or mtypes
.length
== 0 then
330 return variable
.declared_type
331 else if mtypes
.length
== 1 then
334 var res
= merge_types
(node
,mtypes
)
335 if res
== null then res
= variable
.declared_type
341 fun set_variable
(node
: AExpr, variable
: Variable, mtype
: nullable MType)
343 var flow
= node
.after_flow_context
346 flow
.set_var
(variable
, mtype
)
349 fun merge_types
(node
: ANode, col
: Array[nullable MType]): nullable MType
351 if col
.length
== 1 then return col
.first
352 var res
= new Array[nullable MType]
354 if t1
== null then continue # return null
357 if t2
== null then continue # return null
358 if t2
isa MNullableType or t2
isa MNullType then
361 if not is_subtype
(t2
, t1
) then found
= false
364 #print "merge {col.join(" ")} -> {t1}"
368 #self.modelbuilder.warning(node, "Type Error: {col.length} conflicting types: <{col.join(", ")}>")
373 # A specific method call site with its associated informations.
375 # The assiciated node for location
378 # The statis type of the receiver
381 # Is the receiver self?
382 # If "for_self", virtual types of the signature are keeped
383 # If "not_for_self", virtual type are erased
384 var recv_is_self
: Bool
386 # The designated method
387 var mproperty
: MMethod
389 # The statically designated method definition
390 # The most specif one, it is.
391 var mpropdef
: MMethodDef
393 # The resolved signature for the receiver
394 var msignature
: MSignature
396 # Is a implicit cast required on erasure typing policy?
397 var erasure_cast
: Bool
399 private fun check_signature
(v
: TypeVisitor, args
: Array[AExpr]): Bool
401 return v
.check_signature
(self.node
, args
, self.mproperty
.name
, self.msignature
)
406 # The declared type of the variable
407 var declared_type
: nullable MType
410 redef class FlowContext
411 # Store changes of types because of type evolution
412 private var vars
: HashMap[Variable, nullable MType] = new HashMap[Variable, nullable MType]
413 private var cache
: HashMap[Variable, nullable Array[nullable MType]] = new HashMap[Variable, nullable Array[nullable MType]]
415 # Adapt the variable to a static type
416 # Warning1: do not modify vars directly.
417 # Warning2: sub-flow may have cached a unadapted variabial
418 private fun set_var
(variable
: Variable, mtype
: nullable MType)
420 self.vars
[variable
] = mtype
421 self.cache
.keys
.remove
(variable
)
424 private fun collect_types
(variable
: Variable): nullable Array[nullable MType]
426 if cache
.has_key
(variable
) then
427 return cache
[variable
]
429 var res
: nullable Array[nullable MType] = null
430 if vars
.has_key
(variable
) then
431 var mtype
= vars
[variable
]
433 else if self.previous
.is_empty
then
435 res
= [variable
.declared_type
]
437 for flow
in self.previous
do
438 if flow
.is_unreachable
then continue
439 var r2
= flow
.collect_types
(variable
)
440 if r2
== null then continue
445 if not res
.has
(t
) then res
.add
(t
)
450 cache
[variable
] = res
456 # The entry point of the whole typing analysis
457 fun do_typing
(modelbuilder
: ModelBuilder)
461 # The variable associated to the reciever (if any)
462 var selfvariable
: nullable Variable
465 redef class AConcreteMethPropdef
466 redef fun do_typing
(modelbuilder
: ModelBuilder)
468 var nclassdef
= self.parent
.as(AClassdef)
469 var mpropdef
= self.mpropdef
.as(not null)
470 var v
= new TypeVisitor(modelbuilder
, nclassdef
, mpropdef
)
471 self.selfvariable
= v
.selfvariable
473 var nblock
= self.n_block
474 if nblock
== null then return
476 var mmethoddef
= self.mpropdef
.as(not null)
477 for i
in [0..mmethoddef
.msignature
.arity
[ do
478 var mtype
= mmethoddef
.msignature
.mparameters
[i
].mtype
479 if mmethoddef
.msignature
.vararg_rank
== i
then
480 var arrayclass
= v
.get_mclass
(self.n_signature
.n_params
[i
], "Array")
481 if arrayclass
== null then return # Skip error
482 mtype
= arrayclass
.get_mtype
([mtype
])
484 var variable
= self.n_signature
.n_params
[i
].variable
485 assert variable
!= null
486 variable
.declared_type
= mtype
488 for i
in [0..mmethoddef
.msignature
.mclosures
.length
[ do
489 var mclosure
= mmethoddef
.msignature
.mclosures
[i
]
490 var variable
= self.n_signature
.n_closure_decls
[i
].variable
491 assert variable
!= null
492 variable
.declared_type
= mclosure
.mtype
496 if not nblock
.after_flow_context
.is_unreachable
and mmethoddef
.msignature
.return_mtype
!= null then
497 # We reach the end of the function without having a return, it is bad
498 v
.error
(self, "Control error: Reached end of function (a 'return' with a value was expected).")
503 redef class AAttrPropdef
504 redef fun do_typing
(modelbuilder
: ModelBuilder)
506 var nclassdef
= self.parent
.as(AClassdef)
507 var v
= new TypeVisitor(modelbuilder
, nclassdef
, self.mpropdef
.as(not null))
508 self.selfvariable
= v
.selfvariable
510 var nexpr
= self.n_expr
511 if nexpr
!= null then
512 var mtype
= self.mpropdef
.static_mtype
513 v
.visit_expr_subtype
(nexpr
, mtype
)
521 # The static type of the expression.
522 # null if self is a statement of in case of error
523 var mtype
: nullable MType = null
525 # Is the statement correctly typed?
526 # Used to distinguish errors and statements when `mtype' == null
527 var is_typed
: Bool = false
529 # If required, the following implicit cast ".as(XXX)"
530 # Such a cast may by required after evaluating the expression when
531 # a unsafe operation is detected (silently accepted by the Nit language).
532 # The attribute is computed by `check_subtype`
533 var implicit_cast_to
: nullable MType = null
535 # Return the variable read (if any)
536 # Used to perform adaptive typing
537 fun its_variable
: nullable Variable do return null
539 private fun accept_typing
(v
: TypeVisitor)
541 v
.error
(self, "no implemented accept_typing for {self.class_name}")
545 redef class ABlockExpr
546 redef fun accept_typing
(v
)
548 for e
in self.n_expr
do v
.visit_stmt
(e
)
553 redef class AVardeclExpr
554 redef fun accept_typing
(v
)
556 var variable
= self.variable
557 if variable
== null then return # Skip error
559 var ntype
= self.n_type
560 var mtype
: nullable MType
561 if ntype
== null then
564 mtype
= v
.resolve_mtype
(ntype
)
565 if mtype
== null then return # Skip error
568 var nexpr
= self.n_expr
569 if nexpr
!= null then
570 if mtype
!= null then
571 v
.visit_expr_subtype
(nexpr
, mtype
)
573 mtype
= v
.visit_expr
(nexpr
)
574 if mtype
== null then return # Skip error
579 if mtype
== null or mtype
isa MNullType then
580 decltype
= v
.get_mclass
(self, "Object").mclass_type
.as_nullable
581 if mtype
== null then mtype
= decltype
584 variable
.declared_type
= decltype
585 v
.set_variable
(self, variable
, mtype
)
587 #debug("var {variable}: {mtype}")
594 redef fun its_variable
do return self.variable
595 redef fun accept_typing
(v
)
597 var variable
= self.variable
598 if variable
== null then return # Skip error
600 var mtype
= v
.get_variable
(self, variable
)
601 if mtype
!= null then
602 #debug("{variable} is {mtype}")
604 #debug("{variable} is untyped")
611 redef class AVarAssignExpr
612 redef fun accept_typing
(v
)
614 var variable
= self.variable
615 assert variable
!= null
617 var mtype
= v
.visit_expr_subtype
(n_value
, variable
.declared_type
)
619 v
.set_variable
(self, variable
, mtype
)
625 redef class AReassignFormExpr
626 # @depreciated use `reassign_callsite`
627 fun reassign_property
: nullable MMethodDef do return self.reassign_callsite
.mpropdef
629 # The method designed by the reassign operator.
630 var reassign_callsite
: nullable CallSite
632 var read_type
: nullable MType = null
634 # Determine the `reassign_property'
635 # `readtype' is the type of the reading of the left value.
636 # `writetype' is the type of the writing of the left value.
637 # (Because of ACallReassignExpr, both can be different.
638 # Return the static type of the value to store.
639 private fun resolve_reassignment
(v
: TypeVisitor, readtype
, writetype
: MType): nullable MType
641 var reassign_name
: String
642 if self.n_assign_op
isa APlusAssignOp then
644 else if self.n_assign_op
isa AMinusAssignOp then
650 self.read_type
= readtype
652 if readtype
isa MNullType then
653 v
.error
(self, "Error: Method '{reassign_name}' call on 'null'.")
657 var callsite
= v
.get_method
(self, readtype
, reassign_name
, false)
658 if callsite
== null then return null # Skip error
659 self.reassign_callsite
= callsite
661 var msignature
= callsite
.msignature
662 var rettype
= msignature
.return_mtype
663 assert msignature
.arity
== 1 and rettype
!= null
665 var value_type
= v
.visit_expr_subtype
(self.n_value
, msignature
.mparameters
.first
.mtype
)
666 if value_type
== null then return null # Skip error
668 v
.check_subtype
(self, rettype
, writetype
)
673 redef class AVarReassignExpr
674 redef fun accept_typing
(v
)
676 var variable
= self.variable
677 assert variable
!= null
679 var readtype
= v
.get_variable
(self, variable
)
680 if readtype
== null then return
682 var writetype
= variable
.declared_type
683 if writetype
== null then return
685 var rettype
= self.resolve_reassignment
(v
, readtype
, writetype
)
687 v
.set_variable
(self, variable
, rettype
)
694 redef class AContinueExpr
695 redef fun accept_typing
(v
)
697 var nexpr
= self.n_expr
698 if nexpr
!= null then
699 var mtype
= v
.visit_expr
(nexpr
)
705 redef class ABreakExpr
706 redef fun accept_typing
(v
)
708 var nexpr
= self.n_expr
709 if nexpr
!= null then
710 var mtype
= v
.visit_expr
(nexpr
)
716 redef class AReturnExpr
717 redef fun accept_typing
(v
)
719 var nexpr
= self.n_expr
720 var ret_type
= v
.mpropdef
.as(MMethodDef).msignature
.return_mtype
721 if nexpr
!= null then
722 if ret_type
!= null then
723 var mtype
= v
.visit_expr_subtype
(nexpr
, ret_type
)
725 var mtype
= v
.visit_expr
(nexpr
)
726 v
.error
(self, "Error: Return with value in a procedure.")
728 else if ret_type
!= null then
729 v
.error
(self, "Error: Return without value in a function.")
735 redef class AAbortExpr
736 redef fun accept_typing
(v
)
743 redef fun accept_typing
(v
)
745 v
.visit_expr_bool
(n_expr
)
753 redef class AIfexprExpr
754 redef fun accept_typing
(v
)
756 v
.visit_expr_bool
(n_expr
)
758 var t1
= v
.visit_expr
(n_then
)
759 var t2
= v
.visit_expr
(n_else
)
761 if t1
== null or t2
== null then
765 var t
= v
.merge_types
(self, [t1
, t2
])
767 v
.error
(self, "Type Error: ambiguous type {t1} vs {t2}")
774 redef fun accept_typing
(v
)
776 v
.visit_stmt
(n_block
)
781 redef class AWhileExpr
782 redef fun accept_typing
(v
)
784 v
.visit_expr_bool
(n_expr
)
786 v
.visit_stmt
(n_block
)
791 redef class ALoopExpr
792 redef fun accept_typing
(v
)
794 v
.visit_stmt
(n_block
)
800 var coltype
: nullable MClassType
802 var method_iterator
: nullable MMethod
803 var method_is_ok
: nullable MMethod
804 var method_item
: nullable MMethod
805 var method_next
: nullable MMethod
806 var method_key
: nullable MMethod
808 private fun do_type_iterator
(v
: TypeVisitor, mtype
: MType)
810 var objcla
= v
.get_mclass
(self, "Object")
811 if objcla
== null then return
816 var colcla
= v
.try_get_mclass
(self, "Collection")
817 if colcla
!= null and v
.is_subtype
(mtype
, colcla
.get_mtype
([objcla
.mclass_type
.as_nullable
])) then
818 var coltype
= mtype
.supertype_to
(v
.mmodule
, v
.anchor
, colcla
)
819 self.coltype
= coltype
820 var variables
= self.variables
821 if variables
.length
!= 1 then
822 v
.error
(self, "Type Error: Expected one variable")
824 variables
.first
.declared_type
= coltype
.arguments
.first
829 var mapcla
= v
.try_get_mclass
(self, "Map")
830 if mapcla
!= null and v
.is_subtype
(mtype
, mapcla
.get_mtype
([objcla
.mclass_type
.as_nullable
, objcla
.mclass_type
.as_nullable
])) then
831 var coltype
= mtype
.supertype_to
(v
.mmodule
, v
.anchor
, mapcla
)
832 self.coltype
= coltype
833 var variables
= self.variables
834 if variables
.length
!= 2 then
835 v
.error
(self, "Type Error: Expected two variables")
837 variables
[0].declared_type
= coltype
.arguments
[0]
838 variables
[1].declared_type
= coltype
.arguments
[1]
843 if is_col
or is_map
then
844 # get iterator method
845 var coltype
= self.coltype
.as(not null)
846 var itdef
= v
.get_method
(self, coltype
, "iterator", true)
847 if itdef
== null then
848 v
.error
(self, "Type Error: Expected method 'iterator' in type {coltype}")
851 self.method_iterator
= itdef
.mproperty
854 var ittype
= itdef
.msignature
.return_mtype
855 if ittype
== null then
856 v
.error
(self, "Type Error: Expected method 'iterator' to return an Iterator type")
860 # get methods is_ok, next, item
861 var ikdef
= v
.get_method
(self, ittype
, "is_ok", false)
862 if ikdef
== null then
863 v
.error
(self, "Type Error: Expected method 'is_ok' in Iterator type {ittype}")
866 self.method_is_ok
= ikdef
.mproperty
868 var itemdef
= v
.get_method
(self, ittype
, "item", false)
869 if itemdef
== null then
870 v
.error
(self, "Type Error: Expected method 'item' in Iterator type {ittype}")
873 self.method_item
= itemdef
.mproperty
875 var nextdef
= v
.get_method
(self, ittype
, "next", false)
876 if nextdef
== null then
877 v
.error
(self, "Type Error: Expected method 'next' in Iterator type {ittype}")
880 self.method_next
= nextdef
.mproperty
883 var keydef
= v
.get_method
(self, ittype
, "key", false)
884 if keydef
== null then
885 v
.error
(self, "Type Error: Expected method 'key' in Iterator type {ittype}")
888 self.method_key
= keydef
.mproperty
893 v
.modelbuilder
.error
(self, "NOT YET IMPLEMENTED: Do 'for' on {mtype}")
896 redef fun accept_typing
(v
)
898 var mtype
= v
.visit_expr
(n_expr
)
899 if mtype
== null then return
901 self.do_type_iterator
(v
, mtype
)
903 v
.visit_stmt
(n_block
)
908 redef class AAssertExpr
909 redef fun accept_typing
(v
)
911 v
.visit_expr_bool
(n_expr
)
919 redef fun accept_typing
(v
)
921 v
.visit_expr_bool
(n_expr
)
922 v
.visit_expr_bool
(n_expr2
)
923 self.mtype
= v
.type_bool
(self)
928 redef fun accept_typing
(v
)
930 v
.visit_expr_bool
(n_expr
)
931 v
.visit_expr_bool
(n_expr2
)
932 self.mtype
= v
.type_bool
(self)
938 redef fun accept_typing
(v
)
940 v
.visit_expr_bool
(n_expr
)
941 self.mtype
= v
.type_bool
(self)
945 redef class AOrElseExpr
946 redef fun accept_typing
(v
)
948 var t1
= v
.visit_expr
(n_expr
)
949 var t2
= v
.visit_expr
(n_expr2
)
951 if t1
== null or t2
== null then
955 if t1
isa MNullableType then
959 var t
= v
.merge_types
(self, [t1
, t2
])
961 v
.error
(self, "Type Error: ambiguous type {t1} vs {t2}")
968 redef fun accept_typing
(v
)
971 v
.visit_expr
(n_expr2
)
972 self.mtype
= v
.type_bool
(self)
976 redef class ATrueExpr
977 redef fun accept_typing
(v
)
979 self.mtype
= v
.type_bool
(self)
983 redef class AFalseExpr
984 redef fun accept_typing
(v
)
986 self.mtype
= v
.type_bool
(self)
991 redef fun accept_typing
(v
)
993 var mclass
= v
.get_mclass
(self, "Int")
994 if mclass
== null then return # Forward error
995 self.mtype
= mclass
.mclass_type
999 redef class AFloatExpr
1000 redef fun accept_typing
(v
)
1002 var mclass
= v
.get_mclass
(self, "Float")
1003 if mclass
== null then return # Forward error
1004 self.mtype
= mclass
.mclass_type
1008 redef class ACharExpr
1009 redef fun accept_typing
(v
)
1011 var mclass
= v
.get_mclass
(self, "Char")
1012 if mclass
== null then return # Forward error
1013 self.mtype
= mclass
.mclass_type
1017 redef class AStringFormExpr
1018 redef fun accept_typing
(v
)
1020 var mclass
= v
.get_mclass
(self, "String")
1021 if mclass
== null then return # Forward error
1022 self.mtype
= mclass
.mclass_type
1026 redef class ASuperstringExpr
1027 redef fun accept_typing
(v
)
1029 var mclass
= v
.get_mclass
(self, "String")
1030 if mclass
== null then return # Forward error
1031 self.mtype
= mclass
.mclass_type
1032 for nexpr
in self.n_exprs
do
1033 var t
= v
.visit_expr
(nexpr
)
1038 redef class AArrayExpr
1039 redef fun accept_typing
(v
)
1041 var mtypes
= new Array[nullable MType]
1042 for e
in self.n_exprs
.n_exprs
do
1043 var t
= v
.visit_expr
(e
)
1049 var mtype
= v
.merge_types
(self, mtypes
)
1050 if mtype
== null then
1051 v
.error
(self, "Type Error: ambiguous array type {mtypes.join(" ")}")
1054 var mclass
= v
.get_mclass
(self, "Array")
1055 if mclass
== null then return # Forward error
1056 self.mtype
= mclass
.get_mtype
([mtype
])
1060 redef class ARangeExpr
1061 redef fun accept_typing
(v
)
1063 var discrete_class
= v
.get_mclass
(self, "Discrete")
1064 if discrete_class
== null then return # Forward error
1065 var discrete_type
= discrete_class
.intro
.bound_mtype
1066 var t1
= v
.visit_expr_subtype
(self.n_expr
, discrete_type
)
1067 var t2
= v
.visit_expr_subtype
(self.n_expr2
, discrete_type
)
1068 if t1
== null or t2
== null then return
1069 var mclass
= v
.get_mclass
(self, "Range")
1070 if mclass
== null then return # Forward error
1071 if v
.is_subtype
(t1
, t2
) then
1072 self.mtype
= mclass
.get_mtype
([t2
])
1073 else if v
.is_subtype
(t2
, t1
) then
1074 self.mtype
= mclass
.get_mtype
([t1
])
1076 v
.error
(self, "Type Error: Cannot create range: {t1} vs {t2}")
1081 redef class ANullExpr
1082 redef fun accept_typing
(v
)
1084 self.mtype
= v
.mmodule
.model
.null_type
1088 redef class AIsaExpr
1089 # The static type to cast to.
1090 # (different from the static type of the expression that is Bool).
1091 var cast_type
: nullable MType
1092 redef fun accept_typing
(v
)
1094 var mtype
= v
.visit_expr_cast
(self, self.n_expr
, self.n_type
)
1095 self.cast_type
= mtype
1097 var variable
= self.n_expr
.its_variable
1098 if variable
!= null then
1099 var orig
= self.n_expr
.mtype
1100 var from
= if orig
!= null then orig
.to_s
else "invalid"
1101 var to
= if mtype
!= null then mtype
.to_s
else "invalid"
1102 #debug("adapt {variable}: {from} -> {to}")
1103 self.after_flow_context
.when_true
.set_var
(variable
, mtype
)
1106 self.mtype
= v
.type_bool
(self)
1110 redef class AAsCastExpr
1111 redef fun accept_typing
(v
)
1113 self.mtype
= v
.visit_expr_cast
(self, self.n_expr
, self.n_type
)
1117 redef class AAsNotnullExpr
1118 redef fun accept_typing
(v
)
1120 var mtype
= v
.visit_expr
(self.n_expr
)
1121 if mtype
isa MNullType then
1122 v
.error
(self, "Type error: as(not null) on null")
1125 if mtype
isa MNullableType then
1126 self.mtype
= mtype
.mtype
1129 # TODO: warn on useless as not null
1134 redef class AProxyExpr
1135 redef fun accept_typing
(v
)
1137 self.mtype
= v
.visit_expr
(self.n_expr
)
1141 redef class ASelfExpr
1142 redef var its_variable
: nullable Variable
1143 redef fun accept_typing
(v
)
1145 var variable
= v
.selfvariable
1146 self.its_variable
= variable
1147 self.mtype
= v
.get_variable
(self, variable
)
1151 ## MESSAGE SENDING AND PROPERTY
1153 redef class ASendExpr
1154 # @depreciated: use `callsite`
1155 fun mproperty
: nullable MMethod do return callsite
.mproperty
1157 # The property invoked by the send.
1158 var callsite
: nullable CallSite
1160 redef fun accept_typing
(v
)
1162 var recvtype
= v
.visit_expr
(self.n_expr
)
1163 var name
= self.property_name
1165 if recvtype
== null then return # Forward error
1166 if recvtype
isa MNullType then
1167 v
.error
(self, "Error: Method '{name}' call on 'null'.")
1171 var callsite
= v
.get_method
(self, recvtype
, name
, self.n_expr
isa ASelfExpr)
1172 if callsite
== null then return
1173 self.callsite
= callsite
1174 var msignature
= callsite
.msignature
1176 var args
= compute_raw_arguments
1177 self.raw_arguments
= args
1179 callsite
.check_signature
(v
, args
)
1181 if callsite
.mproperty
.is_init
then
1182 var vmpropdef
= v
.mpropdef
1183 if not (vmpropdef
isa MMethodDef and vmpropdef
.mproperty
.is_init
) then
1184 v
.error
(self, "Can call a init only in another init")
1188 var ret
= msignature
.return_mtype
1192 self.is_typed
= true
1195 if self.n_closure_defs
.length
== msignature
.mclosures
.length
then
1196 for i
in [0..self.n_closure_defs
.length
[ do
1197 self.n_closure_defs
[i
].accept_typing
(v
, msignature
.mclosures
[i
])
1200 debug
("closure: got {self.n_closure_defs.length}, want {msignature.mclosures.length}")
1204 # The name of the property
1205 # Each subclass simply provide the correct name.
1206 private fun property_name
: String is abstract
1208 # An array of all arguments (excluding self)
1209 var raw_arguments
: nullable Array[AExpr]
1211 private fun compute_raw_arguments
: Array[AExpr] is abstract
1214 redef class ABinopExpr
1215 redef fun compute_raw_arguments
do return [n_expr2
]
1218 redef fun property_name
do return "=="
1219 redef fun accept_typing
(v
)
1223 var variable
= self.n_expr
.its_variable
1224 if variable
== null then return
1225 var mtype
= self.n_expr2
.mtype
1226 if not mtype
isa MNullType then return
1227 var vartype
= v
.get_variable
(self, variable
)
1228 if not vartype
isa MNullableType then return
1229 self.after_flow_context
.when_true
.set_var
(variable
, mtype
)
1230 self.after_flow_context
.when_false
.set_var
(variable
, vartype
.mtype
)
1231 #debug("adapt {variable}:{vartype} ; true->{mtype} false->{vartype.mtype}")
1235 redef fun property_name
do return "!="
1236 redef fun accept_typing
(v
)
1240 var variable
= self.n_expr
.its_variable
1241 if variable
== null then return
1242 var mtype
= self.n_expr2
.mtype
1243 if not mtype
isa MNullType then return
1244 var vartype
= v
.get_variable
(self, variable
)
1245 if not vartype
isa MNullableType then return
1246 self.after_flow_context
.when_false
.set_var
(variable
, mtype
)
1247 self.after_flow_context
.when_true
.set_var
(variable
, vartype
.mtype
)
1248 #debug("adapt {variable}:{vartype} ; true->{vartype.mtype} false->{mtype}")
1252 redef fun property_name
do return "<"
1255 redef fun property_name
do return "<="
1258 redef fun property_name
do return "<<"
1261 redef fun property_name
do return ">"
1264 redef fun property_name
do return ">="
1267 redef fun property_name
do return ">>"
1269 redef class APlusExpr
1270 redef fun property_name
do return "+"
1272 redef class AMinusExpr
1273 redef fun property_name
do return "-"
1275 redef class AStarshipExpr
1276 redef fun property_name
do return "<=>"
1278 redef class AStarExpr
1279 redef fun property_name
do return "*"
1281 redef class ASlashExpr
1282 redef fun property_name
do return "/"
1284 redef class APercentExpr
1285 redef fun property_name
do return "%"
1288 redef class AUminusExpr
1289 redef fun property_name
do return "unary -"
1290 redef fun compute_raw_arguments
do return new Array[AExpr]
1294 redef class ACallExpr
1295 redef fun property_name
do return n_id
.text
1296 redef fun compute_raw_arguments
do return n_args
.to_a
1299 redef class ACallAssignExpr
1300 redef fun property_name
do return n_id
.text
+ "="
1301 redef fun compute_raw_arguments
1303 var res
= n_args
.to_a
1309 redef class ABraExpr
1310 redef fun property_name
do return "[]"
1311 redef fun compute_raw_arguments
do return n_args
.to_a
1314 redef class ABraAssignExpr
1315 redef fun property_name
do return "[]="
1316 redef fun compute_raw_arguments
1318 var res
= n_args
.to_a
1324 redef class ASendReassignFormExpr
1325 # @depreciated use `write_callsite`
1326 fun write_mproperty
: nullable MMethod do return write_callsite
.mproperty
1328 # The property invoked for the writing
1329 var write_callsite
: nullable CallSite
1331 redef fun accept_typing
(v
)
1333 var recvtype
= v
.visit_expr
(self.n_expr
)
1334 var name
= self.property_name
1336 if recvtype
== null then return # Forward error
1337 if recvtype
isa MNullType then
1338 v
.error
(self, "Error: Method '{name}' call on 'null'.")
1342 var for_self
= self.n_expr
isa ASelfExpr
1343 var callsite
= v
.get_method
(self, recvtype
, name
, for_self
)
1345 if callsite
== null then return
1346 self.callsite
= callsite
1348 var args
= compute_raw_arguments
1349 self.raw_arguments
= args
1351 callsite
.check_signature
(v
, args
)
1353 var readtype
= callsite
.msignature
.return_mtype
1354 if readtype
== null then
1355 v
.error
(self, "Error: {name} is not a function")
1359 var wcallsite
= v
.get_method
(self, recvtype
, name
+ "=", self.n_expr
isa ASelfExpr)
1360 if wcallsite
== null then return
1361 self.write_callsite
= wcallsite
1363 var wtype
= self.resolve_reassignment
(v
, readtype
, wcallsite
.msignature
.mparameters
.last
.mtype
)
1364 if wtype
== null then return
1366 args
= args
.to_a
# duplicate so raw_arguments keeps only the getter args
1367 args
.add
(self.n_value
)
1368 wcallsite
.check_signature
(v
, args
)
1370 self.is_typed
= true
1374 redef class ACallReassignExpr
1375 redef fun property_name
do return n_id
.text
1376 redef fun compute_raw_arguments
do return n_args
.to_a
1379 redef class ABraReassignExpr
1380 redef fun property_name
do return "[]"
1381 redef fun compute_raw_arguments
do return n_args
.to_a
1384 redef class AInitExpr
1385 redef fun property_name
do return "init"
1386 redef fun compute_raw_arguments
do return n_args
.to_a
1390 fun to_a
: Array[AExpr] do return self.n_exprs
.to_a
1395 redef class ASuperExpr
1396 # The method to call if the super is in fact a 'super init call'
1397 # Note: if the super is a normal call-next-method, then this attribute is null
1398 var mproperty
: nullable MMethod
1400 redef fun accept_typing
(v
)
1402 var recvtype
= v
.nclassdef
.mclassdef
.bound_mtype
1403 var mproperty
= v
.mpropdef
.mproperty
1404 if not mproperty
isa MMethod then
1405 v
.error
(self, "Error: super only usable in a method")
1408 var superprops
= mproperty
.lookup_super_definitions
(v
.mmodule
, recvtype
)
1409 if superprops
.length
== 0 then
1410 if mproperty
.is_init
and v
.mpropdef
.is_intro
then
1411 process_superinit
(v
)
1414 v
.error
(self, "Error: No super method to call for {mproperty}.")
1417 # FIXME: covariance of return type in linear extension?
1418 var superprop
= superprops
.first
1419 assert superprop
isa MMethodDef
1421 var msignature
= v
.resolve_signature_for
(superprop
, recvtype
, true)
1422 var args
= self.n_args
.to_a
1423 if args
.length
> 0 then
1424 v
.check_signature
(self, args
, mproperty
.name
, msignature
)
1426 self.mtype
= msignature
.return_mtype
1429 private fun process_superinit
(v
: TypeVisitor)
1431 var recvtype
= v
.nclassdef
.mclassdef
.bound_mtype
1432 var mproperty
= v
.mpropdef
.mproperty
1433 var superprop
: nullable MMethodDef = null
1434 for msupertype
in v
.nclassdef
.mclassdef
.supertypes
do
1435 msupertype
= msupertype
.anchor_to
(v
.mmodule
, recvtype
)
1436 var errcount
= v
.modelbuilder
.toolcontext
.error_count
1437 var candidate
= v
.try_get_mproperty_by_name2
(self, msupertype
, mproperty
.name
).as(nullable MMethod)
1438 if candidate
== null then
1439 if v
.modelbuilder
.toolcontext
.error_count
> errcount
then return # Forard error
1440 continue # Try next super-class
1442 if superprop
!= null and superprop
.mproperty
!= candidate
then
1443 v
.error
(self, "Error: conflicting super constructor to call for {mproperty}: {candidate.full_name}, {superprop.mproperty.full_name}")
1446 var candidatedefs
= candidate
.lookup_definitions
(v
.mmodule
, recvtype
)
1447 if superprop
!= null then
1448 if superprop
== candidatedefs
.first
then continue
1449 candidatedefs
.add
(superprop
)
1451 if candidatedefs
.length
> 1 then
1452 v
.error
(self, "Error: confliting property definitions for property {mproperty} in {recvtype}: {candidatedefs.join(", ")}")
1455 superprop
= candidatedefs
.first
1457 if superprop
== null then
1458 v
.error
(self, "Error: No super method to call for {mproperty}.")
1461 self.mproperty
= superprop
.mproperty
1463 var args
= self.n_args
.to_a
1464 var msignature
= v
.resolve_signature_for
(superprop
, recvtype
, true)
1465 if args
.length
> 0 then
1466 v
.check_signature
(self, args
, mproperty
.name
, msignature
)
1468 # TODO: Check signature
1471 self.is_typed
= true
1477 redef class ANewExpr
1478 # @depreciated use `callsite`
1479 fun mproperty
: nullable MMethod do return self.callsite
.mproperty
1481 # The constructor invoked by the new.
1482 var callsite
: nullable CallSite
1484 redef fun accept_typing
(v
)
1486 var recvtype
= v
.resolve_mtype
(self.n_type
)
1487 if recvtype
== null then return
1488 self.mtype
= recvtype
1490 if not recvtype
isa MClassType then
1491 if recvtype
isa MNullableType then
1492 v
.error
(self, "Type error: cannot instantiate the nullable type {recvtype}.")
1495 v
.error
(self, "Type error: cannot instantiate the formal type {recvtype}.")
1507 var callsite
= v
.get_method
(self, recvtype
, name
, false)
1508 if callsite
== null then return
1510 self.callsite
= callsite
1512 if not callsite
.mproperty
.is_init_for
(recvtype
.mclass
) then
1513 v
.error
(self, "Error: {name} is not a constructor.")
1517 var args
= n_args
.to_a
1518 callsite
.check_signature
(v
, args
)
1524 redef class AAttrFormExpr
1525 # The attribute acceded.
1526 var mproperty
: nullable MAttribute
1528 # The static type of the attribute.
1529 var attr_type
: nullable MType
1531 # Resolve the attribute acceded.
1532 private fun resolve_property
(v
: TypeVisitor)
1534 var recvtype
= v
.visit_expr
(self.n_expr
)
1535 if recvtype
== null then return # Skip error
1536 var name
= self.n_id
.text
1537 if recvtype
isa MNullType then
1538 v
.error
(self, "Error: Attribute '{name}' access on 'null'.")
1542 var unsafe_type
= v
.anchor_to
(recvtype
)
1543 var mproperty
= v
.try_get_mproperty_by_name2
(self, unsafe_type
, name
)
1544 if mproperty
== null then
1545 v
.modelbuilder
.error
(self, "Error: Attribute {name} doesn't exists in {recvtype}.")
1548 assert mproperty
isa MAttribute
1549 self.mproperty
= mproperty
1551 var mpropdefs
= mproperty
.lookup_definitions
(v
.mmodule
, unsafe_type
)
1552 assert mpropdefs
.length
== 1
1553 var mpropdef
= mpropdefs
.first
1554 var attr_type
= mpropdef
.static_mtype
.as(not null)
1555 attr_type
= v
.resolve_for
(attr_type
, recvtype
, self.n_expr
isa ASelfExpr)
1556 self.attr_type
= attr_type
1560 redef class AAttrExpr
1561 redef fun accept_typing
(v
)
1563 self.resolve_property
(v
)
1564 self.mtype
= self.attr_type
1569 redef class AAttrAssignExpr
1570 redef fun accept_typing
(v
)
1572 self.resolve_property
(v
)
1573 var mtype
= self.attr_type
1575 v
.visit_expr_subtype
(self.n_value
, mtype
)
1576 self.is_typed
= true
1580 redef class AAttrReassignExpr
1581 redef fun accept_typing
(v
)
1583 self.resolve_property
(v
)
1584 var mtype
= self.attr_type
1585 if mtype
== null then return # Skip error
1587 self.resolve_reassignment
(v
, mtype
, mtype
)
1589 self.is_typed
= true
1593 redef class AIssetAttrExpr
1594 redef fun accept_typing
(v
)
1596 self.resolve_property
(v
)
1597 var mtype
= self.attr_type
1598 if mtype
== null then return # Skip error
1600 var recvtype
= self.n_expr
.mtype
.as(not null)
1601 var bound
= v
.resolve_for
(mtype
, recvtype
, false)
1602 if bound
isa MNullableType then
1603 v
.error
(self, "Error: isset on a nullable attribute.")
1605 self.mtype
= v
.type_bool
(self)
1611 redef class AClosureCallExpr
1612 redef fun accept_typing
(v
)
1614 var variable
= self.variable
1615 if variable
== null then return # Skip error
1617 var recvtype
= v
.nclassdef
.mclassdef
.bound_mtype
1618 var msignature
= variable
.declared_type
.as(not null)
1619 msignature
= v
.resolve_for
(msignature
, recvtype
, false).as(MSignature)
1621 var args
= n_args
.to_a
1622 v
.check_signature
(self, args
, variable
.name
, msignature
)
1624 self.is_typed
= true
1625 self.mtype
= msignature
.return_mtype
1629 redef class AClosureDef
1630 var mclosure
: nullable MParameter
1632 private fun accept_typing
(v
: TypeVisitor, mparameter
: MParameter)
1634 var variables
= self.variables
1635 if variables
== null then return
1637 self.mclosure
= mparameter
1638 var msignature
= mparameter
.mtype
.as(MSignature)
1640 if msignature
.arity
!= variables
.length
then
1641 v
.error
(self, "Type error: closure {mparameter.name} expects {msignature.arity} parameters, {variables.length} given")
1645 for i
in [0..variables
.length
[ do
1646 variables
[i
].declared_type
= msignature
.mparameters
[i
].mtype
1649 v
.visit_stmt
(self.n_expr
)
1655 redef class ADebugTypeExpr
1656 redef fun accept_typing
(v
)
1658 var expr
= v
.visit_expr
(self.n_expr
)
1659 if expr
== null then return
1660 var unsafe
= v
.anchor_to
(expr
)
1661 var ntype
= self.n_type
1662 var mtype
= v
.resolve_mtype
(ntype
)
1663 if mtype
!= null and mtype
!= expr
then
1664 var umtype
= v
.anchor_to
(mtype
)
1665 v
.modelbuilder
.warning
(self, "Found type {expr} (-> {unsafe}), expected {mtype} (-> {umtype})")