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.
25 redef class ToolContext
26 var typing_phase
: Phase = new TypingPhase(self, [flow_phase
, modelize_property_phase
, local_var_init_phase
])
29 private class TypingPhase
31 redef fun process_npropdef
(npropdef
) do npropdef
.do_typing
(toolcontext
.modelbuilder
)
34 private class TypeVisitor
35 var modelbuilder
: ModelBuilder
37 # The module of the analysis
38 # Used to correctly query the model
39 var mmodule
: MModule is noinit
41 # The static type of the receiver
42 # Mainly used for type tests and type resolutions
43 var anchor
: MClassType is noinit
45 # The analyzed mclassdef
46 var mclassdef
: MClassDef is noinit
48 # The analyzed property
49 var mpropdef
: MPropDef
51 var selfvariable
= new Variable("self")
53 # Is `self` use restricted?
54 # * no explicit `self`
55 # * method called on the implicit self must be top-level
56 # Currently only used for `new` factory since there is no valid receiver inside
57 var is_toplevel_context
= false
61 var mpropdef
= self.mpropdef
62 var mclassdef
= mpropdef
.mclassdef
63 mmodule
= mclassdef
.mmodule
64 self.mclassdef
= mclassdef
65 self.anchor
= mclassdef
.bound_mtype
67 var mclass
= mclassdef
.mclass
69 var selfvariable
= new Variable("self")
70 self.selfvariable
= selfvariable
71 selfvariable
.declared_type
= mclass
.mclass_type
73 var mprop
= mpropdef
.mproperty
74 if mprop
isa MMethod and mprop
.is_new
then
75 is_toplevel_context
= true
79 fun anchor_to
(mtype
: MType): MType
81 return mtype
.anchor_to
(mmodule
, anchor
)
84 fun is_subtype
(sub
, sup
: MType): Bool
86 return sub
.is_subtype
(mmodule
, anchor
, sup
)
89 fun resolve_for
(mtype
, subtype
: MType, for_self
: Bool): MType
91 #print "resolve_for {mtype} sub={subtype} forself={for_self} mmodule={mmodule} anchor={anchor}"
92 var res
= mtype
.resolve_for
(subtype
, anchor
, mmodule
, not for_self
)
96 # Check that `sub` is a subtype of `sup`.
97 # If `sub` is not a valid suptype, then display an error on `node` and return `null`.
98 # If `sub` is a safe subtype of `sup`, then return `sub`.
99 # If `sub` is an unsafe subtype (i.e., an implicit cast is required), then return `sup`.
101 # The point of the return type is to determinate the usable type on an expression when `autocast` is true:
102 # If the suptype is safe, then the return type is the one on the expression typed by `sub`.
103 # Is the subtype is unsafe, then the return type is the one of an implicit cast on `sup`.
104 fun check_subtype
(node
: ANode, sub
, sup
: MType, autocast
: Bool): nullable MType
106 if self.is_subtype
(sub
, sup
) then return sub
107 if autocast
and self.is_subtype
(sub
, self.anchor_to
(sup
)) then
108 # FIXME workaround to the current unsafe typing policy. To remove once fixed virtual types exists.
109 #node.debug("Unsafe typing: expected {sup}, got {sub}")
112 if sup
isa MErrorType then return null # Skip error
113 if sub
.need_anchor
then
114 var u
= anchor_to
(sub
)
115 self.modelbuilder
.error
(node
, "Type Error: expected `{sup}`, got `{sub}: {u}`.")
117 self.modelbuilder
.error
(node
, "Type Error: expected `{sup}`, got `{sub}`.")
122 # Visit an expression and do not care about the return value
123 fun visit_stmt
(nexpr
: nullable AExpr)
125 if nexpr
== null then return
126 nexpr
.accept_typing
(self)
129 # Visit an expression and expects that it is not a statement
130 # Return the type of the expression
131 # Display an error and return null if:
132 # * the type cannot be determined or
133 # * `nexpr` is a statement
134 fun visit_expr
(nexpr
: AExpr): nullable MType
136 nexpr
.accept_typing
(self)
137 var mtype
= nexpr
.mtype
138 if mtype
!= null then return mtype
139 if not nexpr
.is_typed
then
140 if not self.modelbuilder
.toolcontext
.error_count
> 0 then # check that there is really an error
141 if self.modelbuilder
.toolcontext
.verbose_level
> 1 then
142 nexpr
.debug
("No return type but no error.")
145 return null # forward error
147 var more_message
= null
149 if p
!= null then more_message
= p
.bad_expr_message
(nexpr
)
150 if more_message
== null then more_message
= "" else more_message
= " " + more_message
151 self.error
(nexpr
, "Error: expected an expression{more_message}.")
155 # Visit an expression and expect its static type is a least a `sup`
156 # Return the type of the expression or null if
157 # * the type cannot be determined or
158 # * `nexpr` is a statement or
159 # * `nexpr` is not a `sup`
160 fun visit_expr_subtype
(nexpr
: AExpr, sup
: nullable MType): nullable MType
162 var sub
= visit_expr
(nexpr
)
163 if sub
== null then return null # Forward error
165 if sup
== null then return null # Forward error
167 var res
= check_subtype
(nexpr
, sub
, sup
, true)
169 nexpr
.implicit_cast_to
= res
174 # Visit an expression and expect its static type is a `Bool`
175 # Return the type of the expression or null if
176 # * the type cannot be determined or
177 # * `nexpr` is a statement or
178 # * `nexpr` is not a `Bool`
179 fun visit_expr_bool
(nexpr
: AExpr): nullable MType
181 return self.visit_expr_subtype
(nexpr
, self.type_bool
(nexpr
))
184 fun check_expr_cast
(node
: ANode, nexpr
: AExpr, ntype
: AType): nullable MType
186 var sub
= nexpr
.mtype
187 if sub
== null then return null # Forward error
189 var sup
= ntype
.mtype
190 if sup
== null then return null # Forward error
193 self.modelbuilder
.warning
(node
, "useless-type-test", "Warning: expression is already a `{sup}`.")
194 else if self.is_subtype
(sub
, sup
) then
195 self.modelbuilder
.warning
(node
, "useless-type-test", "Warning: expression is already a `{sup}` since it is a `{sub}`.")
200 # Can `mtype` be null (up to the current knowledge)?
201 fun can_be_null
(mtype
: MType): Bool
203 if mtype
isa MNullableType or mtype
isa MNullType then return true
204 if mtype
isa MFormalType then
205 var x
= anchor_to
(mtype
)
206 if x
isa MNullableType or x
isa MNullType then return true
211 # Check that `mtype` can be null (up to the current knowledge).
213 # If not then display a `useless-null-test` warning on node and return false.
215 fun check_can_be_null
(anode
: ANode, mtype
: MType): Bool
217 if mtype
isa MNullType then
218 modelbuilder
.warning
(anode
, "useless-null-test", "Warning: expression is always `null`.")
221 if can_be_null
(mtype
) then return true
223 if mtype
isa MFormalType then
224 var res
= anchor_to
(mtype
)
225 modelbuilder
.warning
(anode
, "useless-null-test", "Warning: expression is not null, since it is a `{mtype}: {res}`.")
227 modelbuilder
.warning
(anode
, "useless-null-test", "Warning: expression is not null, since it is a `{mtype}`.")
232 # Special verification on != and == for null
234 fun null_test
(anode
: ABinopExpr)
236 var mtype
= anode
.n_expr
.mtype
237 var mtype2
= anode
.n_expr2
.mtype
239 if mtype
== null or mtype2
== null then return
241 if not mtype2
isa MNullType then return
243 # Check of useless null
244 if not can_be_null
(mtype
) then return
246 if mtype
isa MNullType then
247 # Because of type adaptation, we cannot just stop here
248 # so return use `null` as a bottom type that will be merged easily (cf) `merge_types`
251 mtype
= mtype
.as_notnull
254 # Check for type adaptation
255 var variable
= anode
.n_expr
.its_variable
256 if variable
== null then return
258 # One is null (mtype2 see above) the other is not null
259 if anode
isa AEqExpr then
260 anode
.after_flow_context
.when_true
.set_var
(self, variable
, mtype2
)
261 anode
.after_flow_context
.when_false
.set_var
(self, variable
, mtype
)
262 else if anode
isa ANeExpr then
263 anode
.after_flow_context
.when_false
.set_var
(self, variable
, mtype2
)
264 anode
.after_flow_context
.when_true
.set_var
(self, variable
, mtype
)
270 fun try_get_mproperty_by_name2
(anode
: ANode, mtype
: MType, name
: String): nullable MProperty
272 return self.modelbuilder
.try_get_mproperty_by_name2
(anode
, mmodule
, mtype
, name
)
275 fun resolve_mtype
(node
: AType): nullable MType
277 return self.modelbuilder
.resolve_mtype
(mclassdef
, node
)
280 fun try_get_mclass
(node
: ANode, name
: String): nullable MClass
282 var mclass
= modelbuilder
.try_get_mclass_by_name
(node
, mmodule
, name
)
286 fun get_mclass
(node
: ANode, name
: String): nullable MClass
288 var mclass
= modelbuilder
.get_mclass_by_name
(node
, mmodule
, name
)
292 fun type_bool
(node
: ANode): nullable MType
294 var mclass
= self.get_mclass
(node
, "Bool")
295 if mclass
== null then return null
296 return mclass
.mclass_type
299 # Construction of a specific callsite according to the current context.
300 # Three entry points exist to create a callsite based on knowledge.
301 # The `build_callsite_by_name` is a top entry point, the method find the mpropdefs to call by the name of this.
302 # see `build_callsite_by_property` and `build_callsite_by_propdef` for more detail.
303 # If you already know the mpropdef to call use directly the `get_method_by_propdef` method
304 # If you just know the mproperty use the `build_callsite_by_property` method to display error if no `mpropdef` is found in the context
305 fun build_callsite_by_name
(node
: ANode, recvtype
: MType, name
: String, recv_is_self
: Bool): nullable CallSite
307 var unsafe_type
= self.anchor_to
(recvtype
)
309 #debug("recv: {recvtype} (aka {unsafe_type})")
310 if recvtype
isa MNullType then
311 var objclass
= get_mclass
(node
, "Object")
312 if objclass
== null then return null # Forward error
313 unsafe_type
= objclass
.mclass_type
316 var mproperty
= self.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
317 if name
== "new" and mproperty
== null then
319 mproperty
= self.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
320 if mproperty
== null then
322 mproperty
= self.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
326 if mproperty
== null then
328 # FIXME This test was added to display a more explicit error when a potential duplication of root object class.
329 if name
== "init" then
330 self.modelbuilder
.error
(node
, "Possible duplication of the root class `Object`")
332 self.modelbuilder
.error
(node
, "Error: method or variable `{name}` unknown in `{recvtype}`.")
334 else if recvtype
.need_anchor
then
335 self.modelbuilder
.error
(node
, "Error: method `{name}` does not exists in `{recvtype}: {unsafe_type}`.")
337 self.modelbuilder
.error
(node
, "Error: method `{name}` does not exists in `{recvtype}`.")
342 assert mproperty
isa MMethod
344 return build_callsite_by_property
(node
, recvtype
, mproperty
, recv_is_self
)
347 # The `build_callsite_by_property` finds the mpropdefs to call by the `MMethod`.
348 # If the mpropdef is found in the context it builds a new `Callsite`.
349 fun build_callsite_by_property
(node
: ANode, recvtype
: MType, mproperty
: MMethod, recv_is_self
: Bool): nullable CallSite
351 var unsafe_type
= self.anchor_to
(recvtype
)
353 if recvtype
isa MNullType then
354 var objclass
= get_mclass
(node
, "Object")
355 if objclass
== null then return null # Forward error
356 unsafe_type
= objclass
.mclass_type
358 # `null` only accepts some methods of object.
359 if recvtype
isa MNullType and not mproperty
.is_null_safe
then
360 self.error
(node
, "Error: method `{mproperty.name}` called on `null`.")
362 else if unsafe_type
isa MNullableType and not mproperty
.is_null_safe
then
363 modelbuilder
.advice
(node
, "call-on-nullable", "Warning: method call on a nullable receiver `{recvtype}`.")
366 if is_toplevel_context
and recv_is_self
and not mproperty
.is_toplevel
then
367 error
(node
, "Error: `{mproperty.name}` is not a top-level method, thus need a receiver.")
369 if not recv_is_self
and mproperty
.is_toplevel
then
370 error
(node
, "Error: cannot call `{mproperty.name}`, a top-level method, with a receiver.")
373 if mproperty
.visibility
== protected_visibility
and not recv_is_self
and self.mmodule
.visibility_for
(mproperty
.intro_mclassdef
.mmodule
) < intrude_visibility
and not modelbuilder
.toolcontext
.opt_ignore_visibility
.value
then
374 self.modelbuilder
.error
(node
, "Error: method `{mproperty.name}` is protected and can only accessed by `self`.")
378 var info
= mproperty
.deprecation
379 if info
!= null and self.mpropdef
.mproperty
.deprecation
== null then
382 self.modelbuilder
.warning
(node
, "deprecated-method", "Deprecation Warning: method `{mproperty.name}` is deprecated: {mdoc.content.first}")
384 self.modelbuilder
.warning
(node
, "deprecated-method", "Deprecation Warning: method `{mproperty.name}` is deprecated.")
388 var propdefs
= mproperty
.lookup_definitions
(self.mmodule
, unsafe_type
)
390 if propdefs
.length
== 0 then
391 self.modelbuilder
.error
(node
, "Type Error: no definition found for property `{mproperty.name}` in `{unsafe_type}`.")
394 else if propdefs
.length
== 1 then
395 mpropdef
= propdefs
.first
397 self.modelbuilder
.warning
(node
, "property-conflict", "Warning: conflicting property definitions for property `{mproperty.name}` in `{unsafe_type}`: {propdefs.join(" ")}")
398 mpropdef
= mproperty
.intro
401 return build_callsite_by_propdef
(node
, recvtype
, mpropdef
, recv_is_self
)
404 # The `build_callsite_by_propdef` builds the callsite directly with the `mprodef` passed in argument.
405 fun build_callsite_by_propdef
(node
: ANode, recvtype
: MType, mpropdef
: MMethodDef, recv_is_self
: Bool): nullable CallSite
407 var msignature
= mpropdef
.msignature
408 if msignature
== null then return null # skip error
409 msignature
= resolve_for
(msignature
, recvtype
, recv_is_self
).as(MSignature)
411 var erasure_cast
= false
412 var rettype
= mpropdef
.msignature
.return_mtype
413 if not recv_is_self
and rettype
!= null then
414 rettype
= rettype
.undecorate
415 if rettype
isa MParameterType then
416 var erased_rettype
= msignature
.return_mtype
417 assert erased_rettype
!= null
418 #node.debug("Erasure cast: Really a {rettype} but unsafely a {erased_rettype}")
423 var callsite
= new CallSite(node
.hot_location
, recvtype
, mmodule
, anchor
, recv_is_self
, mpropdef
.mproperty
, mpropdef
, msignature
, erasure_cast
)
427 fun try_build_callsite_by_name
(node
: ANode, recvtype
: MType, name
: String, recv_is_self
: Bool): nullable CallSite
429 var unsafe_type
= self.anchor_to
(recvtype
)
430 var mproperty
= self.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
431 if mproperty
== null then return null
432 return build_callsite_by_name
(node
, recvtype
, name
, recv_is_self
)
435 # Visit the expressions of args and check their conformity with the corresponding type in signature
436 # The point of this method is to handle varargs correctly
437 # Note: The signature must be correctly adapted
438 fun check_signature
(node
: ANode, args
: Array[AExpr], mproperty
: MProperty, msignature
: MSignature): nullable SignatureMap
440 var vararg_rank
= msignature
.vararg_rank
441 if vararg_rank
>= 0 then
442 if args
.length
< msignature
.arity
then
443 modelbuilder
.error
(node
, "Error: expected at least {msignature.arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
446 else if args
.length
!= msignature
.arity
then
448 if args
.length
> msignature
.arity
then
449 modelbuilder
.error
(node
, "Error: expected {msignature.arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
452 # Other cases are managed later
455 #debug("CALL {unsafe_type}.{msignature}")
457 # Associate each parameter to a position in the arguments
458 var map
= new SignatureMap
460 # Special case for the isolated last argument
461 # TODO: reify this method characteristics (where? the param, the signature, the method?)
462 var last_is_padded
= mproperty
.name
.chars
.last
== '='
463 var nbargs
= args
.length
464 if last_is_padded
then
466 assert not args
.last
isa ANamedargExpr
467 map
.map
[msignature
.arity
- 1] = args
.length
- 1
468 self.visit_expr_subtype
(args
.last
, msignature
.mparameters
.last
.mtype
)
471 # First, handle named arguments
472 for i
in [0..args
.length
[ do
474 if not e
isa ANamedargExpr then continue
475 var name
= e
.n_id
.text
476 var param
= msignature
.mparameter_by_name
(name
)
477 if param
== null then
478 modelbuilder
.error
(e
.n_id
, "Error: no parameter `{name}` for `{mproperty}{msignature}`.")
481 var idx
= msignature
.mparameters
.index_of
(param
)
482 var prev
= map
.map
.get_or_null
(idx
)
484 modelbuilder
.error
(e
, "Error: parameter `{name}` already associated with argument #{prev} for `{mproperty}{msignature}`.")
488 e
.mtype
= self.visit_expr_subtype
(e
.n_expr
, param
.mtype
)
491 # Number of minimum mandatory remaining parameters
494 # Second, associate remaining parameters
495 var vararg_decl
= args
.length
- msignature
.arity
497 for i
in [0..msignature
.arity
[ do
498 # Skip parameters associated by name
499 if map
.map
.has_key
(i
) then continue
501 var param
= msignature
.mparameters
[i
]
503 # Search the next free argument: skip named arguments since they are already associated
504 while j
< nbargs
and args
[j
] isa ANamedargExpr do j
+= 1
506 if not param
.mtype
isa MNullableType then
516 if i
== vararg_rank
then
518 continue # skip the vararg
521 if not param
.is_vararg
then
522 var paramtype
= param
.mtype
523 self.visit_expr_subtype
(arg
, paramtype
)
525 check_one_vararg
(arg
, param
)
529 if min_arity
> 0 then
530 if last_is_padded
then min_arity
+= 1
531 if min_arity
< msignature
.arity
then
532 modelbuilder
.error
(node
, "Error: expected at least {min_arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
534 modelbuilder
.error
(node
, "Error: expected {min_arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
539 # Third, check varargs
540 if vararg_rank
>= 0 then
541 var paramtype
= msignature
.mparameters
[vararg_rank
].mtype
542 var first
= args
[vararg_rank
]
543 if vararg_decl
== 0 then
544 if not check_one_vararg
(first
, msignature
.mparameters
[vararg_rank
]) then return null
546 first
.vararg_decl
= vararg_decl
+ 1
547 for i
in [vararg_rank
..vararg_rank
+vararg_decl
] do
548 self.visit_expr_subtype
(args
[i
], paramtype
)
556 # Check an expression as a single vararg.
557 # The main point of the method if to handle the case of reversed vararg (see `AVarargExpr`)
558 fun check_one_vararg
(arg
: AExpr, param
: MParameter): Bool
560 var paramtype
= param
.mtype
561 var mclass
= get_mclass
(arg
, "Array")
562 if mclass
== null then return false # Forward error
563 var array_mtype
= mclass
.get_mtype
([paramtype
])
564 if arg
isa AVarargExpr then
565 self.visit_expr_subtype
(arg
.n_expr
, array_mtype
)
566 arg
.mtype
= arg
.n_expr
.mtype
568 # only one vararg, maybe `...` was forgot, so be gentle!
569 var t
= visit_expr
(arg
)
570 if t
== null then return false # Forward error
571 if not is_subtype
(t
, paramtype
) and is_subtype
(t
, array_mtype
) then
572 # Not acceptable but could be a `...`
573 error
(arg
, "Type Error: expected `{paramtype}`, got `{t}`. Is an ellipsis `...` missing on the argument?")
576 # Standard valid vararg, finish the job
578 self.visit_expr_subtype
(arg
, paramtype
)
583 fun error
(node
: ANode, message
: String)
585 self.modelbuilder
.error
(node
, message
)
588 fun get_variable
(node
: AExpr, variable
: Variable): nullable MType
590 if not variable
.is_adapted
then return variable
.declared_type
592 var flow
= node
.after_flow_context
593 if flow
== null then return null # skip error
595 if flow
.vars
.has_key
(variable
) then
596 return flow
.vars
[variable
]
598 #node.debug("*** START Collected for {variable}")
599 var mtypes
= flow
.collect_types
(variable
)
600 #node.debug("**** END Collected for {variable}")
601 if mtypes
.length
== 0 then
602 return variable
.declared_type
603 else if mtypes
.length
== 1 then
606 var res
= merge_types
(node
,mtypes
)
608 res
= variable
.declared_type
609 # Try to fallback to a non-null version
610 if res
!= null and can_be_null
(res
) then do
612 if t
!= null and can_be_null
(t
) then break label
622 # Some variables where type-adapted during the visit
625 # Some loops had been visited during the visit
628 fun set_variable
(node
: AExpr, variable
: Variable, mtype
: nullable MType)
630 var flow
= node
.after_flow_context
633 flow
.set_var
(self, variable
, mtype
)
636 # Find the exact representable most specific common super-type in `col`.
638 # Try to find the most specific common type that is a super-type of each types
640 # In most cases, the result is simply the most general type in `col`.
641 # If nullables types are involved, then the nullable information is correctly preserved.
642 # If incomparable super-types exists in `col`, them no solution is given and the `null`
643 # value is returned (since union types are non representable in Nit)
645 # The `null` values in `col` are ignored, nulltypes (MNullType) are considered.
647 # Returns the `null` value if:
650 # * `col` only have null values
651 # * there is a conflict
653 # Example (with a diamond A,B,C,D):
655 # * merge(A,B,C) -> A, because A is the most general type in {A,B,C}
656 # * merge(C,B) -> null, there is conflict, because `B or C` cannot be represented
657 # * merge(A,nullable B) -> nullable A, because A is the most general type and
658 # the nullable information is preserved
659 fun merge_types
(node
: ANode, col
: Array[nullable MType]): nullable MType
661 if col
.length
== 1 then return col
.first
663 if t1
== null then continue # return null
666 if t2
== null then continue # return null
667 if can_be_null
(t2
) and not can_be_null
(t1
) then
670 if not is_subtype
(t2
, t1
) then found
= false
673 #print "merge {col.join(" ")} -> {t1}"
677 #self.modelbuilder.warning(node, "Type Error: {col.length} conflicting types: <{col.join(", ")}>")
681 # Find a most general common subtype between `type1` and `type2`.
683 # Find the most general type that is a subtype of `type2` and, if possible, a subtype of `type1`.
684 # Basically, this return the most specific type between `type1` and `type2`.
685 # If nullable types are involved, the information is correctly preserved.
686 # If `type1` and `type2` are incomparable then `type2` is preferred (since intersection types
687 # are not representable in Nit).
689 # The `null` value is returned if both `type1` and `type2` are null.
691 # Examples (with diamond A,B,C,D):
693 # * intersect_types(A,B) -> B, because B is a subtype of A
694 # * intersect_types(B,A) -> B, because B is a subtype of A
695 # * intersect_types(B,C) -> C, B and C are incomparable,
696 # `type2` is then preferred (`B and C` cannot be represented)
697 # * intersect_types(nullable B,A) -> B, because B<:A and the non-null information is preserved
698 # * intersect_types(B,nullable C) -> C, `type2` is preferred and the non-null information is preserved
699 fun intersect_types
(node
: ANode, type1
, type2
: nullable MType): nullable MType
701 if type1
== null then return type2
702 if type2
== null then return type1
704 if not can_be_null
(type2
) or not can_be_null
(type1
) then
705 type1
= type1
.as_notnull
706 type2
= type2
.as_notnull
710 if is_subtype
(type1
, type2
) then
718 # Find a most general type that is a subtype of `type1` but not one of `type2`.
720 # Basically, this returns `type1`-`type2` but since there is no substraction type
721 # in Nit this just returns `type1` most of the case.
723 # The few other cases are if `type2` is a super-type and if some nullable information
726 # The `null` value is returned if `type1` is null.
728 # Examples (with diamond A,B,C,D):
730 # * diff_types(A,B) -> A, because the notB cannot be represented
731 # * diff_types(B,A) -> None (absurd type), because B<:A
732 # * diff_types(nullable A, nullable B) -> A, because null is removed
733 # * diff_types(nullable B, A) -> Null, because anything but null is removed
734 fun diff_types
(node
: ANode, type1
, type2
: nullable MType): nullable MType
736 if type1
== null then return null
737 if type2
== null then return type1
739 # if t1 <: t2 then t1-t2 = bottom
740 if is_subtype
(type1
, type2
) then
741 return modelbuilder
.model
.null_type
.as_notnull
744 # else if t1 <: nullable t2 then t1-t2 = nulltype
745 if is_subtype
(type1
, type2
.as_nullable
) then
746 return modelbuilder
.model
.null_type
749 # else t2 can be null and type2 must accept null then null is excluded in t1
750 if can_be_null
(type1
) and (type2
isa MNullableType or type2
isa MNullType) then
751 return type1
.as_notnull
758 # Mapping between parameters and arguments in a call.
760 # Parameters and arguments are not stored in the class but referenced by their position (starting from 0)
762 # The point of this class is to help engine and other things to map arguments in the AST to parameters of the model.
764 # Associate a parameter to an argument
765 var map
= new ArrayMap[Int, Int]
768 # A specific method call site with its associated informations.
774 # The static type of the receiver (possibly unresolved)
777 # The module where the callsite is present
780 # The anchor to use with `recv` or `msignature`
781 var anchor
: nullable MClassType
783 # Is the receiver self?
784 # If "for_self", virtual types of the signature are kept
785 # If "not_for_self", virtual type are erased
786 var recv_is_self
: Bool
788 # The designated method
789 var mproperty
: MMethod
791 # The statically designated method definition
792 # The most specif one, it is.
793 var mpropdef
: MMethodDef
795 # The resolved signature for the receiver
796 var msignature
: MSignature
798 # Is a implicit cast required on erasure typing policy?
799 var erasure_cast
: Bool
801 # The mapping used on the call to associate arguments to parameters
802 # If null then no specific association is required.
803 var signaturemap
: nullable SignatureMap = null
805 private fun check_signature
(v
: TypeVisitor, node
: ANode, args
: Array[AExpr]): Bool
807 var map
= v
.check_signature
(node
, args
, self.mproperty
, self.msignature
)
809 if map
== null then is_broken
= true
813 # Information about the callsite to display on a node
814 fun dump_info
(v
: ASTDump): String do
815 return "{recv}.{mpropdef}{msignature}"
818 redef fun mdoc_or_fallback
do return mproperty
.intro
.mdoc
822 # The declared type of the variable
823 var declared_type
: nullable MType = null is writable
825 # Was the variable type-adapted?
826 # This is used to speedup type retrieval while it remains `false`
827 private var is_adapted
= false
830 redef class FlowContext
831 # Store changes of types because of type evolution
832 private var vars
= new HashMap[Variable, nullable MType]
834 # Adapt the variable to a static type
835 # Warning1: do not modify vars directly.
836 # Warning2: sub-flow may have cached a unadapted variable
837 private fun set_var
(v
: TypeVisitor, variable
: Variable, mtype
: nullable MType)
839 if variable
.declared_type
== mtype
and not variable
.is_adapted
then return
840 if vars
.has_key
(variable
) and vars
[variable
] == mtype
then return
841 self.vars
[variable
] = mtype
843 variable
.is_adapted
= true
844 #node.debug "set {variable} to {mtype or else "X"}"
847 # Look in the flow and previous flow and collect all first reachable type adaptation of a local variable
848 private fun collect_types
(variable
: Variable): Array[nullable MType]
850 #node.debug "flow for {variable}"
851 var res
= new Array[nullable MType]
854 var seen
= new HashSet[FlowContext]
855 while not todo
.is_empty
do
857 if f
.is_unreachable
then continue
858 if seen
.has
(f
) then continue
861 if f
.vars
.has_key
(variable
) then
862 # Found something. Collect it and do not process further on this path
863 res
.add f
.vars
[variable
]
864 #f.node.debug "process {variable}: got {f.vars[variable] or else "X"}"
866 todo
.add_all f
.previous
868 if f
.previous
.is_empty
then
869 # Root flowcontext mean a parameter or something related
870 res
.add variable
.declared_type
871 #f.node.debug "root process {variable}: got {variable.declared_type or else "X"}"
875 #self.node.debug "##### end flow for {variable}: {res.join(" ")}"
881 # The entry point of the whole typing analysis
882 fun do_typing
(modelbuilder
: ModelBuilder)
886 # The variable associated to the receiver (if any)
887 var selfvariable
: nullable Variable
890 redef class AMethPropdef
891 redef fun do_typing
(modelbuilder
: ModelBuilder)
893 var mpropdef
= self.mpropdef
894 if mpropdef
== null then return # skip error
896 var v
= new TypeVisitor(modelbuilder
, mpropdef
)
897 self.selfvariable
= v
.selfvariable
899 var mmethoddef
= self.mpropdef
.as(not null)
900 var msignature
= mmethoddef
.msignature
901 if msignature
== null then return # skip error
902 for i
in [0..msignature
.arity
[ do
903 var mtype
= msignature
.mparameters
[i
].mtype
904 if msignature
.vararg_rank
== i
then
905 var arrayclass
= v
.get_mclass
(self.n_signature
.n_params
[i
], "Array")
906 if arrayclass
== null then return # Skip error
907 mtype
= arrayclass
.get_mtype
([mtype
])
909 var variable
= self.n_signature
.n_params
[i
].variable
910 assert variable
!= null
911 variable
.declared_type
= mtype
914 var nblock
= self.n_block
915 if nblock
== null then return
920 if not v
.has_loop
or not v
.dirty
then break
923 var post_visitor
= new PostTypingVisitor(v
)
924 post_visitor
.enter_visit
(self)
926 if not nblock
.after_flow_context
.is_unreachable
and msignature
.return_mtype
!= null then
927 # We reach the end of the function without having a return, it is bad
928 v
.error
(self, "Error: reached end of function; expected `return` with a value.")
933 private class PostTypingVisitor
935 var type_visitor
: TypeVisitor
936 redef fun visit
(n
) do
938 n
.accept_post_typing
(type_visitor
)
939 if n
isa AExpr and n
.mtype
== null and not n
.is_typed
then
946 private fun accept_post_typing
(v
: TypeVisitor) do end
948 # An additional information message to explain the role of a child expression.
950 # The point of the method is to allow some kind of double dispatch so the parent
951 # choose how to describe its children.
952 private fun bad_expr_message
(child
: AExpr): nullable String do return null
955 redef class AAttrPropdef
956 redef fun do_typing
(modelbuilder
: ModelBuilder)
958 if not has_value
then return
960 var mpropdef
= self.mreadpropdef
961 if mpropdef
== null or mpropdef
.msignature
== null then return # skip error
963 var v
= new TypeVisitor(modelbuilder
, mpropdef
)
964 self.selfvariable
= v
.selfvariable
966 var nexpr
= self.n_expr
967 if nexpr
!= null then
968 var mtype
= self.mtype
969 v
.visit_expr_subtype
(nexpr
, mtype
)
971 var nblock
= self.n_block
972 if nblock
!= null then
974 if not nblock
.after_flow_context
.is_unreachable
then
975 # We reach the end of the init without having a return, it is bad
976 v
.error
(self, "Error: reached end of block; expected `return`.")
985 # The static type of the expression.
986 # null if self is a statement or in case of error
987 var mtype
: nullable MType = null
989 # Is the statement correctly typed?
990 # Used to distinguish errors and statements when `mtype == null`
991 var is_typed
: Bool = false
993 # If required, the following implicit cast `.as(XXX)`
994 # Such a cast may by required after evaluating the expression when
995 # a unsafe operation is detected (silently accepted by the Nit language).
996 # The attribute is computed by `check_subtype`
997 var implicit_cast_to
: nullable MType = null
999 # Return the variable read (if any)
1000 # Used to perform adaptive typing
1001 fun its_variable
: nullable Variable do return null
1003 private fun accept_typing
(v
: TypeVisitor)
1005 v
.error
(self, "no implemented accept_typing for {self.class_name}")
1008 # Is non-null if `self` is a leaf of a comprehension array construction.
1009 # In this case, the enclosing literal array node is designated.
1010 # The result of the evaluation of `self` must be
1011 # stored inside the designated array (there is an implicit `push`)
1012 var comprehension
: nullable AArrayExpr = null
1014 # It indicates the number of arguments collected as a vararg.
1016 # When 0, the argument is used as is, without transformation.
1017 # When 1, the argument is transformed into an singleton array.
1018 # Above 1, the arguments and the next ones are transformed into a common array.
1020 # This attribute is meaning less on expressions not used as attributes.
1021 var vararg_decl
: Int = 0
1023 redef fun dump_info
(v
) do
1025 var mtype
= self.mtype
1026 if mtype
!= null then
1027 res
+= v
.yellow
(":{mtype}")
1029 var ict
= self.implicit_cast_to
1031 res
+= v
.yellow
("(.as({ict}))")
1036 # Type the expression as if located in `visited_mpropdef`
1037 # `TypeVisitor` and `PostTypingVisitor` will be used to do the typing, see them for more information.
1039 # `visited_mpropdef`: Correspond to the evaluation context in which the expression is located.
1040 fun do_typing
(modelbuilder
: ModelBuilder, visited_mpropdef
: MPropDef)
1042 var type_visitor
= new TypeVisitor(modelbuilder
, visited_mpropdef
)
1043 type_visitor
.visit_stmt
(self)
1044 var post_visitor
= new PostTypingVisitor(type_visitor
)
1045 post_visitor
.enter_visit
(self)
1049 redef class ABlockExpr
1050 redef fun accept_typing
(v
)
1052 for e
in self.n_expr
do v
.visit_stmt
(e
)
1053 self.is_typed
= true
1056 # The type of a blockexpr is the one of the last expression (or null if empty)
1059 if self.n_expr
.is_empty
then return null
1060 return self.n_expr
.last
.mtype
1064 redef class AVardeclExpr
1065 redef fun accept_typing
(v
)
1067 var variable
= self.variable
1068 if variable
== null then return # Skip error
1070 var ntype
= self.n_type
1071 var mtype
: nullable MType
1072 if ntype
== null then
1075 mtype
= v
.resolve_mtype
(ntype
)
1076 if mtype
== null then return # Skip error
1079 var nexpr
= self.n_expr
1080 if nexpr
!= null then
1081 if mtype
!= null then
1082 var etype
= v
.visit_expr_subtype
(nexpr
, mtype
)
1083 if etype
== mtype
then
1084 assert ntype
!= null
1085 v
.modelbuilder
.advice
(ntype
, "useless-type", "Warning: useless type definition for variable `{variable.name}`")
1088 mtype
= v
.visit_expr
(nexpr
)
1089 if mtype
== null then return # Skip error
1093 var decltype
= mtype
1094 if mtype
== null or mtype
isa MNullType then
1095 var objclass
= v
.get_mclass
(self, "Object")
1096 if objclass
== null then return # skip error
1097 decltype
= objclass
.mclass_type
.as_nullable
1098 if mtype
== null then mtype
= decltype
1101 variable
.declared_type
= decltype
1102 v
.set_variable
(self, variable
, mtype
)
1104 #debug("var {variable}: {mtype}")
1107 self.is_typed
= true
1111 redef class AVarExpr
1112 redef fun its_variable
do return self.variable
1113 redef fun accept_typing
(v
)
1115 var variable
= self.variable
1116 if variable
== null then return # Skip error
1118 var mtype
= v
.get_variable
(self, variable
)
1119 if mtype
!= null then
1120 #debug("{variable} is {mtype}")
1122 #debug("{variable} is untyped")
1129 redef class AVarAssignExpr
1130 redef fun accept_typing
(v
)
1132 var variable
= self.variable
1133 assert variable
!= null
1135 var mtype
= v
.visit_expr_subtype
(n_value
, variable
.declared_type
)
1137 v
.set_variable
(self, variable
, mtype
)
1139 self.is_typed
= true
1143 redef class AReassignFormExpr
1144 # The method designed by the reassign operator.
1145 var reassign_callsite
: nullable CallSite
1147 var read_type
: nullable MType = null
1149 # Determine the `reassign_property`
1150 # `readtype` is the type of the reading of the left value.
1151 # `writetype` is the type of the writing of the left value.
1152 # (Because of `ACallReassignExpr`, both can be different.
1153 # Return the static type of the value to store.
1154 private fun resolve_reassignment
(v
: TypeVisitor, readtype
, writetype
: MType): nullable MType
1156 var reassign_name
= self.n_assign_op
.operator
1158 self.read_type
= readtype
1160 var callsite
= v
.build_callsite_by_name
(self.n_assign_op
, readtype
, reassign_name
, false)
1161 if callsite
== null then return null # Skip error
1162 self.reassign_callsite
= callsite
1164 var msignature
= callsite
.msignature
1165 var rettype
= msignature
.return_mtype
1166 assert msignature
.arity
== 1 and rettype
!= null
1168 var value_type
= v
.visit_expr_subtype
(self.n_value
, msignature
.mparameters
.first
.mtype
)
1169 if value_type
== null then return null # Skip error
1171 v
.check_subtype
(self, rettype
, writetype
, false)
1176 redef class AVarReassignExpr
1177 redef fun accept_typing
(v
)
1179 var variable
= self.variable
1180 assert variable
!= null
1182 var readtype
= v
.get_variable
(self, variable
)
1183 if readtype
== null then return
1185 read_type
= readtype
1187 var writetype
= variable
.declared_type
1188 if writetype
== null then return
1190 var rettype
= self.resolve_reassignment
(v
, readtype
, writetype
)
1192 v
.set_variable
(self, variable
, rettype
)
1194 self.is_typed
= rettype
!= null
1198 redef class AContinueExpr
1199 redef fun accept_typing
(v
)
1201 var nexpr
= self.n_expr
1202 if nexpr
!= null then
1205 self.is_typed
= true
1209 redef class ABreakExpr
1210 redef fun accept_typing
(v
)
1212 var nexpr
= self.n_expr
1213 if nexpr
!= null then
1216 self.is_typed
= true
1220 redef class AReturnExpr
1221 redef fun accept_typing
(v
)
1223 var nexpr
= self.n_expr
1225 var mpropdef
= v
.mpropdef
1226 if mpropdef
isa MMethodDef then
1227 ret_type
= mpropdef
.msignature
.return_mtype
1228 else if mpropdef
isa MAttributeDef then
1229 ret_type
= mpropdef
.static_mtype
1233 if nexpr
!= null then
1234 if ret_type
!= null then
1235 v
.visit_expr_subtype
(nexpr
, ret_type
)
1238 v
.error
(nexpr
, "Error: `return` with value in a procedure.")
1241 else if ret_type
!= null then
1242 v
.error
(self, "Error: `return` without value in a function.")
1245 self.is_typed
= true
1249 redef class AAbortExpr
1250 redef fun accept_typing
(v
)
1252 self.is_typed
= true
1257 redef fun accept_typing
(v
)
1259 v
.visit_expr_bool
(n_expr
)
1261 v
.visit_stmt
(n_then
)
1262 v
.visit_stmt
(n_else
)
1264 self.is_typed
= true
1266 if n_then
!= null and n_else
== null then
1267 self.mtype
= n_then
.mtype
1272 redef class AIfexprExpr
1273 redef fun accept_typing
(v
)
1275 v
.visit_expr_bool
(n_expr
)
1277 var t1
= v
.visit_expr
(n_then
)
1278 var t2
= v
.visit_expr
(n_else
)
1280 if t1
== null or t2
== null then
1284 var t
= v
.merge_types
(self, [t1
, t2
])
1286 v
.error
(self, "Type Error: ambiguous type `{t1}` vs `{t2}`.")
1293 redef fun accept_typing
(v
)
1295 v
.visit_stmt
(n_block
)
1296 v
.visit_stmt
(n_catch
)
1297 self.is_typed
= true
1301 redef class AWhileExpr
1302 redef fun accept_typing
(v
)
1305 v
.visit_expr_bool
(n_expr
)
1306 v
.visit_stmt
(n_block
)
1307 self.is_typed
= true
1311 redef class ALoopExpr
1312 redef fun accept_typing
(v
)
1315 v
.visit_stmt
(n_block
)
1316 self.is_typed
= true
1320 redef class AForExpr
1321 redef fun accept_typing
(v
)
1325 for g
in n_groups
do
1326 var mtype
= v
.visit_expr
(g
.n_expr
)
1327 if mtype
== null then return
1328 g
.do_type_iterator
(v
, mtype
)
1329 if g
.is_broken
then is_broken
= true
1332 v
.visit_stmt
(n_block
)
1334 self.mtype
= n_block
.mtype
1335 self.is_typed
= true
1339 redef class AForGroup
1340 var coltype
: nullable MClassType
1342 var method_iterator
: nullable CallSite
1343 var method_is_ok
: nullable CallSite
1344 var method_item
: nullable CallSite
1345 var method_next
: nullable CallSite
1346 var method_key
: nullable CallSite
1347 var method_finish
: nullable CallSite
1349 var method_lt
: nullable CallSite
1350 var method_successor
: nullable CallSite
1352 private fun do_type_iterator
(v
: TypeVisitor, mtype
: MType)
1354 if mtype
isa MNullType then
1355 v
.error
(self, "Type Error: `for` cannot iterate over `null`.")
1360 var objcla
= v
.get_mclass
(self, "Object")
1361 if objcla
== null then return
1363 # check iterator method
1364 var itdef
= v
.build_callsite_by_name
(self, mtype
, "iterator", n_expr
isa ASelfExpr)
1365 if itdef
== null then
1366 v
.error
(self, "Type Error: `for` expects a type providing an `iterator` method, got `{mtype}`.")
1369 self.method_iterator
= itdef
1371 # check that iterator return something
1372 var ittype
= itdef
.msignature
.return_mtype
1373 if ittype
== null then
1374 v
.error
(self, "Type Error: `for` expects the method `iterator` to return an `Iterator` or `MapIterator` type.")
1379 var colit_cla
= v
.try_get_mclass
(self, "Iterator")
1380 var mapit_cla
= v
.try_get_mclass
(self, "MapIterator")
1384 if colit_cla
!= null and v
.is_subtype
(ittype
, colit_cla
.get_mtype
([objcla
.mclass_type
.as_nullable
])) then
1386 var coltype
= ittype
.supertype_to
(v
.mmodule
, v
.anchor
, colit_cla
)
1387 var variables
= self.variables
1388 if variables
.length
!= 1 then
1389 v
.error
(self, "Type Error: `for` expects only one variable when using `Iterator`.")
1391 variables
.first
.declared_type
= coltype
.arguments
.first
1396 if mapit_cla
!= null and v
.is_subtype
(ittype
, mapit_cla
.get_mtype
([objcla
.mclass_type
.as_nullable
, objcla
.mclass_type
.as_nullable
])) then
1398 var coltype
= ittype
.supertype_to
(v
.mmodule
, v
.anchor
, mapit_cla
)
1399 var variables
= self.variables
1400 if variables
.length
!= 2 then
1401 v
.error
(self, "Type Error: `for` expects two variables when using `MapIterator`.")
1403 variables
[0].declared_type
= coltype
.arguments
[0]
1404 variables
[1].declared_type
= coltype
.arguments
[1]
1409 if not is_col
and not is_map
then
1410 v
.error
(self, "Type Error: `for` expects the method `iterator` to return an `Iterator` or `MapIterator` type.")
1414 # anchor formal and virtual types
1415 if mtype
.need_anchor
then mtype
= v
.anchor_to
(mtype
)
1417 mtype
= mtype
.undecorate
1418 self.coltype
= mtype
.as(MClassType)
1420 # get methods is_ok, next, item
1421 var ikdef
= v
.build_callsite_by_name
(self, ittype
, "is_ok", false)
1422 if ikdef
== null then
1423 v
.error
(self, "Type Error: `for` expects a method `is_ok` in type `{ittype}`.")
1426 self.method_is_ok
= ikdef
1428 var itemdef
= v
.build_callsite_by_name
(self, ittype
, "item", false)
1429 if itemdef
== null then
1430 v
.error
(self, "Type Error: `for` expects a method `item` in type `{ittype}`.")
1433 self.method_item
= itemdef
1435 var nextdef
= v
.build_callsite_by_name
(self, ittype
, "next", false)
1436 if nextdef
== null then
1437 v
.error
(self, "Type Error: `for` expects a method `next` in type {ittype}.")
1440 self.method_next
= nextdef
1442 self.method_finish
= v
.try_build_callsite_by_name
(self, ittype
, "finish", false)
1445 var keydef
= v
.build_callsite_by_name
(self, ittype
, "key", false)
1446 if keydef
== null then
1447 v
.error
(self, "Type Error: `for` expects a method `key` in type `{ittype}`.")
1450 self.method_key
= keydef
1453 if self.variables
.length
== 1 and n_expr
isa ARangeExpr then
1454 var variable
= variables
.first
1455 var vtype
= variable
.declared_type
.as(not null)
1457 if n_expr
isa AOrangeExpr then
1458 self.method_lt
= v
.build_callsite_by_name
(self, vtype
, "<", false)
1460 self.method_lt
= v
.build_callsite_by_name
(self, vtype
, "<=", false)
1463 self.method_successor
= v
.build_callsite_by_name
(self, vtype
, "successor", false)
1468 redef class AWithExpr
1469 var method_start
: nullable CallSite
1470 var method_finish
: nullable CallSite
1472 redef fun accept_typing
(v
: TypeVisitor)
1474 var mtype
= v
.visit_expr
(n_expr
)
1475 if mtype
== null then return
1477 method_start
= v
.build_callsite_by_name
(self, mtype
, "start", n_expr
isa ASelfExpr)
1478 method_finish
= v
.build_callsite_by_name
(self, mtype
, "finish", n_expr
isa ASelfExpr)
1480 v
.visit_stmt
(n_block
)
1481 self.mtype
= n_block
.mtype
1482 self.is_typed
= true
1486 redef class AAssertExpr
1487 redef fun accept_typing
(v
)
1489 v
.visit_expr_bool
(n_expr
)
1491 v
.visit_stmt
(n_else
)
1492 self.is_typed
= true
1497 redef fun accept_typing
(v
)
1499 v
.visit_expr_bool
(n_expr
)
1500 v
.visit_expr_bool
(n_expr2
)
1501 self.mtype
= v
.type_bool
(self)
1505 redef class AImpliesExpr
1506 redef fun accept_typing
(v
)
1508 v
.visit_expr_bool
(n_expr
)
1509 v
.visit_expr_bool
(n_expr2
)
1510 self.mtype
= v
.type_bool
(self)
1514 redef class AAndExpr
1515 redef fun accept_typing
(v
)
1517 v
.visit_expr_bool
(n_expr
)
1518 v
.visit_expr_bool
(n_expr2
)
1519 self.mtype
= v
.type_bool
(self)
1523 redef class ANotExpr
1524 redef fun accept_typing
(v
)
1526 v
.visit_expr_bool
(n_expr
)
1527 self.mtype
= v
.type_bool
(self)
1531 redef class AOrElseExpr
1532 redef fun accept_typing
(v
)
1534 var t1
= v
.visit_expr
(n_expr
)
1535 var t2
= v
.visit_expr
(n_expr2
)
1537 if t1
== null or t2
== null then
1541 if t1
isa MNullType then
1544 else if v
.can_be_null
(t1
) then
1548 var t
= v
.merge_types
(self, [t1
, t2
])
1550 var c
= v
.get_mclass
(self, "Object")
1551 if c
== null then return # forward error
1553 if v
.can_be_null
(t2
) then
1556 #v.error(self, "Type Error: ambiguous type {t1} vs {t2}")
1561 redef fun accept_post_typing
(v
)
1563 var t1
= n_expr
.mtype
1567 v
.check_can_be_null
(n_expr
, t1
)
1572 redef class ATrueExpr
1573 redef fun accept_typing
(v
)
1575 self.mtype
= v
.type_bool
(self)
1579 redef class AFalseExpr
1580 redef fun accept_typing
(v
)
1582 self.mtype
= v
.type_bool
(self)
1586 redef class AIntegerExpr
1587 redef fun accept_typing
(v
)
1589 var mclass
: nullable MClass = null
1590 if value
isa Byte then
1591 mclass
= v
.get_mclass
(self, "Byte")
1592 else if value
isa Int then
1593 mclass
= v
.get_mclass
(self, "Int")
1594 else if value
isa Int8 then
1595 mclass
= v
.get_mclass
(self, "Int8")
1596 else if value
isa Int16 then
1597 mclass
= v
.get_mclass
(self, "Int16")
1598 else if value
isa UInt16 then
1599 mclass
= v
.get_mclass
(self, "UInt16")
1600 else if value
isa Int32 then
1601 mclass
= v
.get_mclass
(self, "Int32")
1602 else if value
isa UInt32 then
1603 mclass
= v
.get_mclass
(self, "UInt32")
1605 if mclass
== null then return # Forward error
1606 self.mtype
= mclass
.mclass_type
1610 redef class AFloatExpr
1611 redef fun accept_typing
(v
)
1613 var mclass
= v
.get_mclass
(self, "Float")
1614 if mclass
== null then return # Forward error
1615 self.mtype
= mclass
.mclass_type
1619 redef class ACharExpr
1620 redef fun accept_typing
(v
) do
1621 var mclass
: nullable MClass = null
1622 if is_code_point
then
1623 mclass
= v
.get_mclass
(self, "Int")
1625 mclass
= v
.get_mclass
(self, "Char")
1627 if mclass
== null then return # Forward error
1628 self.mtype
= mclass
.mclass_type
1632 redef class AugmentedStringFormExpr
1635 # Text::to_re, used for prefix `re`
1636 var to_re
: nullable CallSite = null
1637 # Regex::ignore_case, used for suffix `i` on `re`
1638 var ignore_case
: nullable CallSite = null
1639 # Regex::newline, used for suffix `m` on `re`
1640 var newline
: nullable CallSite = null
1641 # Regex::extended, used for suffix `b` on `re`
1642 var extended
: nullable CallSite = null
1643 # CString::to_bytes_with_copy, used for prefix `b`
1644 var to_bytes_with_copy
: nullable CallSite = null
1646 redef fun accept_typing
(v
) do
1647 var mclass
= v
.get_mclass
(self, "String")
1648 if mclass
== null then return # Forward error
1649 if is_bytestring
then
1650 to_bytes_with_copy
= v
.build_callsite_by_name
(self, v
.mmodule
.c_string_type
, "to_bytes_with_copy", false)
1651 mclass
= v
.get_mclass
(self, "Bytes")
1653 to_re
= v
.build_callsite_by_name
(self, mclass
.mclass_type
, "to_re", false)
1654 for i
in suffix
.chars
do
1655 mclass
= v
.get_mclass
(self, "Regex")
1656 if mclass
== null then
1657 v
.error
(self, "Error: `Regex` class unknown")
1662 service
= "ignore_case="
1663 ignore_case
= v
.build_callsite_by_name
(self, mclass
.mclass_type
, service
, false)
1664 else if i
== 'm' then
1665 service
= "newline="
1666 newline
= v
.build_callsite_by_name
(self, mclass
.mclass_type
, service
, false)
1667 else if i
== 'b' then
1668 service
= "extended="
1669 extended
= v
.build_callsite_by_name
(self, mclass
.mclass_type
, service
, false)
1671 v
.error
(self, "Type Error: Unrecognized suffix {i} in prefixed Regex")
1676 if mclass
== null then return # Forward error
1677 mtype
= mclass
.mclass_type
1681 redef class ASuperstringExpr
1682 redef fun accept_typing
(v
)
1685 var objclass
= v
.get_mclass
(self, "Object")
1686 if objclass
== null then return # Forward error
1687 var objtype
= objclass
.mclass_type
1688 for nexpr
in self.n_exprs
do
1689 v
.visit_expr_subtype
(nexpr
, objtype
)
1694 redef class AArrayExpr
1695 # The `with_capacity` method on Array
1696 var with_capacity_callsite
: nullable CallSite
1698 # The `push` method on arrays
1699 var push_callsite
: nullable CallSite
1701 # The element of each type
1702 var element_mtype
: nullable MType
1704 # Set that `self` is a part of comprehension array `na`
1705 # If `self` is a `for`, or a `if`, then `set_comprehension` is recursively applied.
1706 private fun set_comprehension
(n
: nullable AExpr)
1710 else if n
isa AForExpr then
1711 set_comprehension
(n
.n_block
)
1712 else if n
isa AIfExpr then
1713 set_comprehension
(n
.n_then
)
1714 set_comprehension
(n
.n_else
)
1717 n
.comprehension
= self
1720 redef fun accept_typing
(v
)
1722 var mtype
: nullable MType = null
1723 var ntype
= self.n_type
1724 if ntype
!= null then
1725 mtype
= v
.resolve_mtype
(ntype
)
1726 if mtype
== null then return # Skip error
1728 var mtypes
= new Array[nullable MType]
1730 for e
in self.n_exprs
do
1731 var t
= v
.visit_expr
(e
)
1735 set_comprehension
(e
)
1736 if mtype
!= null then
1737 if v
.check_subtype
(e
, t
, mtype
, false) == null then return # Forward error
1738 if t
== mtype
then useless
= true
1743 if mtype
== null then
1744 # Ensure monotony for type adaptation on loops
1745 if self.element_mtype
!= null then mtypes
.add
self.element_mtype
1746 mtype
= v
.merge_types
(self, mtypes
)
1748 if mtype
== null or mtype
isa MNullType then
1749 v
.error
(self, "Type Error: ambiguous array type {mtypes.join(" ")}")
1753 assert ntype
!= null
1754 v
.modelbuilder
.warning
(ntype
, "useless-type", "Warning: useless type declaration `{mtype}` in literal Array since it can be inferred from the elements type.")
1757 self.element_mtype
= mtype
1759 var mclass
= v
.get_mclass
(self, "Array")
1760 if mclass
== null then return # Forward error
1761 var array_mtype
= mclass
.get_mtype
([mtype
])
1763 with_capacity_callsite
= v
.build_callsite_by_name
(self, array_mtype
, "with_capacity", false)
1764 push_callsite
= v
.build_callsite_by_name
(self, array_mtype
, "push", false)
1766 self.mtype
= array_mtype
1770 redef class ARangeExpr
1771 var init_callsite
: nullable CallSite
1773 redef fun accept_typing
(v
)
1775 var discrete_class
= v
.get_mclass
(self, "Discrete")
1776 if discrete_class
== null then return # Forward error
1777 var discrete_type
= discrete_class
.intro
.bound_mtype
1778 var t1
= v
.visit_expr_subtype
(self.n_expr
, discrete_type
)
1779 var t2
= v
.visit_expr_subtype
(self.n_expr2
, discrete_type
)
1780 if t1
== null or t2
== null then return
1781 var mclass
= v
.get_mclass
(self, "Range")
1782 if mclass
== null then return # Forward error
1784 if v
.is_subtype
(t1
, t2
) then
1785 mtype
= mclass
.get_mtype
([t2
])
1786 else if v
.is_subtype
(t2
, t1
) then
1787 mtype
= mclass
.get_mtype
([t1
])
1789 v
.error
(self, "Type Error: cannot create range: `{t1}` vs `{t2}`.")
1795 # get the constructor
1797 if self isa ACrangeExpr then
1798 callsite
= v
.build_callsite_by_name
(self, mtype
, "defaultinit", false)
1799 else if self isa AOrangeExpr then
1800 callsite
= v
.build_callsite_by_name
(self, mtype
, "without_last", false)
1804 init_callsite
= callsite
1808 redef class ANullExpr
1809 redef fun accept_typing
(v
)
1811 self.mtype
= v
.mmodule
.model
.null_type
1815 redef class AIsaExpr
1816 # The static type to cast to.
1817 # (different from the static type of the expression that is `Bool`).
1818 var cast_type
: nullable MType
1819 redef fun accept_typing
(v
)
1821 v
.visit_expr
(n_expr
)
1823 var mtype
= v
.resolve_mtype
(n_type
)
1825 self.cast_type
= mtype
1827 var variable
= self.n_expr
.its_variable
1828 if variable
!= null then
1829 var orig
= self.n_expr
.mtype
1830 #var from = if orig != null then orig.to_s else "invalid"
1831 #var to = if mtype != null then mtype.to_s else "invalid"
1832 #debug("adapt {variable}: {from} -> {to}")
1834 var thentype
= v
.intersect_types
(self, orig
, mtype
)
1835 if thentype
!= orig
then
1836 self.after_flow_context
.when_true
.set_var
(v
, variable
, thentype
)
1837 #debug "{variable}:{orig or else "?"} isa {mtype or else "?"} -> then {thentype or else "?"}"
1840 var elsetype
= v
.diff_types
(self, orig
, mtype
)
1841 if elsetype
!= orig
then
1842 self.after_flow_context
.when_false
.set_var
(v
, variable
, elsetype
)
1843 #debug "{variable}:{orig or else "?"} isa {mtype or else "?"} -> else {elsetype or else "?"}"
1847 self.mtype
= v
.type_bool
(self)
1850 redef fun accept_post_typing
(v
)
1852 v
.check_expr_cast
(self, self.n_expr
, self.n_type
)
1855 redef fun dump_info
(v
) do
1857 var mtype
= self.cast_type
1858 if mtype
!= null then
1859 res
+= v
.yellow
(".as({mtype})")
1866 redef class AAsCastExpr
1867 redef fun accept_typing
(v
)
1869 v
.visit_expr
(n_expr
)
1871 self.mtype
= v
.resolve_mtype
(n_type
)
1874 redef fun accept_post_typing
(v
)
1876 v
.check_expr_cast
(self, self.n_expr
, self.n_type
)
1880 redef class AAsNotnullExpr
1881 redef fun accept_typing
(v
)
1883 var mtype
= v
.visit_expr
(self.n_expr
)
1884 if mtype
== null then return # Forward error
1886 if mtype
isa MNullType then
1887 v
.error
(self, "Type Error: `as(not null)` on `null`.")
1891 if v
.can_be_null
(mtype
) then
1892 mtype
= mtype
.as_notnull
1898 redef fun accept_post_typing
(v
)
1900 var mtype
= n_expr
.mtype
1901 if mtype
== null then return
1902 v
.check_can_be_null
(n_expr
, mtype
)
1906 redef class AParExpr
1907 redef fun accept_typing
(v
)
1909 self.mtype
= v
.visit_expr
(self.n_expr
)
1913 redef class AOnceExpr
1914 redef fun accept_typing
(v
)
1916 self.mtype
= v
.visit_expr
(self.n_expr
)
1920 redef class ASelfExpr
1921 redef var its_variable
: nullable Variable
1922 redef fun accept_typing
(v
)
1924 if v
.is_toplevel_context
and not self isa AImplicitSelfExpr then
1925 v
.error
(self, "Error: `self` cannot be used in top-level method.")
1927 var variable
= v
.selfvariable
1928 self.its_variable
= variable
1929 self.mtype
= v
.get_variable
(self, variable
)
1933 redef class AImplicitSelfExpr
1934 # Is the implicit receiver `sys`?
1936 # By default, the implicit receiver is `self`.
1937 # But when there is not method for `self`, `sys` is used as a fall-back.
1938 # Is this case this flag is set to `true`.
1942 ## MESSAGE SENDING AND PROPERTY
1944 redef class ASendExpr
1945 # The property invoked by the send.
1946 var callsite
: nullable CallSite
1948 # Is self a safe call (with `x?.foo`)?
1949 # If so and the receiver is null, then the arguments won't be evaluated
1950 # and the call skipped (replaced with null).
1951 var is_safe
: Bool = false
1953 redef fun bad_expr_message
(child
)
1955 if child
== self.n_expr
then
1956 return "to be the receiver of `{self.property_name}`"
1961 redef fun accept_typing
(v
)
1963 var nrecv
= self.n_expr
1964 var recvtype
= v
.visit_expr
(nrecv
)
1966 if nrecv
isa ASafeExpr then
1967 # Has the receiver the form `x?.foo`?
1968 # For parsing "reasons" the `?` is in the receiver node, not the call node.
1972 var name
= self.property_name
1973 var node
= self.property_node
1975 if recvtype
== null then return # Forward error
1978 var unsafe_type
= v
.anchor_to
(recvtype
)
1979 var mproperty
= v
.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
1980 if mproperty
== null and nrecv
isa AImplicitSelfExpr then
1981 # Special fall-back search in `sys` when noting found in the implicit receiver.
1982 var sysclass
= v
.try_get_mclass
(node
, "Sys")
1983 if sysclass
!= null then
1984 var systype
= sysclass
.mclass_type
1985 mproperty
= v
.try_get_mproperty_by_name2
(node
, systype
, name
)
1986 if mproperty
!= null then
1987 callsite
= v
.build_callsite_by_name
(node
, systype
, name
, false)
1988 if callsite
== null then return # Forward error
1989 # Update information, we are looking at `sys` now, not `self`
1991 nrecv
.its_variable
= null
1992 nrecv
.mtype
= systype
1997 if callsite
== null then
1998 # If still nothing, just exit
1999 callsite
= v
.build_callsite_by_name
(node
, recvtype
, name
, nrecv
isa ASelfExpr)
2000 if callsite
== null then return
2003 self.callsite
= callsite
2004 var msignature
= callsite
.msignature
2006 var args
= compute_raw_arguments
2008 if not self isa ACallrefExpr then
2009 callsite
.check_signature
(v
, node
, args
)
2012 if callsite
.mproperty
.is_init
then
2013 var vmpropdef
= v
.mpropdef
2014 if not (vmpropdef
isa MMethodDef and vmpropdef
.mproperty
.is_init
) then
2015 v
.error
(node
, "Error: an `init` can only be called from another `init`.")
2017 if vmpropdef
isa MMethodDef and vmpropdef
.mproperty
.is_root_init
and not callsite
.mproperty
.is_root_init
then
2018 v
.error
(node
, "Error: `{vmpropdef}` cannot call a factory `{callsite.mproperty}`.")
2022 var ret
= msignature
.return_mtype
2025 # A safe receiver makes that the call is not executed and returns null
2026 ret
= ret
.as_nullable
2030 self.is_typed
= true
2034 # The name of the property
2035 # Each subclass simply provide the correct name.
2036 private fun property_name
: String is abstract
2038 # The node identifying the name (id, operator, etc) for messages.
2040 # Is `self` by default
2041 private fun property_node
: ANode do return self
2043 # An array of all arguments (excluding self)
2044 fun raw_arguments
: Array[AExpr] do return compute_raw_arguments
2046 private fun compute_raw_arguments
: Array[AExpr] is abstract
2048 redef fun dump_info
(v
) do
2050 var callsite
= self.callsite
2051 if callsite
!= null then
2052 res
+= v
.yellow
(" call="+callsite
.dump_info
(v
))
2058 redef class ABinopExpr
2059 redef fun compute_raw_arguments
do return [n_expr2
]
2060 redef fun property_name
do return operator
2061 redef fun property_node
do return n_op
2064 redef class AEqFormExpr
2065 redef fun accept_typing
(v
)
2071 redef fun accept_post_typing
(v
)
2073 var mtype
= n_expr
.mtype
2074 var mtype2
= n_expr2
.mtype
2076 if mtype
== null or mtype2
== null then return
2078 if mtype
== v
.type_bool
(self) and (n_expr2
isa AFalseExpr or n_expr2
isa ATrueExpr) then
2079 v
.modelbuilder
.warning
(self, "useless-truism", "Warning: useless comparison to a Bool literal.")
2082 if not mtype2
isa MNullType then return
2084 v
.check_can_be_null
(n_expr
, mtype
)
2088 redef class AUnaryopExpr
2089 redef fun property_name
do return "unary {operator}"
2090 redef fun compute_raw_arguments
do return new Array[AExpr]
2093 redef class ACallExpr
2094 redef fun property_name
do return n_qid
.n_id
.text
2095 redef fun property_node
do return n_qid
2096 redef fun compute_raw_arguments
do return n_args
.to_a
2099 redef class ACallAssignExpr
2100 redef fun property_name
do return n_qid
.n_id
.text
+ "="
2101 redef fun property_node
do return n_qid
2102 redef fun compute_raw_arguments
2104 var res
= n_args
.to_a
2110 redef class ABraExpr
2111 redef fun property_name
do return "[]"
2112 redef fun compute_raw_arguments
do return n_args
.to_a
2115 redef class ABraAssignExpr
2116 redef fun property_name
do return "[]="
2117 redef fun compute_raw_arguments
2119 var res
= n_args
.to_a
2125 redef class ASendReassignFormExpr
2126 # The property invoked for the writing
2127 var write_callsite
: nullable CallSite
2129 redef fun accept_typing
(v
)
2131 var recvtype
= v
.visit_expr
(self.n_expr
)
2132 var name
= self.property_name
2133 var node
= self.property_node
2135 if recvtype
== null then return # Forward error
2137 var for_self
= self.n_expr
isa ASelfExpr
2138 var callsite
= v
.build_callsite_by_name
(node
, recvtype
, name
, for_self
)
2140 if callsite
== null then return
2141 self.callsite
= callsite
2143 var args
= compute_raw_arguments
2145 callsite
.check_signature
(v
, node
, args
)
2147 var readtype
= callsite
.msignature
.return_mtype
2148 if readtype
== null then
2149 v
.error
(node
, "Error: `{name}` is not a function.")
2153 var wcallsite
= v
.build_callsite_by_name
(node
, recvtype
, name
+ "=", self.n_expr
isa ASelfExpr)
2154 if wcallsite
== null then return
2155 self.write_callsite
= wcallsite
2157 var wtype
= self.resolve_reassignment
(v
, readtype
, wcallsite
.msignature
.mparameters
.last
.mtype
)
2158 if wtype
== null then return
2160 args
= args
.to_a
# duplicate so raw_arguments keeps only the getter args
2161 args
.add
(self.n_value
)
2162 wcallsite
.check_signature
(v
, node
, args
)
2164 self.is_typed
= true
2168 redef class ACallReassignExpr
2169 redef fun property_name
do return n_qid
.n_id
.text
2170 redef fun property_node
do return n_qid
.n_id
2171 redef fun compute_raw_arguments
do return n_args
.to_a
2174 redef class ABraReassignExpr
2175 redef fun property_name
do return "[]"
2176 redef fun compute_raw_arguments
do return n_args
.to_a
2179 redef class AInitExpr
2180 redef fun property_name
do if n_args
.n_exprs
.is_empty
then return "init" else return "defaultinit"
2181 redef fun property_node
do return n_kwinit
2182 redef fun compute_raw_arguments
do return n_args
.to_a
2185 redef class ACallrefExpr
2186 redef fun property_name
do return n_qid
.n_id
.text
2187 redef fun property_node
do return n_qid
2188 redef fun compute_raw_arguments
do return n_args
.to_a
2190 redef fun accept_typing
(v
)
2192 super # do the job as if it was a real call
2193 var res
= callsite
.mproperty
2195 var msignature
= callsite
.mpropdef
.msignature
2196 var recv
= callsite
.recv
2197 assert msignature
!= null
2198 var arity
= msignature
.mparameters
.length
2200 var routine_type_name
= "ProcRef"
2201 if msignature
.return_mtype
!= null then
2202 routine_type_name
= "FunRef"
2205 var target_routine_class
= "{routine_type_name}{arity}"
2206 var routine_mclass
= v
.get_mclass
(self, target_routine_class
)
2208 if routine_mclass
== null then
2209 v
.error
(self, "Error: missing functional types, try `import functional`")
2213 var types_list
= new Array[MType]
2214 for param
in msignature
.mparameters
do
2215 if param
.is_vararg
then
2216 types_list
.push
(v
.mmodule
.array_type
(param
.mtype
))
2218 types_list
.push
(param
.mtype
)
2221 if msignature
.return_mtype
!= null then
2222 types_list
.push
(msignature
.return_mtype
.as(not null))
2225 # Why we need an anchor :
2229 # def toto(x: E) do print "{x}"
2232 # var a = new A[Int]
2233 # var f = &a.toto # without anchor : ProcRef1[E]
2234 # # with anchor : ProcRef[Int]
2236 # However, we can only anchor if we can resolve every formal
2237 # parameter, here's an example where we can't.
2240 # fun bar: A[E] do return self
2241 # fun foo: Fun0[A[E]] do return &bar # here we can't anchor
2243 # var f1 = a1.foo # when this expression will be evaluated,
2244 # # `a1` will anchor `&bar` returned by `foo`.
2247 var routine_type
= routine_mclass
.get_mtype
(types_list
)
2248 if not recv
.need_anchor
then
2249 routine_type
= routine_type
.anchor_to
(v
.mmodule
, recv
.as(MClassType))
2252 self.mtype
= routine_type
2257 fun to_a
: Array[AExpr] do return self.n_exprs
.to_a
2262 redef class ASuperExpr
2263 # The method to call if the super is in fact a 'super init call'
2264 # Note: if the super is a normal call-next-method, then this attribute is null
2265 var callsite
: nullable CallSite
2267 # The method to call is the super is a standard `call-next-method` super-call
2268 # Note: if the super is a special super-init-call, then this attribute is null
2269 var mpropdef
: nullable MMethodDef
2271 redef fun accept_typing
(v
)
2273 var anchor
= v
.anchor
2274 var recvtype
= v
.get_variable
(self, v
.selfvariable
)
2275 assert recvtype
!= null
2276 var mproperty
= v
.mpropdef
.mproperty
2277 if not mproperty
isa MMethod then
2278 v
.error
(self, "Error: `super` only usable in a `method`.")
2281 var superprops
= mproperty
.lookup_super_definitions
(v
.mmodule
, anchor
)
2282 if superprops
.length
== 0 then
2283 if mproperty
.is_init
and v
.mpropdef
.is_intro
then
2284 process_superinit
(v
)
2287 v
.error
(self, "Error: no super method to call for `{mproperty}`.")
2290 # FIXME: covariance of return type in linear extension?
2291 var superprop
= superprops
.first
2293 var msignature
= superprop
.msignature
.as(not null)
2294 msignature
= v
.resolve_for
(msignature
, recvtype
, true).as(MSignature)
2295 var args
= self.n_args
.to_a
2296 if args
.length
> 0 then
2297 signaturemap
= v
.check_signature
(self, args
, mproperty
, msignature
)
2299 self.mtype
= msignature
.return_mtype
2300 self.is_typed
= true
2301 v
.mpropdef
.has_supercall
= true
2302 mpropdef
= v
.mpropdef
.as(MMethodDef)
2305 # The mapping used on the call to associate arguments to parameters.
2306 # If null then no specific association is required.
2307 var signaturemap
: nullable SignatureMap
2309 private fun process_superinit
(v
: TypeVisitor)
2311 var anchor
= v
.anchor
2312 var recvtype
= v
.get_variable
(self, v
.selfvariable
)
2313 assert recvtype
!= null
2314 var mpropdef
= v
.mpropdef
2315 assert mpropdef
isa MMethodDef
2316 var mproperty
= mpropdef
.mproperty
2317 var superprop
: nullable MMethodDef = null
2318 for msupertype
in mpropdef
.mclassdef
.supertypes
do
2319 msupertype
= msupertype
.anchor_to
(v
.mmodule
, anchor
)
2320 var errcount
= v
.modelbuilder
.toolcontext
.error_count
2321 var candidate
= v
.try_get_mproperty_by_name2
(self, msupertype
, mproperty
.name
).as(nullable MMethod)
2322 if candidate
== null then
2323 if v
.modelbuilder
.toolcontext
.error_count
> errcount
then return # Forward error
2324 continue # Try next super-class
2326 if superprop
!= null and candidate
.is_root_init
then
2329 if superprop
!= null and superprop
.mproperty
!= candidate
and not superprop
.mproperty
.is_root_init
then
2330 v
.error
(self, "Error: conflicting super constructor to call for `{mproperty}`: `{candidate.full_name}`, `{superprop.mproperty.full_name}`")
2333 var candidatedefs
= candidate
.lookup_definitions
(v
.mmodule
, anchor
)
2334 if superprop
!= null and superprop
.mproperty
== candidate
then
2335 if superprop
== candidatedefs
.first
then continue
2336 candidatedefs
.add
(superprop
)
2338 if candidatedefs
.length
> 1 then
2339 v
.error
(self, "Error: conflicting property definitions for property `{mproperty}` in `{recvtype}`: {candidatedefs.join(", ")}")
2342 superprop
= candidatedefs
.first
2344 if superprop
== null then
2345 v
.error
(self, "Error: no super method to call for `{mproperty}`.")
2349 var msignature
= superprop
.msignature
.as(not null)
2350 msignature
= v
.resolve_for
(msignature
, recvtype
, true).as(MSignature)
2352 var callsite
= new CallSite(hot_location
, recvtype
, v
.mmodule
, v
.anchor
, true, superprop
.mproperty
, superprop
, msignature
, false)
2353 self.callsite
= callsite
2355 var args
= self.n_args
.to_a
2356 if args
.length
> 0 then
2357 callsite
.check_signature
(v
, self, args
)
2359 # Check there is at least enough parameters
2360 if mpropdef
.msignature
.arity
< msignature
.arity
then
2361 v
.error
(self, "Error: not enough implicit arguments to pass. Got `{mpropdef.msignature.arity}`, expected at least `{msignature.arity}`. Signature is `{msignature}`.")
2364 # Check that each needed parameter is conform
2366 for sp
in msignature
.mparameters
do
2367 var p
= mpropdef
.msignature
.mparameters
[i
]
2368 if not v
.is_subtype
(p
.mtype
, sp
.mtype
) then
2369 v
.error
(self, "Type Error: expected argument #{i} of type `{sp.mtype}`, got implicit argument `{p.name}` of type `{p.mtype}`. Signature is {msignature}")
2376 self.is_typed
= true
2379 redef fun dump_info
(v
) do
2381 var callsite
= self.callsite
2382 if callsite
!= null then
2383 res
+= v
.yellow
(" super-init="+callsite
.dump_info
(v
))
2385 var mpropdef
= self.mpropdef
2386 if mpropdef
!= null then
2387 res
+= v
.yellow
(" call-next-method="+mpropdef
.to_s
)
2395 redef class ANewExpr
2396 # The constructor invoked by the new.
2397 var callsite
: nullable CallSite
2399 # The designated type
2400 var recvtype
: nullable MClassType
2402 redef fun accept_typing
(v
)
2404 var recvtype
= v
.resolve_mtype
(self.n_type
)
2405 if recvtype
== null then return
2407 if not recvtype
isa MClassType then
2408 if recvtype
isa MNullableType then
2409 v
.error
(self, "Type Error: cannot instantiate the nullable type `{recvtype}`.")
2411 else if recvtype
isa MFormalType then
2412 v
.error
(self, "Type Error: cannot instantiate the formal type `{recvtype}`.")
2415 v
.error
(self, "Type Error: cannot instantiate the type `{recvtype}`.")
2420 self.recvtype
= recvtype
2421 var kind
= recvtype
.mclass
.kind
2424 var nqid
= self.n_qid
2426 if nqid
!= null then
2427 name
= nqid
.n_id
.text
2433 if name
== "intern" then
2434 if kind
!= concrete_kind
then
2435 v
.error
(self, "Type Error: cannot instantiate {kind} {recvtype}.")
2438 if n_args
.n_exprs
.not_empty
then
2439 v
.error
(n_args
, "Type Error: the intern constructor expects no arguments.")
2443 self.mtype
= recvtype
2447 var callsite
= v
.build_callsite_by_name
(node
, recvtype
, name
, false)
2448 if callsite
== null then return
2450 if not callsite
.mproperty
.is_new
then
2451 if kind
!= concrete_kind
then
2452 v
.error
(self, "Type Error: cannot instantiate {kind} `{recvtype}`.")
2455 self.mtype
= recvtype
2457 self.mtype
= callsite
.msignature
.return_mtype
2458 assert self.mtype
!= null
2461 self.callsite
= callsite
2463 if not callsite
.mproperty
.is_init_for
(recvtype
.mclass
) then
2464 v
.error
(self, "Error: `{name}` is not a constructor.")
2468 var args
= n_args
.to_a
2469 callsite
.check_signature
(v
, node
, args
)
2472 redef fun dump_info
(v
) do
2474 var callsite
= self.callsite
2475 if callsite
!= null then
2476 res
+= v
.yellow
(" call="+callsite
.dump_info
(v
))
2484 redef class AAttrFormExpr
2485 # The attribute accessed.
2486 var mproperty
: nullable MAttribute
2488 # The static type of the attribute.
2489 var attr_type
: nullable MType
2491 # Resolve the attribute accessed.
2492 private fun resolve_property
(v
: TypeVisitor)
2494 var recvtype
= v
.visit_expr
(self.n_expr
)
2495 if recvtype
== null then return # Skip error
2496 var node
= self.n_id
2497 var name
= node
.text
2498 if recvtype
isa MNullType then
2499 v
.error
(node
, "Error: attribute `{name}` access on `null`.")
2503 var unsafe_type
= v
.anchor_to
(recvtype
)
2504 var mproperty
= v
.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
2505 if mproperty
== null then
2506 v
.modelbuilder
.error
(node
, "Error: attribute `{name}` does not exist in `{recvtype}`.")
2509 assert mproperty
isa MAttribute
2510 self.mproperty
= mproperty
2512 var mpropdefs
= mproperty
.lookup_definitions
(v
.mmodule
, unsafe_type
)
2513 assert mpropdefs
.length
== 1
2514 var mpropdef
= mpropdefs
.first
2515 var attr_type
= mpropdef
.static_mtype
2516 if attr_type
== null then return # skip error
2517 attr_type
= v
.resolve_for
(attr_type
, recvtype
, self.n_expr
isa ASelfExpr)
2518 self.attr_type
= attr_type
2521 redef fun dump_info
(v
) do
2523 var mproperty
= self.mproperty
2524 var attr_type
= self.attr_type
2525 if mproperty
!= null then
2526 res
+= v
.yellow
(" attr={mproperty}:{attr_type or else "BROKEN"}")
2532 redef class AAttrExpr
2533 redef fun accept_typing
(v
)
2535 self.resolve_property
(v
)
2536 self.mtype
= self.attr_type
2540 redef class AAttrAssignExpr
2541 redef fun accept_typing
(v
)
2543 self.resolve_property
(v
)
2544 var mtype
= self.attr_type
2546 v
.visit_expr_subtype
(self.n_value
, mtype
)
2547 self.is_typed
= mtype
!= null
2551 redef class AAttrReassignExpr
2552 redef fun accept_typing
(v
)
2554 self.resolve_property
(v
)
2555 var mtype
= self.attr_type
2556 if mtype
== null then return # Skip error
2558 var rettype
= self.resolve_reassignment
(v
, mtype
, mtype
)
2560 self.is_typed
= rettype
!= null
2564 redef class AIssetAttrExpr
2565 redef fun accept_typing
(v
)
2567 self.resolve_property
(v
)
2568 var mtype
= self.attr_type
2569 if mtype
== null then return # Skip error
2571 var recvtype
= self.n_expr
.mtype
.as(not null)
2572 var bound
= v
.resolve_for
(mtype
, recvtype
, false)
2573 if bound
isa MNullableType then
2574 v
.error
(n_id
, "Type Error: `isset` on a nullable attribute.")
2576 self.mtype
= v
.type_bool
(self)
2580 redef class ASafeExpr
2581 redef fun accept_typing
(v
)
2583 var mtype
= v
.visit_expr
(n_expr
)
2584 if mtype
== null then return # Skip error
2586 if mtype
isa MNullType then
2587 # While `null?.foo` is semantically well defined and should not execute `foo` and just return `null`,
2588 # currently `null.foo` is forbidden so it seems coherent to also forbid `null?.foo`
2589 v
.modelbuilder
.error
(self, "Error: safe operator `?` on `null`.")
2593 self.mtype
= mtype
.as_notnull
2595 if not v
.can_be_null
(mtype
) then
2596 v
.modelbuilder
.warning
(self, "useless-safe", "Warning: useless safe operator `?` on non-nullable value.")
2602 redef class AVarargExpr
2603 redef fun accept_typing
(v
)
2605 # This kind of pseudo-expression can be only processed trough a signature
2606 # See `check_signature`
2607 # Other cases are a syntax error.
2608 v
.error
(self, "Syntax Error: unexpected `...`.")
2614 redef class ADebugTypeExpr
2615 redef fun accept_typing
(v
)
2617 var expr
= v
.visit_expr
(self.n_expr
)
2618 if expr
== null then return
2619 var unsafe
= v
.anchor_to
(expr
)
2620 var ntype
= self.n_type
2621 var mtype
= v
.resolve_mtype
(ntype
)
2622 if mtype
!= null and mtype
!= expr
then
2623 var umtype
= v
.anchor_to
(mtype
)
2624 v
.modelbuilder
.warning
(self, "debug", "Found type {expr} (-> {unsafe}), expected {mtype} (-> {umtype})")
2626 self.is_typed
= true