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
)
322 if mproperty
== null then
324 self.modelbuilder
.error
(node
, "Error: method or variable `{name}` unknown in `{recvtype}`.")
325 else if recvtype
.need_anchor
then
326 self.modelbuilder
.error
(node
, "Error: method `{name}` does not exists in `{recvtype}: {unsafe_type}`.")
328 self.modelbuilder
.error
(node
, "Error: method `{name}` does not exists in `{recvtype}`.")
333 assert mproperty
isa MMethod
335 return build_callsite_by_property
(node
, recvtype
, mproperty
, recv_is_self
)
338 # The `build_callsite_by_property` finds the mpropdefs to call by the `MMethod`.
339 # If the mpropdef is found in the context it builds a new `Callsite`.
340 fun build_callsite_by_property
(node
: ANode, recvtype
: MType, mproperty
: MMethod, recv_is_self
: Bool): nullable CallSite
342 var unsafe_type
= self.anchor_to
(recvtype
)
344 if recvtype
isa MNullType then
345 var objclass
= get_mclass
(node
, "Object")
346 if objclass
== null then return null # Forward error
347 unsafe_type
= objclass
.mclass_type
349 # `null` only accepts some methods of object.
350 if recvtype
isa MNullType and not mproperty
.is_null_safe
then
351 self.error
(node
, "Error: method `{mproperty.name}` called on `null`.")
353 else if unsafe_type
isa MNullableType and not mproperty
.is_null_safe
then
354 modelbuilder
.advice
(node
, "call-on-nullable", "Warning: method call on a nullable receiver `{recvtype}`.")
357 if is_toplevel_context
and recv_is_self
and not mproperty
.is_toplevel
then
358 error
(node
, "Error: `{mproperty.name}` is not a top-level method, thus need a receiver.")
360 if not recv_is_self
and mproperty
.is_toplevel
then
361 error
(node
, "Error: cannot call `{mproperty.name}`, a top-level method, with a receiver.")
364 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
365 self.modelbuilder
.error
(node
, "Error: method `{mproperty.name}` is protected and can only accessed by `self`.")
369 var info
= mproperty
.deprecation
370 if info
!= null and self.mpropdef
.mproperty
.deprecation
== null then
373 self.modelbuilder
.warning
(node
, "deprecated-method", "Deprecation Warning: method `{mproperty.name}` is deprecated: {mdoc.content.first}")
375 self.modelbuilder
.warning
(node
, "deprecated-method", "Deprecation Warning: method `{mproperty.name}` is deprecated.")
379 var propdefs
= mproperty
.lookup_definitions
(self.mmodule
, unsafe_type
)
381 if propdefs
.length
== 0 then
382 self.modelbuilder
.error
(node
, "Type Error: no definition found for property `{mproperty.name}` in `{unsafe_type}`.")
385 else if propdefs
.length
== 1 then
386 mpropdef
= propdefs
.first
388 self.modelbuilder
.warning
(node
, "property-conflict", "Warning: conflicting property definitions for property `{mproperty.name}` in `{unsafe_type}`: {propdefs.join(" ")}")
389 mpropdef
= mproperty
.intro
392 return build_callsite_by_propdef
(node
, recvtype
, mpropdef
, recv_is_self
)
395 # The `build_callsite_by_propdef` builds the callsite directly with the `mprodef` passed in argument.
396 fun build_callsite_by_propdef
(node
: ANode, recvtype
: MType, mpropdef
: MMethodDef, recv_is_self
: Bool): nullable CallSite
398 var msignature
= mpropdef
.new_msignature
or else mpropdef
.msignature
399 if msignature
== null then return null # skip error
400 msignature
= resolve_for
(msignature
, recvtype
, recv_is_self
).as(MSignature)
402 var erasure_cast
= false
403 var rettype
= mpropdef
.msignature
.return_mtype
404 if not recv_is_self
and rettype
!= null then
405 rettype
= rettype
.undecorate
406 if rettype
isa MParameterType then
407 var erased_rettype
= msignature
.return_mtype
408 assert erased_rettype
!= null
409 #node.debug("Erasure cast: Really a {rettype} but unsafely a {erased_rettype}")
414 var callsite
= new CallSite(node
.hot_location
, recvtype
, mmodule
, anchor
, recv_is_self
, mpropdef
.mproperty
, mpropdef
, msignature
, erasure_cast
)
418 fun try_build_callsite_by_name
(node
: ANode, recvtype
: MType, name
: String, recv_is_self
: Bool): nullable CallSite
420 var unsafe_type
= self.anchor_to
(recvtype
)
421 var mproperty
= self.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
422 if mproperty
== null then return null
423 return build_callsite_by_name
(node
, recvtype
, name
, recv_is_self
)
426 # Visit the expressions of args and check their conformity with the corresponding type in signature
427 # The point of this method is to handle varargs correctly
428 # Note: The signature must be correctly adapted
429 fun check_signature
(node
: ANode, args
: Array[AExpr], mproperty
: MProperty, msignature
: MSignature): nullable SignatureMap
431 var vararg_rank
= msignature
.vararg_rank
432 if vararg_rank
>= 0 then
433 if args
.length
< msignature
.arity
then
434 modelbuilder
.error
(node
, "Error: expected at least {msignature.arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
437 else if args
.length
!= msignature
.arity
then
439 if args
.length
> msignature
.arity
then
440 modelbuilder
.error
(node
, "Error: expected {msignature.arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
443 # Other cases are managed later
446 #debug("CALL {unsafe_type}.{msignature}")
448 # Associate each parameter to a position in the arguments
449 var map
= new SignatureMap
451 # Special case for the isolated last argument
452 # TODO: reify this method characteristics (where? the param, the signature, the method?)
453 var last_is_padded
= mproperty
.name
.chars
.last
== '='
454 var nbargs
= args
.length
455 if last_is_padded
then
457 assert not args
.last
isa ANamedargExpr
458 map
.map
[msignature
.arity
- 1] = args
.length
- 1
459 self.visit_expr_subtype
(args
.last
, msignature
.mparameters
.last
.mtype
)
462 # First, handle named arguments
463 for i
in [0..args
.length
[ do
465 if not e
isa ANamedargExpr then continue
466 var name
= e
.n_id
.text
467 var param
= msignature
.mparameter_by_name
(name
)
468 if param
== null then
469 modelbuilder
.error
(e
.n_id
, "Error: no parameter `{name}` for `{mproperty}{msignature}`.")
472 var idx
= msignature
.mparameters
.index_of
(param
)
473 var prev
= map
.map
.get_or_null
(idx
)
475 modelbuilder
.error
(e
, "Error: parameter `{name}` already associated with argument #{prev} for `{mproperty}{msignature}`.")
479 e
.mtype
= self.visit_expr_subtype
(e
.n_expr
, param
.mtype
)
482 # Number of minimum mandatory remaining parameters
485 # Second, associate remaining parameters
486 var vararg_decl
= args
.length
- msignature
.arity
488 for i
in [0..msignature
.arity
[ do
489 # Skip parameters associated by name
490 if map
.map
.has_key
(i
) then continue
492 var param
= msignature
.mparameters
[i
]
494 # Search the next free argument: skip named arguments since they are already associated
495 while j
< nbargs
and args
[j
] isa ANamedargExpr do j
+= 1
497 if not param
.mtype
isa MNullableType then
507 if i
== vararg_rank
then
509 continue # skip the vararg
512 if not param
.is_vararg
then
513 var paramtype
= param
.mtype
514 self.visit_expr_subtype
(arg
, paramtype
)
516 check_one_vararg
(arg
, param
)
520 if min_arity
> 0 then
521 if last_is_padded
then min_arity
+= 1
522 if min_arity
< msignature
.arity
then
523 modelbuilder
.error
(node
, "Error: expected at least {min_arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
525 modelbuilder
.error
(node
, "Error: expected {min_arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
530 # Third, check varargs
531 if vararg_rank
>= 0 then
532 var paramtype
= msignature
.mparameters
[vararg_rank
].mtype
533 var first
= args
[vararg_rank
]
534 if vararg_decl
== 0 then
535 if not check_one_vararg
(first
, msignature
.mparameters
[vararg_rank
]) then return null
537 first
.vararg_decl
= vararg_decl
+ 1
538 for i
in [vararg_rank
..vararg_rank
+vararg_decl
] do
539 self.visit_expr_subtype
(args
[i
], paramtype
)
547 # Check an expression as a single vararg.
548 # The main point of the method if to handle the case of reversed vararg (see `AVarargExpr`)
549 fun check_one_vararg
(arg
: AExpr, param
: MParameter): Bool
551 var paramtype
= param
.mtype
552 var mclass
= get_mclass
(arg
, "Array")
553 if mclass
== null then return false # Forward error
554 var array_mtype
= mclass
.get_mtype
([paramtype
])
555 if arg
isa AVarargExpr then
556 self.visit_expr_subtype
(arg
.n_expr
, array_mtype
)
557 arg
.mtype
= arg
.n_expr
.mtype
559 # only one vararg, maybe `...` was forgot, so be gentle!
560 var t
= visit_expr
(arg
)
561 if t
== null then return false # Forward error
562 if not is_subtype
(t
, paramtype
) and is_subtype
(t
, array_mtype
) then
563 # Not acceptable but could be a `...`
564 error
(arg
, "Type Error: expected `{paramtype}`, got `{t}`. Is an ellipsis `...` missing on the argument?")
567 # Standard valid vararg, finish the job
569 self.visit_expr_subtype
(arg
, paramtype
)
574 fun error
(node
: ANode, message
: String)
576 self.modelbuilder
.error
(node
, message
)
579 fun get_variable
(node
: AExpr, variable
: Variable): nullable MType
581 if not variable
.is_adapted
then return variable
.declared_type
583 var flow
= node
.after_flow_context
584 if flow
== null then return null # skip error
586 if flow
.vars
.has_key
(variable
) then
587 return flow
.vars
[variable
]
589 #node.debug("*** START Collected for {variable}")
590 var mtypes
= flow
.collect_types
(variable
)
591 #node.debug("**** END Collected for {variable}")
592 if mtypes
.length
== 0 then
593 return variable
.declared_type
594 else if mtypes
.length
== 1 then
597 var res
= merge_types
(node
,mtypes
)
599 res
= variable
.declared_type
600 # Try to fallback to a non-null version
601 if res
!= null and can_be_null
(res
) then do
603 if t
!= null and can_be_null
(t
) then break label
613 # Some variables where type-adapted during the visit
616 # Some loops had been visited during the visit
619 fun set_variable
(node
: AExpr, variable
: Variable, mtype
: nullable MType)
621 var flow
= node
.after_flow_context
624 flow
.set_var
(self, variable
, mtype
)
627 # Find the exact representable most specific common super-type in `col`.
629 # Try to find the most specific common type that is a super-type of each types
631 # In most cases, the result is simply the most general type in `col`.
632 # If nullables types are involved, then the nullable information is correctly preserved.
633 # If incomparable super-types exists in `col`, them no solution is given and the `null`
634 # value is returned (since union types are non representable in Nit)
636 # The `null` values in `col` are ignored, nulltypes (MNullType) are considered.
638 # Returns the `null` value if:
641 # * `col` only have null values
642 # * there is a conflict
644 # Example (with a diamond A,B,C,D):
646 # * merge(A,B,C) -> A, because A is the most general type in {A,B,C}
647 # * merge(C,B) -> null, there is conflict, because `B or C` cannot be represented
648 # * merge(A,nullable B) -> nullable A, because A is the most general type and
649 # the nullable information is preserved
650 fun merge_types
(node
: ANode, col
: Array[nullable MType]): nullable MType
652 if col
.length
== 1 then return col
.first
654 if t1
== null then continue # return null
657 if t2
== null then continue # return null
658 if can_be_null
(t2
) and not can_be_null
(t1
) then
661 if not is_subtype
(t2
, t1
) then found
= false
664 #print "merge {col.join(" ")} -> {t1}"
668 #self.modelbuilder.warning(node, "Type Error: {col.length} conflicting types: <{col.join(", ")}>")
672 # Find a most general common subtype between `type1` and `type2`.
674 # Find the most general type that is a subtype of `type2` and, if possible, a subtype of `type1`.
675 # Basically, this return the most specific type between `type1` and `type2`.
676 # If nullable types are involved, the information is correctly preserved.
677 # If `type1` and `type2` are incomparable then `type2` is preferred (since intersection types
678 # are not representable in Nit).
680 # The `null` value is returned if both `type1` and `type2` are null.
682 # Examples (with diamond A,B,C,D):
684 # * intersect_types(A,B) -> B, because B is a subtype of A
685 # * intersect_types(B,A) -> B, because B is a subtype of A
686 # * intersect_types(B,C) -> C, B and C are incomparable,
687 # `type2` is then preferred (`B and C` cannot be represented)
688 # * intersect_types(nullable B,A) -> B, because B<:A and the non-null information is preserved
689 # * intersect_types(B,nullable C) -> C, `type2` is preferred and the non-null information is preserved
690 fun intersect_types
(node
: ANode, type1
, type2
: nullable MType): nullable MType
692 if type1
== null then return type2
693 if type2
== null then return type1
695 if not can_be_null
(type2
) or not can_be_null
(type1
) then
696 type1
= type1
.as_notnull
697 type2
= type2
.as_notnull
701 if is_subtype
(type1
, type2
) then
709 # Find a most general type that is a subtype of `type1` but not one of `type2`.
711 # Basically, this returns `type1`-`type2` but since there is no substraction type
712 # in Nit this just returns `type1` most of the case.
714 # The few other cases are if `type2` is a super-type and if some nullable information
717 # The `null` value is returned if `type1` is null.
719 # Examples (with diamond A,B,C,D):
721 # * diff_types(A,B) -> A, because the notB cannot be represented
722 # * diff_types(B,A) -> None (absurd type), because B<:A
723 # * diff_types(nullable A, nullable B) -> A, because null is removed
724 # * diff_types(nullable B, A) -> Null, because anything but null is removed
725 fun diff_types
(node
: ANode, type1
, type2
: nullable MType): nullable MType
727 if type1
== null then return null
728 if type2
== null then return type1
730 # if t1 <: t2 then t1-t2 = bottom
731 if is_subtype
(type1
, type2
) then
732 return modelbuilder
.model
.null_type
.as_notnull
735 # else if t1 <: nullable t2 then t1-t2 = nulltype
736 if is_subtype
(type1
, type2
.as_nullable
) then
737 return modelbuilder
.model
.null_type
740 # else t2 can be null and type2 must accept null then null is excluded in t1
741 if can_be_null
(type1
) and (type2
isa MNullableType or type2
isa MNullType) then
742 return type1
.as_notnull
749 # Mapping between parameters and arguments in a call.
751 # Parameters and arguments are not stored in the class but referenced by their position (starting from 0)
753 # The point of this class is to help engine and other things to map arguments in the AST to parameters of the model.
755 # Associate a parameter to an argument
756 var map
= new ArrayMap[Int, Int]
759 # A specific method call site with its associated informations.
765 # The static type of the receiver (possibly unresolved)
768 # The module where the callsite is present
771 # The anchor to use with `recv` or `msignature`
772 var anchor
: nullable MClassType
774 # Is the receiver self?
775 # If "for_self", virtual types of the signature are kept
776 # If "not_for_self", virtual type are erased
777 var recv_is_self
: Bool
779 # The designated method
780 var mproperty
: MMethod
782 # The statically designated method definition
783 # The most specif one, it is.
784 var mpropdef
: MMethodDef
786 # The resolved signature for the receiver
787 var msignature
: MSignature
789 # Is a implicit cast required on erasure typing policy?
790 var erasure_cast
: Bool
792 # The mapping used on the call to associate arguments to parameters
793 # If null then no specific association is required.
794 var signaturemap
: nullable SignatureMap = null
796 private fun check_signature
(v
: TypeVisitor, node
: ANode, args
: Array[AExpr]): Bool
798 var map
= v
.check_signature
(node
, args
, self.mproperty
, self.msignature
)
800 if map
== null then is_broken
= true
804 # Information about the callsite to display on a node
805 fun dump_info
(v
: ASTDump): String do
806 return "{recv}.{mpropdef}{msignature}"
809 redef fun mdoc_or_fallback
do return mproperty
.intro
.mdoc
813 # The declared type of the variable
814 var declared_type
: nullable MType = null is writable
816 # Was the variable type-adapted?
817 # This is used to speedup type retrieval while it remains `false`
818 private var is_adapted
= false
821 redef class FlowContext
822 # Store changes of types because of type evolution
823 private var vars
= new HashMap[Variable, nullable MType]
825 # Adapt the variable to a static type
826 # Warning1: do not modify vars directly.
827 # Warning2: sub-flow may have cached a unadapted variable
828 private fun set_var
(v
: TypeVisitor, variable
: Variable, mtype
: nullable MType)
830 if variable
.declared_type
== mtype
and not variable
.is_adapted
then return
831 if vars
.has_key
(variable
) and vars
[variable
] == mtype
then return
832 self.vars
[variable
] = mtype
834 variable
.is_adapted
= true
835 #node.debug "set {variable} to {mtype or else "X"}"
838 # Look in the flow and previous flow and collect all first reachable type adaptation of a local variable
839 private fun collect_types
(variable
: Variable): Array[nullable MType]
841 #node.debug "flow for {variable}"
842 var res
= new Array[nullable MType]
845 var seen
= new HashSet[FlowContext]
846 while not todo
.is_empty
do
848 if f
.is_unreachable
then continue
849 if seen
.has
(f
) then continue
852 if f
.vars
.has_key
(variable
) then
853 # Found something. Collect it and do not process further on this path
854 res
.add f
.vars
[variable
]
855 #f.node.debug "process {variable}: got {f.vars[variable] or else "X"}"
857 todo
.add_all f
.previous
859 if f
.previous
.is_empty
then
860 # Root flowcontext mean a parameter or something related
861 res
.add variable
.declared_type
862 #f.node.debug "root process {variable}: got {variable.declared_type or else "X"}"
866 #self.node.debug "##### end flow for {variable}: {res.join(" ")}"
872 # The entry point of the whole typing analysis
873 fun do_typing
(modelbuilder
: ModelBuilder)
877 # The variable associated to the receiver (if any)
878 var selfvariable
: nullable Variable
881 redef class AMethPropdef
882 redef fun do_typing
(modelbuilder
: ModelBuilder)
884 var mpropdef
= self.mpropdef
885 if mpropdef
== null then return # skip error
887 var v
= new TypeVisitor(modelbuilder
, mpropdef
)
888 self.selfvariable
= v
.selfvariable
890 var mmethoddef
= self.mpropdef
.as(not null)
891 var msignature
= mmethoddef
.msignature
892 if msignature
== null then return # skip error
893 for i
in [0..msignature
.arity
[ do
894 var mtype
= msignature
.mparameters
[i
].mtype
895 if msignature
.vararg_rank
== i
then
896 var arrayclass
= v
.get_mclass
(self.n_signature
.n_params
[i
], "Array")
897 if arrayclass
== null then return # Skip error
898 mtype
= arrayclass
.get_mtype
([mtype
])
900 var variable
= self.n_signature
.n_params
[i
].variable
901 assert variable
!= null
902 variable
.declared_type
= mtype
905 var nblock
= self.n_block
906 if nblock
== null then return
911 if not v
.has_loop
or not v
.dirty
then break
914 var post_visitor
= new PostTypingVisitor(v
)
915 post_visitor
.enter_visit
(self)
917 if not nblock
.after_flow_context
.is_unreachable
and msignature
.return_mtype
!= null then
918 # We reach the end of the function without having a return, it is bad
919 v
.error
(self, "Error: reached end of function; expected `return` with a value.")
924 private class PostTypingVisitor
926 var type_visitor
: TypeVisitor
927 redef fun visit
(n
) do
929 n
.accept_post_typing
(type_visitor
)
930 if n
isa AExpr and n
.mtype
== null and not n
.is_typed
then
937 private fun accept_post_typing
(v
: TypeVisitor) do end
939 # An additional information message to explain the role of a child expression.
941 # The point of the method is to allow some kind of double dispatch so the parent
942 # choose how to describe its children.
943 private fun bad_expr_message
(child
: AExpr): nullable String do return null
946 redef class AAttrPropdef
947 redef fun do_typing
(modelbuilder
: ModelBuilder)
949 if not has_value
then return
951 var mpropdef
= self.mreadpropdef
952 if mpropdef
== null or mpropdef
.msignature
== null then return # skip error
954 var v
= new TypeVisitor(modelbuilder
, mpropdef
)
955 self.selfvariable
= v
.selfvariable
957 var nexpr
= self.n_expr
958 if nexpr
!= null then
959 var mtype
= self.mtype
960 v
.visit_expr_subtype
(nexpr
, mtype
)
962 var nblock
= self.n_block
963 if nblock
!= null then
965 if not nblock
.after_flow_context
.is_unreachable
then
966 # We reach the end of the init without having a return, it is bad
967 v
.error
(self, "Error: reached end of block; expected `return`.")
976 # The static type of the expression.
977 # null if self is a statement or in case of error
978 var mtype
: nullable MType = null
980 # Is the statement correctly typed?
981 # Used to distinguish errors and statements when `mtype == null`
982 var is_typed
: Bool = false
984 # If required, the following implicit cast `.as(XXX)`
985 # Such a cast may by required after evaluating the expression when
986 # a unsafe operation is detected (silently accepted by the Nit language).
987 # The attribute is computed by `check_subtype`
988 var implicit_cast_to
: nullable MType = null
990 # Return the variable read (if any)
991 # Used to perform adaptive typing
992 fun its_variable
: nullable Variable do return null
994 private fun accept_typing
(v
: TypeVisitor)
996 v
.error
(self, "no implemented accept_typing for {self.class_name}")
999 # Is non-null if `self` is a leaf of a comprehension array construction.
1000 # In this case, the enclosing literal array node is designated.
1001 # The result of the evaluation of `self` must be
1002 # stored inside the designated array (there is an implicit `push`)
1003 var comprehension
: nullable AArrayExpr = null
1005 # It indicates the number of arguments collected as a vararg.
1007 # When 0, the argument is used as is, without transformation.
1008 # When 1, the argument is transformed into an singleton array.
1009 # Above 1, the arguments and the next ones are transformed into a common array.
1011 # This attribute is meaning less on expressions not used as attributes.
1012 var vararg_decl
: Int = 0
1014 redef fun dump_info
(v
) do
1016 var mtype
= self.mtype
1017 if mtype
!= null then
1018 res
+= v
.yellow
(":{mtype}")
1020 var ict
= self.implicit_cast_to
1022 res
+= v
.yellow
("(.as({ict}))")
1028 redef class ABlockExpr
1029 redef fun accept_typing
(v
)
1031 for e
in self.n_expr
do v
.visit_stmt
(e
)
1032 self.is_typed
= true
1035 # The type of a blockexpr is the one of the last expression (or null if empty)
1038 if self.n_expr
.is_empty
then return null
1039 return self.n_expr
.last
.mtype
1043 redef class AVardeclExpr
1044 redef fun accept_typing
(v
)
1046 var variable
= self.variable
1047 if variable
== null then return # Skip error
1049 var ntype
= self.n_type
1050 var mtype
: nullable MType
1051 if ntype
== null then
1054 mtype
= v
.resolve_mtype
(ntype
)
1055 if mtype
== null then return # Skip error
1058 var nexpr
= self.n_expr
1059 if nexpr
!= null then
1060 if mtype
!= null then
1061 var etype
= v
.visit_expr_subtype
(nexpr
, mtype
)
1062 if etype
== mtype
then
1063 assert ntype
!= null
1064 v
.modelbuilder
.advice
(ntype
, "useless-type", "Warning: useless type definition for variable `{variable.name}`")
1067 mtype
= v
.visit_expr
(nexpr
)
1068 if mtype
== null then return # Skip error
1072 var decltype
= mtype
1073 if mtype
== null or mtype
isa MNullType then
1074 var objclass
= v
.get_mclass
(self, "Object")
1075 if objclass
== null then return # skip error
1076 decltype
= objclass
.mclass_type
.as_nullable
1077 if mtype
== null then mtype
= decltype
1080 variable
.declared_type
= decltype
1081 v
.set_variable
(self, variable
, mtype
)
1083 #debug("var {variable}: {mtype}")
1086 self.is_typed
= true
1090 redef class AVarExpr
1091 redef fun its_variable
do return self.variable
1092 redef fun accept_typing
(v
)
1094 var variable
= self.variable
1095 if variable
== null then return # Skip error
1097 var mtype
= v
.get_variable
(self, variable
)
1098 if mtype
!= null then
1099 #debug("{variable} is {mtype}")
1101 #debug("{variable} is untyped")
1108 redef class AVarAssignExpr
1109 redef fun accept_typing
(v
)
1111 var variable
= self.variable
1112 assert variable
!= null
1114 var mtype
= v
.visit_expr_subtype
(n_value
, variable
.declared_type
)
1116 v
.set_variable
(self, variable
, mtype
)
1118 self.is_typed
= true
1122 redef class AReassignFormExpr
1123 # The method designed by the reassign operator.
1124 var reassign_callsite
: nullable CallSite
1126 var read_type
: nullable MType = null
1128 # Determine the `reassign_property`
1129 # `readtype` is the type of the reading of the left value.
1130 # `writetype` is the type of the writing of the left value.
1131 # (Because of `ACallReassignExpr`, both can be different.
1132 # Return the static type of the value to store.
1133 private fun resolve_reassignment
(v
: TypeVisitor, readtype
, writetype
: MType): nullable MType
1135 var reassign_name
= self.n_assign_op
.operator
1137 self.read_type
= readtype
1139 var callsite
= v
.build_callsite_by_name
(self.n_assign_op
, readtype
, reassign_name
, false)
1140 if callsite
== null then return null # Skip error
1141 self.reassign_callsite
= callsite
1143 var msignature
= callsite
.msignature
1144 var rettype
= msignature
.return_mtype
1145 assert msignature
.arity
== 1 and rettype
!= null
1147 var value_type
= v
.visit_expr_subtype
(self.n_value
, msignature
.mparameters
.first
.mtype
)
1148 if value_type
== null then return null # Skip error
1150 v
.check_subtype
(self, rettype
, writetype
, false)
1155 redef class AVarReassignExpr
1156 redef fun accept_typing
(v
)
1158 var variable
= self.variable
1159 assert variable
!= null
1161 var readtype
= v
.get_variable
(self, variable
)
1162 if readtype
== null then return
1164 read_type
= readtype
1166 var writetype
= variable
.declared_type
1167 if writetype
== null then return
1169 var rettype
= self.resolve_reassignment
(v
, readtype
, writetype
)
1171 v
.set_variable
(self, variable
, rettype
)
1173 self.is_typed
= rettype
!= null
1177 redef class AContinueExpr
1178 redef fun accept_typing
(v
)
1180 var nexpr
= self.n_expr
1181 if nexpr
!= null then
1184 self.is_typed
= true
1188 redef class ABreakExpr
1189 redef fun accept_typing
(v
)
1191 var nexpr
= self.n_expr
1192 if nexpr
!= null then
1195 self.is_typed
= true
1199 redef class AReturnExpr
1200 redef fun accept_typing
(v
)
1202 var nexpr
= self.n_expr
1204 var mpropdef
= v
.mpropdef
1205 if mpropdef
isa MMethodDef then
1206 ret_type
= mpropdef
.msignature
.return_mtype
1207 else if mpropdef
isa MAttributeDef then
1208 ret_type
= mpropdef
.static_mtype
1212 if nexpr
!= null then
1213 if ret_type
!= null then
1214 v
.visit_expr_subtype
(nexpr
, ret_type
)
1217 v
.error
(nexpr
, "Error: `return` with value in a procedure.")
1220 else if ret_type
!= null then
1221 v
.error
(self, "Error: `return` without value in a function.")
1224 self.is_typed
= true
1228 redef class AAbortExpr
1229 redef fun accept_typing
(v
)
1231 self.is_typed
= true
1236 redef fun accept_typing
(v
)
1238 v
.visit_expr_bool
(n_expr
)
1240 v
.visit_stmt
(n_then
)
1241 v
.visit_stmt
(n_else
)
1243 self.is_typed
= true
1245 if n_then
!= null and n_else
== null then
1246 self.mtype
= n_then
.mtype
1251 redef class AIfexprExpr
1252 redef fun accept_typing
(v
)
1254 v
.visit_expr_bool
(n_expr
)
1256 var t1
= v
.visit_expr
(n_then
)
1257 var t2
= v
.visit_expr
(n_else
)
1259 if t1
== null or t2
== null then
1263 var t
= v
.merge_types
(self, [t1
, t2
])
1265 v
.error
(self, "Type Error: ambiguous type `{t1}` vs `{t2}`.")
1272 redef fun accept_typing
(v
)
1274 v
.visit_stmt
(n_block
)
1275 v
.visit_stmt
(n_catch
)
1276 self.is_typed
= true
1280 redef class AWhileExpr
1281 redef fun accept_typing
(v
)
1284 v
.visit_expr_bool
(n_expr
)
1285 v
.visit_stmt
(n_block
)
1286 self.is_typed
= true
1290 redef class ALoopExpr
1291 redef fun accept_typing
(v
)
1294 v
.visit_stmt
(n_block
)
1295 self.is_typed
= true
1299 redef class AForExpr
1300 redef fun accept_typing
(v
)
1304 for g
in n_groups
do
1305 var mtype
= v
.visit_expr
(g
.n_expr
)
1306 if mtype
== null then return
1307 g
.do_type_iterator
(v
, mtype
)
1308 if g
.is_broken
then is_broken
= true
1311 v
.visit_stmt
(n_block
)
1313 self.mtype
= n_block
.mtype
1314 self.is_typed
= true
1318 redef class AForGroup
1319 var coltype
: nullable MClassType
1321 var method_iterator
: nullable CallSite
1322 var method_is_ok
: nullable CallSite
1323 var method_item
: nullable CallSite
1324 var method_next
: nullable CallSite
1325 var method_key
: nullable CallSite
1326 var method_finish
: nullable CallSite
1328 var method_lt
: nullable CallSite
1329 var method_successor
: nullable CallSite
1331 private fun do_type_iterator
(v
: TypeVisitor, mtype
: MType)
1333 if mtype
isa MNullType then
1334 v
.error
(self, "Type Error: `for` cannot iterate over `null`.")
1339 var objcla
= v
.get_mclass
(self, "Object")
1340 if objcla
== null then return
1342 # check iterator method
1343 var itdef
= v
.build_callsite_by_name
(self, mtype
, "iterator", n_expr
isa ASelfExpr)
1344 if itdef
== null then
1345 v
.error
(self, "Type Error: `for` expects a type providing an `iterator` method, got `{mtype}`.")
1348 self.method_iterator
= itdef
1350 # check that iterator return something
1351 var ittype
= itdef
.msignature
.return_mtype
1352 if ittype
== null then
1353 v
.error
(self, "Type Error: `for` expects the method `iterator` to return an `Iterator` or `MapIterator` type.")
1358 var colit_cla
= v
.try_get_mclass
(self, "Iterator")
1359 var mapit_cla
= v
.try_get_mclass
(self, "MapIterator")
1363 if colit_cla
!= null and v
.is_subtype
(ittype
, colit_cla
.get_mtype
([objcla
.mclass_type
.as_nullable
])) then
1365 var coltype
= ittype
.supertype_to
(v
.mmodule
, v
.anchor
, colit_cla
)
1366 var variables
= self.variables
1367 if variables
.length
!= 1 then
1368 v
.error
(self, "Type Error: `for` expects only one variable when using `Iterator`.")
1370 variables
.first
.declared_type
= coltype
.arguments
.first
1375 if mapit_cla
!= null and v
.is_subtype
(ittype
, mapit_cla
.get_mtype
([objcla
.mclass_type
.as_nullable
, objcla
.mclass_type
.as_nullable
])) then
1377 var coltype
= ittype
.supertype_to
(v
.mmodule
, v
.anchor
, mapit_cla
)
1378 var variables
= self.variables
1379 if variables
.length
!= 2 then
1380 v
.error
(self, "Type Error: `for` expects two variables when using `MapIterator`.")
1382 variables
[0].declared_type
= coltype
.arguments
[0]
1383 variables
[1].declared_type
= coltype
.arguments
[1]
1388 if not is_col
and not is_map
then
1389 v
.error
(self, "Type Error: `for` expects the method `iterator` to return an `Iterator` or `MapIterator` type.")
1393 # anchor formal and virtual types
1394 if mtype
.need_anchor
then mtype
= v
.anchor_to
(mtype
)
1396 mtype
= mtype
.undecorate
1397 self.coltype
= mtype
.as(MClassType)
1399 # get methods is_ok, next, item
1400 var ikdef
= v
.build_callsite_by_name
(self, ittype
, "is_ok", false)
1401 if ikdef
== null then
1402 v
.error
(self, "Type Error: `for` expects a method `is_ok` in type `{ittype}`.")
1405 self.method_is_ok
= ikdef
1407 var itemdef
= v
.build_callsite_by_name
(self, ittype
, "item", false)
1408 if itemdef
== null then
1409 v
.error
(self, "Type Error: `for` expects a method `item` in type `{ittype}`.")
1412 self.method_item
= itemdef
1414 var nextdef
= v
.build_callsite_by_name
(self, ittype
, "next", false)
1415 if nextdef
== null then
1416 v
.error
(self, "Type Error: `for` expects a method `next` in type {ittype}.")
1419 self.method_next
= nextdef
1421 self.method_finish
= v
.try_build_callsite_by_name
(self, ittype
, "finish", false)
1424 var keydef
= v
.build_callsite_by_name
(self, ittype
, "key", false)
1425 if keydef
== null then
1426 v
.error
(self, "Type Error: `for` expects a method `key` in type `{ittype}`.")
1429 self.method_key
= keydef
1432 if self.variables
.length
== 1 and n_expr
isa ARangeExpr then
1433 var variable
= variables
.first
1434 var vtype
= variable
.declared_type
.as(not null)
1436 if n_expr
isa AOrangeExpr then
1437 self.method_lt
= v
.build_callsite_by_name
(self, vtype
, "<", false)
1439 self.method_lt
= v
.build_callsite_by_name
(self, vtype
, "<=", false)
1442 self.method_successor
= v
.build_callsite_by_name
(self, vtype
, "successor", false)
1447 redef class AWithExpr
1448 var method_start
: nullable CallSite
1449 var method_finish
: nullable CallSite
1451 redef fun accept_typing
(v
: TypeVisitor)
1453 var mtype
= v
.visit_expr
(n_expr
)
1454 if mtype
== null then return
1456 method_start
= v
.build_callsite_by_name
(self, mtype
, "start", n_expr
isa ASelfExpr)
1457 method_finish
= v
.build_callsite_by_name
(self, mtype
, "finish", n_expr
isa ASelfExpr)
1459 v
.visit_stmt
(n_block
)
1460 self.mtype
= n_block
.mtype
1461 self.is_typed
= true
1465 redef class AAssertExpr
1466 redef fun accept_typing
(v
)
1468 v
.visit_expr_bool
(n_expr
)
1470 v
.visit_stmt
(n_else
)
1471 self.is_typed
= true
1476 redef fun accept_typing
(v
)
1478 v
.visit_expr_bool
(n_expr
)
1479 v
.visit_expr_bool
(n_expr2
)
1480 self.mtype
= v
.type_bool
(self)
1484 redef class AImpliesExpr
1485 redef fun accept_typing
(v
)
1487 v
.visit_expr_bool
(n_expr
)
1488 v
.visit_expr_bool
(n_expr2
)
1489 self.mtype
= v
.type_bool
(self)
1493 redef class AAndExpr
1494 redef fun accept_typing
(v
)
1496 v
.visit_expr_bool
(n_expr
)
1497 v
.visit_expr_bool
(n_expr2
)
1498 self.mtype
= v
.type_bool
(self)
1502 redef class ANotExpr
1503 redef fun accept_typing
(v
)
1505 v
.visit_expr_bool
(n_expr
)
1506 self.mtype
= v
.type_bool
(self)
1510 redef class AOrElseExpr
1511 redef fun accept_typing
(v
)
1513 var t1
= v
.visit_expr
(n_expr
)
1514 var t2
= v
.visit_expr
(n_expr2
)
1516 if t1
== null or t2
== null then
1520 if t1
isa MNullType then
1523 else if v
.can_be_null
(t1
) then
1527 var t
= v
.merge_types
(self, [t1
, t2
])
1529 var c
= v
.get_mclass
(self, "Object")
1530 if c
== null then return # forward error
1532 if v
.can_be_null
(t2
) then
1535 #v.error(self, "Type Error: ambiguous type {t1} vs {t2}")
1540 redef fun accept_post_typing
(v
)
1542 var t1
= n_expr
.mtype
1546 v
.check_can_be_null
(n_expr
, t1
)
1551 redef class ATrueExpr
1552 redef fun accept_typing
(v
)
1554 self.mtype
= v
.type_bool
(self)
1558 redef class AFalseExpr
1559 redef fun accept_typing
(v
)
1561 self.mtype
= v
.type_bool
(self)
1565 redef class AIntegerExpr
1566 redef fun accept_typing
(v
)
1568 var mclass
: nullable MClass = null
1569 if value
isa Byte then
1570 mclass
= v
.get_mclass
(self, "Byte")
1571 else if value
isa Int then
1572 mclass
= v
.get_mclass
(self, "Int")
1573 else if value
isa Int8 then
1574 mclass
= v
.get_mclass
(self, "Int8")
1575 else if value
isa Int16 then
1576 mclass
= v
.get_mclass
(self, "Int16")
1577 else if value
isa UInt16 then
1578 mclass
= v
.get_mclass
(self, "UInt16")
1579 else if value
isa Int32 then
1580 mclass
= v
.get_mclass
(self, "Int32")
1581 else if value
isa UInt32 then
1582 mclass
= v
.get_mclass
(self, "UInt32")
1584 if mclass
== null then return # Forward error
1585 self.mtype
= mclass
.mclass_type
1589 redef class AFloatExpr
1590 redef fun accept_typing
(v
)
1592 var mclass
= v
.get_mclass
(self, "Float")
1593 if mclass
== null then return # Forward error
1594 self.mtype
= mclass
.mclass_type
1598 redef class ACharExpr
1599 redef fun accept_typing
(v
) do
1600 var mclass
: nullable MClass = null
1601 if is_code_point
then
1602 mclass
= v
.get_mclass
(self, "Int")
1604 mclass
= v
.get_mclass
(self, "Char")
1606 if mclass
== null then return # Forward error
1607 self.mtype
= mclass
.mclass_type
1611 redef class AugmentedStringFormExpr
1614 # Text::to_re, used for prefix `re`
1615 var to_re
: nullable CallSite = null
1616 # Regex::ignore_case, used for suffix `i` on `re`
1617 var ignore_case
: nullable CallSite = null
1618 # Regex::newline, used for suffix `m` on `re`
1619 var newline
: nullable CallSite = null
1620 # Regex::extended, used for suffix `b` on `re`
1621 var extended
: nullable CallSite = null
1622 # CString::to_bytes_with_copy, used for prefix `b`
1623 var to_bytes_with_copy
: nullable CallSite = null
1625 redef fun accept_typing
(v
) do
1626 var mclass
= v
.get_mclass
(self, "String")
1627 if mclass
== null then return # Forward error
1628 if is_bytestring
then
1629 to_bytes_with_copy
= v
.build_callsite_by_name
(self, v
.mmodule
.c_string_type
, "to_bytes_with_copy", false)
1630 mclass
= v
.get_mclass
(self, "Bytes")
1632 to_re
= v
.build_callsite_by_name
(self, mclass
.mclass_type
, "to_re", false)
1633 for i
in suffix
.chars
do
1634 mclass
= v
.get_mclass
(self, "Regex")
1635 if mclass
== null then
1636 v
.error
(self, "Error: `Regex` class unknown")
1641 service
= "ignore_case="
1642 ignore_case
= v
.build_callsite_by_name
(self, mclass
.mclass_type
, service
, false)
1643 else if i
== 'm' then
1644 service
= "newline="
1645 newline
= v
.build_callsite_by_name
(self, mclass
.mclass_type
, service
, false)
1646 else if i
== 'b' then
1647 service
= "extended="
1648 extended
= v
.build_callsite_by_name
(self, mclass
.mclass_type
, service
, false)
1650 v
.error
(self, "Type Error: Unrecognized suffix {i} in prefixed Regex")
1655 if mclass
== null then return # Forward error
1656 mtype
= mclass
.mclass_type
1660 redef class ASuperstringExpr
1661 redef fun accept_typing
(v
)
1664 var objclass
= v
.get_mclass
(self, "Object")
1665 if objclass
== null then return # Forward error
1666 var objtype
= objclass
.mclass_type
1667 for nexpr
in self.n_exprs
do
1668 v
.visit_expr_subtype
(nexpr
, objtype
)
1673 redef class AArrayExpr
1674 # The `with_capacity` method on Array
1675 var with_capacity_callsite
: nullable CallSite
1677 # The `push` method on arrays
1678 var push_callsite
: nullable CallSite
1680 # The element of each type
1681 var element_mtype
: nullable MType
1683 # Set that `self` is a part of comprehension array `na`
1684 # If `self` is a `for`, or a `if`, then `set_comprehension` is recursively applied.
1685 private fun set_comprehension
(n
: nullable AExpr)
1689 else if n
isa AForExpr then
1690 set_comprehension
(n
.n_block
)
1691 else if n
isa AIfExpr then
1692 set_comprehension
(n
.n_then
)
1693 set_comprehension
(n
.n_else
)
1696 n
.comprehension
= self
1699 redef fun accept_typing
(v
)
1701 var mtype
: nullable MType = null
1702 var ntype
= self.n_type
1703 if ntype
!= null then
1704 mtype
= v
.resolve_mtype
(ntype
)
1705 if mtype
== null then return # Skip error
1707 var mtypes
= new Array[nullable MType]
1709 for e
in self.n_exprs
do
1710 var t
= v
.visit_expr
(e
)
1714 set_comprehension
(e
)
1715 if mtype
!= null then
1716 if v
.check_subtype
(e
, t
, mtype
, false) == null then return # Forward error
1717 if t
== mtype
then useless
= true
1722 if mtype
== null then
1723 # Ensure monotony for type adaptation on loops
1724 if self.element_mtype
!= null then mtypes
.add
self.element_mtype
1725 mtype
= v
.merge_types
(self, mtypes
)
1727 if mtype
== null or mtype
isa MNullType then
1728 v
.error
(self, "Type Error: ambiguous array type {mtypes.join(" ")}")
1732 assert ntype
!= null
1733 v
.modelbuilder
.warning
(ntype
, "useless-type", "Warning: useless type declaration `{mtype}` in literal Array since it can be inferred from the elements type.")
1736 self.element_mtype
= mtype
1738 var mclass
= v
.get_mclass
(self, "Array")
1739 if mclass
== null then return # Forward error
1740 var array_mtype
= mclass
.get_mtype
([mtype
])
1742 with_capacity_callsite
= v
.build_callsite_by_name
(self, array_mtype
, "with_capacity", false)
1743 push_callsite
= v
.build_callsite_by_name
(self, array_mtype
, "push", false)
1745 self.mtype
= array_mtype
1749 redef class ARangeExpr
1750 var init_callsite
: nullable CallSite
1752 redef fun accept_typing
(v
)
1754 var discrete_class
= v
.get_mclass
(self, "Discrete")
1755 if discrete_class
== null then return # Forward error
1756 var discrete_type
= discrete_class
.intro
.bound_mtype
1757 var t1
= v
.visit_expr_subtype
(self.n_expr
, discrete_type
)
1758 var t2
= v
.visit_expr_subtype
(self.n_expr2
, discrete_type
)
1759 if t1
== null or t2
== null then return
1760 var mclass
= v
.get_mclass
(self, "Range")
1761 if mclass
== null then return # Forward error
1763 if v
.is_subtype
(t1
, t2
) then
1764 mtype
= mclass
.get_mtype
([t2
])
1765 else if v
.is_subtype
(t2
, t1
) then
1766 mtype
= mclass
.get_mtype
([t1
])
1768 v
.error
(self, "Type Error: cannot create range: `{t1}` vs `{t2}`.")
1774 # get the constructor
1776 if self isa ACrangeExpr then
1777 callsite
= v
.build_callsite_by_name
(self, mtype
, "init", false)
1778 else if self isa AOrangeExpr then
1779 callsite
= v
.build_callsite_by_name
(self, mtype
, "without_last", false)
1783 init_callsite
= callsite
1787 redef class ANullExpr
1788 redef fun accept_typing
(v
)
1790 self.mtype
= v
.mmodule
.model
.null_type
1794 redef class AIsaExpr
1795 # The static type to cast to.
1796 # (different from the static type of the expression that is `Bool`).
1797 var cast_type
: nullable MType
1798 redef fun accept_typing
(v
)
1800 v
.visit_expr
(n_expr
)
1802 var mtype
= v
.resolve_mtype
(n_type
)
1804 self.cast_type
= mtype
1806 var variable
= self.n_expr
.its_variable
1807 if variable
!= null then
1808 var orig
= self.n_expr
.mtype
1809 #var from = if orig != null then orig.to_s else "invalid"
1810 #var to = if mtype != null then mtype.to_s else "invalid"
1811 #debug("adapt {variable}: {from} -> {to}")
1813 var thentype
= v
.intersect_types
(self, orig
, mtype
)
1814 if thentype
!= orig
then
1815 self.after_flow_context
.when_true
.set_var
(v
, variable
, thentype
)
1816 #debug "{variable}:{orig or else "?"} isa {mtype or else "?"} -> then {thentype or else "?"}"
1819 var elsetype
= v
.diff_types
(self, orig
, mtype
)
1820 if elsetype
!= orig
then
1821 self.after_flow_context
.when_false
.set_var
(v
, variable
, elsetype
)
1822 #debug "{variable}:{orig or else "?"} isa {mtype or else "?"} -> else {elsetype or else "?"}"
1826 self.mtype
= v
.type_bool
(self)
1829 redef fun accept_post_typing
(v
)
1831 v
.check_expr_cast
(self, self.n_expr
, self.n_type
)
1834 redef fun dump_info
(v
) do
1836 var mtype
= self.cast_type
1837 if mtype
!= null then
1838 res
+= v
.yellow
(".as({mtype})")
1845 redef class AAsCastExpr
1846 redef fun accept_typing
(v
)
1848 v
.visit_expr
(n_expr
)
1850 self.mtype
= v
.resolve_mtype
(n_type
)
1853 redef fun accept_post_typing
(v
)
1855 v
.check_expr_cast
(self, self.n_expr
, self.n_type
)
1859 redef class AAsNotnullExpr
1860 redef fun accept_typing
(v
)
1862 var mtype
= v
.visit_expr
(self.n_expr
)
1863 if mtype
== null then return # Forward error
1865 if mtype
isa MNullType then
1866 v
.error
(self, "Type Error: `as(not null)` on `null`.")
1870 if v
.can_be_null
(mtype
) then
1871 mtype
= mtype
.as_notnull
1877 redef fun accept_post_typing
(v
)
1879 var mtype
= n_expr
.mtype
1880 if mtype
== null then return
1881 v
.check_can_be_null
(n_expr
, mtype
)
1885 redef class AParExpr
1886 redef fun accept_typing
(v
)
1888 self.mtype
= v
.visit_expr
(self.n_expr
)
1892 redef class AOnceExpr
1893 redef fun accept_typing
(v
)
1895 self.mtype
= v
.visit_expr
(self.n_expr
)
1899 redef class ASelfExpr
1900 redef var its_variable
: nullable Variable
1901 redef fun accept_typing
(v
)
1903 if v
.is_toplevel_context
and not self isa AImplicitSelfExpr then
1904 v
.error
(self, "Error: `self` cannot be used in top-level method.")
1906 var variable
= v
.selfvariable
1907 self.its_variable
= variable
1908 self.mtype
= v
.get_variable
(self, variable
)
1912 redef class AImplicitSelfExpr
1913 # Is the implicit receiver `sys`?
1915 # By default, the implicit receiver is `self`.
1916 # But when there is not method for `self`, `sys` is used as a fall-back.
1917 # Is this case this flag is set to `true`.
1921 ## MESSAGE SENDING AND PROPERTY
1923 redef class ASendExpr
1924 # The property invoked by the send.
1925 var callsite
: nullable CallSite
1927 # Is self a safe call (with `x?.foo`)?
1928 # If so and the receiver is null, then the arguments won't be evaluated
1929 # and the call skipped (replaced with null).
1930 var is_safe
: Bool = false
1932 redef fun bad_expr_message
(child
)
1934 if child
== self.n_expr
then
1935 return "to be the receiver of `{self.property_name}`"
1940 redef fun accept_typing
(v
)
1942 var nrecv
= self.n_expr
1943 var recvtype
= v
.visit_expr
(nrecv
)
1945 if nrecv
isa ASafeExpr then
1946 # Has the receiver the form `x?.foo`?
1947 # For parsing "reasons" the `?` is in the receiver node, not the call node.
1951 var name
= self.property_name
1952 var node
= self.property_node
1954 if recvtype
== null then return # Forward error
1957 var unsafe_type
= v
.anchor_to
(recvtype
)
1958 var mproperty
= v
.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
1959 if mproperty
== null and nrecv
isa AImplicitSelfExpr then
1960 # Special fall-back search in `sys` when noting found in the implicit receiver.
1961 var sysclass
= v
.try_get_mclass
(node
, "Sys")
1962 if sysclass
!= null then
1963 var systype
= sysclass
.mclass_type
1964 mproperty
= v
.try_get_mproperty_by_name2
(node
, systype
, name
)
1965 if mproperty
!= null then
1966 callsite
= v
.build_callsite_by_name
(node
, systype
, name
, false)
1967 if callsite
== null then return # Forward error
1968 # Update information, we are looking at `sys` now, not `self`
1970 nrecv
.its_variable
= null
1971 nrecv
.mtype
= systype
1976 if callsite
== null then
1977 # If still nothing, just exit
1978 callsite
= v
.build_callsite_by_name
(node
, recvtype
, name
, nrecv
isa ASelfExpr)
1979 if callsite
== null then return
1982 self.callsite
= callsite
1983 var msignature
= callsite
.msignature
1985 var args
= compute_raw_arguments
1987 if not self isa ACallrefExpr then
1988 callsite
.check_signature
(v
, node
, args
)
1991 if callsite
.mproperty
.is_init
then
1992 var vmpropdef
= v
.mpropdef
1993 if not (vmpropdef
isa MMethodDef and vmpropdef
.mproperty
.is_init
) then
1994 v
.error
(node
, "Error: an `init` can only be called from another `init`.")
1996 if vmpropdef
isa MMethodDef and vmpropdef
.mproperty
.is_root_init
and not callsite
.mproperty
.is_root_init
then
1997 v
.error
(node
, "Error: `{vmpropdef}` cannot call a factory `{callsite.mproperty}`.")
2001 var ret
= msignature
.return_mtype
2004 # A safe receiver makes that the call is not executed and returns null
2005 ret
= ret
.as_nullable
2009 self.is_typed
= true
2013 # The name of the property
2014 # Each subclass simply provide the correct name.
2015 private fun property_name
: String is abstract
2017 # The node identifying the name (id, operator, etc) for messages.
2019 # Is `self` by default
2020 private fun property_node
: ANode do return self
2022 # An array of all arguments (excluding self)
2023 fun raw_arguments
: Array[AExpr] do return compute_raw_arguments
2025 private fun compute_raw_arguments
: Array[AExpr] is abstract
2027 redef fun dump_info
(v
) do
2029 var callsite
= self.callsite
2030 if callsite
!= null then
2031 res
+= v
.yellow
(" call="+callsite
.dump_info
(v
))
2037 redef class ABinopExpr
2038 redef fun compute_raw_arguments
do return [n_expr2
]
2039 redef fun property_name
do return operator
2040 redef fun property_node
do return n_op
2043 redef class AEqFormExpr
2044 redef fun accept_typing
(v
)
2050 redef fun accept_post_typing
(v
)
2052 var mtype
= n_expr
.mtype
2053 var mtype2
= n_expr2
.mtype
2055 if mtype
== null or mtype2
== null then return
2057 if mtype
== v
.type_bool
(self) and (n_expr2
isa AFalseExpr or n_expr2
isa ATrueExpr) then
2058 v
.modelbuilder
.warning
(self, "useless-truism", "Warning: useless comparison to a Bool literal.")
2061 if not mtype2
isa MNullType then return
2063 v
.check_can_be_null
(n_expr
, mtype
)
2067 redef class AUnaryopExpr
2068 redef fun property_name
do return "unary {operator}"
2069 redef fun compute_raw_arguments
do return new Array[AExpr]
2072 redef class ACallExpr
2073 redef fun property_name
do return n_qid
.n_id
.text
2074 redef fun property_node
do return n_qid
2075 redef fun compute_raw_arguments
do return n_args
.to_a
2078 redef class ACallAssignExpr
2079 redef fun property_name
do return n_qid
.n_id
.text
+ "="
2080 redef fun property_node
do return n_qid
2081 redef fun compute_raw_arguments
2083 var res
= n_args
.to_a
2089 redef class ABraExpr
2090 redef fun property_name
do return "[]"
2091 redef fun compute_raw_arguments
do return n_args
.to_a
2094 redef class ABraAssignExpr
2095 redef fun property_name
do return "[]="
2096 redef fun compute_raw_arguments
2098 var res
= n_args
.to_a
2104 redef class ASendReassignFormExpr
2105 # The property invoked for the writing
2106 var write_callsite
: nullable CallSite
2108 redef fun accept_typing
(v
)
2110 var recvtype
= v
.visit_expr
(self.n_expr
)
2111 var name
= self.property_name
2112 var node
= self.property_node
2114 if recvtype
== null then return # Forward error
2116 var for_self
= self.n_expr
isa ASelfExpr
2117 var callsite
= v
.build_callsite_by_name
(node
, recvtype
, name
, for_self
)
2119 if callsite
== null then return
2120 self.callsite
= callsite
2122 var args
= compute_raw_arguments
2124 callsite
.check_signature
(v
, node
, args
)
2126 var readtype
= callsite
.msignature
.return_mtype
2127 if readtype
== null then
2128 v
.error
(node
, "Error: `{name}` is not a function.")
2132 var wcallsite
= v
.build_callsite_by_name
(node
, recvtype
, name
+ "=", self.n_expr
isa ASelfExpr)
2133 if wcallsite
== null then return
2134 self.write_callsite
= wcallsite
2136 var wtype
= self.resolve_reassignment
(v
, readtype
, wcallsite
.msignature
.mparameters
.last
.mtype
)
2137 if wtype
== null then return
2139 args
= args
.to_a
# duplicate so raw_arguments keeps only the getter args
2140 args
.add
(self.n_value
)
2141 wcallsite
.check_signature
(v
, node
, args
)
2143 self.is_typed
= true
2147 redef class ACallReassignExpr
2148 redef fun property_name
do return n_qid
.n_id
.text
2149 redef fun property_node
do return n_qid
.n_id
2150 redef fun compute_raw_arguments
do return n_args
.to_a
2153 redef class ABraReassignExpr
2154 redef fun property_name
do return "[]"
2155 redef fun compute_raw_arguments
do return n_args
.to_a
2158 redef class AInitExpr
2159 redef fun property_name
do return "init"
2160 redef fun property_node
do return n_kwinit
2161 redef fun compute_raw_arguments
do return n_args
.to_a
2164 redef class ACallrefExpr
2165 redef fun property_name
do return n_qid
.n_id
.text
2166 redef fun property_node
do return n_qid
2167 redef fun compute_raw_arguments
do return n_args
.to_a
2169 redef fun accept_typing
(v
)
2171 super # do the job as if it was a real call
2172 var res
= callsite
.mproperty
2174 var msignature
= callsite
.mpropdef
.msignature
2175 var recv
= callsite
.recv
2176 assert msignature
!= null
2177 var arity
= msignature
.mparameters
.length
2179 var routine_type_name
= "ProcRef"
2180 if msignature
.return_mtype
!= null then
2181 routine_type_name
= "FunRef"
2184 var target_routine_class
= "{routine_type_name}{arity}"
2185 var routine_mclass
= v
.get_mclass
(self, target_routine_class
)
2187 if routine_mclass
== null then
2188 v
.error
(self, "Error: missing functional types, try `import functional`")
2192 var types_list
= new Array[MType]
2193 for param
in msignature
.mparameters
do
2194 if param
.is_vararg
then
2195 types_list
.push
(v
.mmodule
.array_type
(param
.mtype
))
2197 types_list
.push
(param
.mtype
)
2200 if msignature
.return_mtype
!= null then
2201 types_list
.push
(msignature
.return_mtype
.as(not null))
2204 # Why we need an anchor :
2208 # def toto(x: E) do print "{x}"
2211 # var a = new A[Int]
2212 # var f = &a.toto # without anchor : ProcRef1[E]
2213 # # with anchor : ProcRef[Int]
2215 # However, we can only anchor if we can resolve every formal
2216 # parameter, here's an example where we can't.
2219 # fun bar: A[E] do return self
2220 # fun foo: Fun0[A[E]] do return &bar # here we can't anchor
2222 # var f1 = a1.foo # when this expression will be evaluated,
2223 # # `a1` will anchor `&bar` returned by `foo`.
2226 var routine_type
= routine_mclass
.get_mtype
(types_list
)
2227 if not recv
.need_anchor
then
2228 routine_type
= routine_type
.anchor_to
(v
.mmodule
, recv
.as(MClassType))
2231 self.mtype
= routine_type
2236 fun to_a
: Array[AExpr] do return self.n_exprs
.to_a
2241 redef class ASuperExpr
2242 # The method to call if the super is in fact a 'super init call'
2243 # Note: if the super is a normal call-next-method, then this attribute is null
2244 var callsite
: nullable CallSite
2246 # The method to call is the super is a standard `call-next-method` super-call
2247 # Note: if the super is a special super-init-call, then this attribute is null
2248 var mpropdef
: nullable MMethodDef
2250 redef fun accept_typing
(v
)
2252 var anchor
= v
.anchor
2253 var recvtype
= v
.get_variable
(self, v
.selfvariable
)
2254 assert recvtype
!= null
2255 var mproperty
= v
.mpropdef
.mproperty
2256 if not mproperty
isa MMethod then
2257 v
.error
(self, "Error: `super` only usable in a `method`.")
2260 var superprops
= mproperty
.lookup_super_definitions
(v
.mmodule
, anchor
)
2261 if superprops
.length
== 0 then
2262 if mproperty
.is_init
and v
.mpropdef
.is_intro
then
2263 process_superinit
(v
)
2266 v
.error
(self, "Error: no super method to call for `{mproperty}`.")
2269 # FIXME: covariance of return type in linear extension?
2270 var superprop
= superprops
.first
2272 var msignature
= superprop
.msignature
.as(not null)
2273 msignature
= v
.resolve_for
(msignature
, recvtype
, true).as(MSignature)
2274 var args
= self.n_args
.to_a
2275 if args
.length
> 0 then
2276 signaturemap
= v
.check_signature
(self, args
, mproperty
, msignature
)
2278 self.mtype
= msignature
.return_mtype
2279 self.is_typed
= true
2280 v
.mpropdef
.has_supercall
= true
2281 mpropdef
= v
.mpropdef
.as(MMethodDef)
2284 # The mapping used on the call to associate arguments to parameters.
2285 # If null then no specific association is required.
2286 var signaturemap
: nullable SignatureMap
2288 private fun process_superinit
(v
: TypeVisitor)
2290 var anchor
= v
.anchor
2291 var recvtype
= v
.get_variable
(self, v
.selfvariable
)
2292 assert recvtype
!= null
2293 var mpropdef
= v
.mpropdef
2294 assert mpropdef
isa MMethodDef
2295 var mproperty
= mpropdef
.mproperty
2296 var superprop
: nullable MMethodDef = null
2297 for msupertype
in mpropdef
.mclassdef
.supertypes
do
2298 msupertype
= msupertype
.anchor_to
(v
.mmodule
, anchor
)
2299 var errcount
= v
.modelbuilder
.toolcontext
.error_count
2300 var candidate
= v
.try_get_mproperty_by_name2
(self, msupertype
, mproperty
.name
).as(nullable MMethod)
2301 if candidate
== null then
2302 if v
.modelbuilder
.toolcontext
.error_count
> errcount
then return # Forward error
2303 continue # Try next super-class
2305 if superprop
!= null and candidate
.is_root_init
then
2308 if superprop
!= null and superprop
.mproperty
!= candidate
and not superprop
.mproperty
.is_root_init
then
2309 v
.error
(self, "Error: conflicting super constructor to call for `{mproperty}`: `{candidate.full_name}`, `{superprop.mproperty.full_name}`")
2312 var candidatedefs
= candidate
.lookup_definitions
(v
.mmodule
, anchor
)
2313 if superprop
!= null and superprop
.mproperty
== candidate
then
2314 if superprop
== candidatedefs
.first
then continue
2315 candidatedefs
.add
(superprop
)
2317 if candidatedefs
.length
> 1 then
2318 v
.error
(self, "Error: conflicting property definitions for property `{mproperty}` in `{recvtype}`: {candidatedefs.join(", ")}")
2321 superprop
= candidatedefs
.first
2323 if superprop
== null then
2324 v
.error
(self, "Error: no super method to call for `{mproperty}`.")
2328 var msignature
= superprop
.new_msignature
or else superprop
.msignature
.as(not null)
2329 msignature
= v
.resolve_for
(msignature
, recvtype
, true).as(MSignature)
2331 var callsite
= new CallSite(hot_location
, recvtype
, v
.mmodule
, v
.anchor
, true, superprop
.mproperty
, superprop
, msignature
, false)
2332 self.callsite
= callsite
2334 var args
= self.n_args
.to_a
2335 if args
.length
> 0 then
2336 callsite
.check_signature
(v
, self, args
)
2338 # Check there is at least enough parameters
2339 if mpropdef
.msignature
.arity
< msignature
.arity
then
2340 v
.error
(self, "Error: not enough implicit arguments to pass. Got `{mpropdef.msignature.arity}`, expected at least `{msignature.arity}`. Signature is `{msignature}`.")
2343 # Check that each needed parameter is conform
2345 for sp
in msignature
.mparameters
do
2346 var p
= mpropdef
.msignature
.mparameters
[i
]
2347 if not v
.is_subtype
(p
.mtype
, sp
.mtype
) then
2348 v
.error
(self, "Type Error: expected argument #{i} of type `{sp.mtype}`, got implicit argument `{p.name}` of type `{p.mtype}`. Signature is {msignature}")
2355 self.is_typed
= true
2358 redef fun dump_info
(v
) do
2360 var callsite
= self.callsite
2361 if callsite
!= null then
2362 res
+= v
.yellow
(" super-init="+callsite
.dump_info
(v
))
2364 var mpropdef
= self.mpropdef
2365 if mpropdef
!= null then
2366 res
+= v
.yellow
(" call-next-method="+mpropdef
.to_s
)
2374 redef class ANewExpr
2375 # The constructor invoked by the new.
2376 var callsite
: nullable CallSite
2378 # The designated type
2379 var recvtype
: nullable MClassType
2381 redef fun accept_typing
(v
)
2383 var recvtype
= v
.resolve_mtype
(self.n_type
)
2384 if recvtype
== null then return
2386 if not recvtype
isa MClassType then
2387 if recvtype
isa MNullableType then
2388 v
.error
(self, "Type Error: cannot instantiate the nullable type `{recvtype}`.")
2390 else if recvtype
isa MFormalType then
2391 v
.error
(self, "Type Error: cannot instantiate the formal type `{recvtype}`.")
2394 v
.error
(self, "Type Error: cannot instantiate the type `{recvtype}`.")
2399 self.recvtype
= recvtype
2400 var kind
= recvtype
.mclass
.kind
2403 var nqid
= self.n_qid
2405 if nqid
!= null then
2406 name
= nqid
.n_id
.text
2412 if name
== "intern" then
2413 if kind
!= concrete_kind
then
2414 v
.error
(self, "Type Error: cannot instantiate {kind} {recvtype}.")
2417 if n_args
.n_exprs
.not_empty
then
2418 v
.error
(n_args
, "Type Error: the intern constructor expects no arguments.")
2422 self.mtype
= recvtype
2426 var callsite
= v
.build_callsite_by_name
(node
, recvtype
, name
, false)
2427 if callsite
== null then return
2429 if not callsite
.mproperty
.is_new
then
2430 if kind
!= concrete_kind
then
2431 v
.error
(self, "Type Error: cannot instantiate {kind} `{recvtype}`.")
2434 self.mtype
= recvtype
2436 self.mtype
= callsite
.msignature
.return_mtype
2437 assert self.mtype
!= null
2440 self.callsite
= callsite
2442 if not callsite
.mproperty
.is_init_for
(recvtype
.mclass
) then
2443 v
.error
(self, "Error: `{name}` is not a constructor.")
2447 var args
= n_args
.to_a
2448 callsite
.check_signature
(v
, node
, args
)
2451 redef fun dump_info
(v
) do
2453 var callsite
= self.callsite
2454 if callsite
!= null then
2455 res
+= v
.yellow
(" call="+callsite
.dump_info
(v
))
2463 redef class AAttrFormExpr
2464 # The attribute accessed.
2465 var mproperty
: nullable MAttribute
2467 # The static type of the attribute.
2468 var attr_type
: nullable MType
2470 # Resolve the attribute accessed.
2471 private fun resolve_property
(v
: TypeVisitor)
2473 var recvtype
= v
.visit_expr
(self.n_expr
)
2474 if recvtype
== null then return # Skip error
2475 var node
= self.n_id
2476 var name
= node
.text
2477 if recvtype
isa MNullType then
2478 v
.error
(node
, "Error: attribute `{name}` access on `null`.")
2482 var unsafe_type
= v
.anchor_to
(recvtype
)
2483 var mproperty
= v
.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
2484 if mproperty
== null then
2485 v
.modelbuilder
.error
(node
, "Error: attribute `{name}` does not exist in `{recvtype}`.")
2488 assert mproperty
isa MAttribute
2489 self.mproperty
= mproperty
2491 var mpropdefs
= mproperty
.lookup_definitions
(v
.mmodule
, unsafe_type
)
2492 assert mpropdefs
.length
== 1
2493 var mpropdef
= mpropdefs
.first
2494 var attr_type
= mpropdef
.static_mtype
2495 if attr_type
== null then return # skip error
2496 attr_type
= v
.resolve_for
(attr_type
, recvtype
, self.n_expr
isa ASelfExpr)
2497 self.attr_type
= attr_type
2500 redef fun dump_info
(v
) do
2502 var mproperty
= self.mproperty
2503 var attr_type
= self.attr_type
2504 if mproperty
!= null then
2505 res
+= v
.yellow
(" attr={mproperty}:{attr_type or else "BROKEN"}")
2511 redef class AAttrExpr
2512 redef fun accept_typing
(v
)
2514 self.resolve_property
(v
)
2515 self.mtype
= self.attr_type
2519 redef class AAttrAssignExpr
2520 redef fun accept_typing
(v
)
2522 self.resolve_property
(v
)
2523 var mtype
= self.attr_type
2525 v
.visit_expr_subtype
(self.n_value
, mtype
)
2526 self.is_typed
= mtype
!= null
2530 redef class AAttrReassignExpr
2531 redef fun accept_typing
(v
)
2533 self.resolve_property
(v
)
2534 var mtype
= self.attr_type
2535 if mtype
== null then return # Skip error
2537 var rettype
= self.resolve_reassignment
(v
, mtype
, mtype
)
2539 self.is_typed
= rettype
!= null
2543 redef class AIssetAttrExpr
2544 redef fun accept_typing
(v
)
2546 self.resolve_property
(v
)
2547 var mtype
= self.attr_type
2548 if mtype
== null then return # Skip error
2550 var recvtype
= self.n_expr
.mtype
.as(not null)
2551 var bound
= v
.resolve_for
(mtype
, recvtype
, false)
2552 if bound
isa MNullableType then
2553 v
.error
(n_id
, "Type Error: `isset` on a nullable attribute.")
2555 self.mtype
= v
.type_bool
(self)
2559 redef class ASafeExpr
2560 redef fun accept_typing
(v
)
2562 var mtype
= v
.visit_expr
(n_expr
)
2563 if mtype
== null then return # Skip error
2565 if mtype
isa MNullType then
2566 # While `null?.foo` is semantically well defined and should not execute `foo` and just return `null`,
2567 # currently `null.foo` is forbidden so it seems coherent to also forbid `null?.foo`
2568 v
.modelbuilder
.error
(self, "Error: safe operator `?` on `null`.")
2572 self.mtype
= mtype
.as_notnull
2574 if not v
.can_be_null
(mtype
) then
2575 v
.modelbuilder
.warning
(self, "useless-safe", "Warning: useless safe operator `?` on non-nullable value.")
2581 redef class AVarargExpr
2582 redef fun accept_typing
(v
)
2584 # This kind of pseudo-expression can be only processed trough a signature
2585 # See `check_signature`
2586 # Other cases are a syntax error.
2587 v
.error
(self, "Syntax Error: unexpected `...`.")
2593 redef class ADebugTypeExpr
2594 redef fun accept_typing
(v
)
2596 var expr
= v
.visit_expr
(self.n_expr
)
2597 if expr
== null then return
2598 var unsafe
= v
.anchor_to
(expr
)
2599 var ntype
= self.n_type
2600 var mtype
= v
.resolve_mtype
(ntype
)
2601 if mtype
!= null and mtype
!= expr
then
2602 var umtype
= v
.anchor_to
(mtype
)
2603 v
.modelbuilder
.warning
(self, "debug", "Found type {expr} (-> {unsafe}), expected {mtype} (-> {umtype})")
2605 self.is_typed
= true