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 self.modelbuilder
.error
(node
, "Error: method or variable `{name}` unknown in `{recvtype}`.")
329 else if recvtype
.need_anchor
then
330 self.modelbuilder
.error
(node
, "Error: method `{name}` does not exists in `{recvtype}: {unsafe_type}`.")
332 self.modelbuilder
.error
(node
, "Error: method `{name}` does not exists in `{recvtype}`.")
337 assert mproperty
isa MMethod
339 return build_callsite_by_property
(node
, recvtype
, mproperty
, recv_is_self
)
342 # The `build_callsite_by_property` finds the mpropdefs to call by the `MMethod`.
343 # If the mpropdef is found in the context it builds a new `Callsite`.
344 fun build_callsite_by_property
(node
: ANode, recvtype
: MType, mproperty
: MMethod, recv_is_self
: Bool): nullable CallSite
346 var unsafe_type
= self.anchor_to
(recvtype
)
348 if recvtype
isa MNullType then
349 var objclass
= get_mclass
(node
, "Object")
350 if objclass
== null then return null # Forward error
351 unsafe_type
= objclass
.mclass_type
353 # `null` only accepts some methods of object.
354 if recvtype
isa MNullType and not mproperty
.is_null_safe
then
355 self.error
(node
, "Error: method `{mproperty.name}` called on `null`.")
357 else if unsafe_type
isa MNullableType and not mproperty
.is_null_safe
then
358 modelbuilder
.advice
(node
, "call-on-nullable", "Warning: method call on a nullable receiver `{recvtype}`.")
361 if is_toplevel_context
and recv_is_self
and not mproperty
.is_toplevel
then
362 error
(node
, "Error: `{mproperty.name}` is not a top-level method, thus need a receiver.")
364 if not recv_is_self
and mproperty
.is_toplevel
then
365 error
(node
, "Error: cannot call `{mproperty.name}`, a top-level method, with a receiver.")
368 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
369 self.modelbuilder
.error
(node
, "Error: method `{mproperty.name}` is protected and can only accessed by `self`.")
373 var info
= mproperty
.deprecation
374 if info
!= null and self.mpropdef
.mproperty
.deprecation
== null then
377 self.modelbuilder
.warning
(node
, "deprecated-method", "Deprecation Warning: method `{mproperty.name}` is deprecated: {mdoc.content.first}")
379 self.modelbuilder
.warning
(node
, "deprecated-method", "Deprecation Warning: method `{mproperty.name}` is deprecated.")
383 var propdefs
= mproperty
.lookup_definitions
(self.mmodule
, unsafe_type
)
385 if propdefs
.length
== 0 then
386 self.modelbuilder
.error
(node
, "Type Error: no definition found for property `{mproperty.name}` in `{unsafe_type}`.")
389 else if propdefs
.length
== 1 then
390 mpropdef
= propdefs
.first
392 self.modelbuilder
.warning
(node
, "property-conflict", "Warning: conflicting property definitions for property `{mproperty.name}` in `{unsafe_type}`: {propdefs.join(" ")}")
393 mpropdef
= mproperty
.intro
396 return build_callsite_by_propdef
(node
, recvtype
, mpropdef
, recv_is_self
)
399 # The `build_callsite_by_propdef` builds the callsite directly with the `mprodef` passed in argument.
400 fun build_callsite_by_propdef
(node
: ANode, recvtype
: MType, mpropdef
: MMethodDef, recv_is_self
: Bool): nullable CallSite
402 var msignature
= mpropdef
.msignature
403 if msignature
== null then return null # skip error
404 msignature
= resolve_for
(msignature
, recvtype
, recv_is_self
).as(MSignature)
406 var erasure_cast
= false
407 var rettype
= mpropdef
.msignature
.return_mtype
408 if not recv_is_self
and rettype
!= null then
409 rettype
= rettype
.undecorate
410 if rettype
isa MParameterType then
411 var erased_rettype
= msignature
.return_mtype
412 assert erased_rettype
!= null
413 #node.debug("Erasure cast: Really a {rettype} but unsafely a {erased_rettype}")
418 var callsite
= new CallSite(node
.hot_location
, recvtype
, mmodule
, anchor
, recv_is_self
, mpropdef
.mproperty
, mpropdef
, msignature
, erasure_cast
)
422 fun try_build_callsite_by_name
(node
: ANode, recvtype
: MType, name
: String, recv_is_self
: Bool): nullable CallSite
424 var unsafe_type
= self.anchor_to
(recvtype
)
425 var mproperty
= self.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
426 if mproperty
== null then return null
427 return build_callsite_by_name
(node
, recvtype
, name
, recv_is_self
)
430 # Visit the expressions of args and check their conformity with the corresponding type in signature
431 # The point of this method is to handle varargs correctly
432 # Note: The signature must be correctly adapted
433 fun check_signature
(node
: ANode, args
: Array[AExpr], mproperty
: MProperty, msignature
: MSignature): nullable SignatureMap
435 var vararg_rank
= msignature
.vararg_rank
436 if vararg_rank
>= 0 then
437 if args
.length
< msignature
.arity
then
438 modelbuilder
.error
(node
, "Error: expected at least {msignature.arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
441 else if args
.length
!= msignature
.arity
then
443 if args
.length
> msignature
.arity
then
444 modelbuilder
.error
(node
, "Error: expected {msignature.arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
447 # Other cases are managed later
450 #debug("CALL {unsafe_type}.{msignature}")
452 # Associate each parameter to a position in the arguments
453 var map
= new SignatureMap
455 # Special case for the isolated last argument
456 # TODO: reify this method characteristics (where? the param, the signature, the method?)
457 var last_is_padded
= mproperty
.name
.chars
.last
== '='
458 var nbargs
= args
.length
459 if last_is_padded
then
461 assert not args
.last
isa ANamedargExpr
462 map
.map
[msignature
.arity
- 1] = args
.length
- 1
463 self.visit_expr_subtype
(args
.last
, msignature
.mparameters
.last
.mtype
)
466 # First, handle named arguments
467 for i
in [0..args
.length
[ do
469 if not e
isa ANamedargExpr then continue
470 var name
= e
.n_id
.text
471 var param
= msignature
.mparameter_by_name
(name
)
472 if param
== null then
473 modelbuilder
.error
(e
.n_id
, "Error: no parameter `{name}` for `{mproperty}{msignature}`.")
476 var idx
= msignature
.mparameters
.index_of
(param
)
477 var prev
= map
.map
.get_or_null
(idx
)
479 modelbuilder
.error
(e
, "Error: parameter `{name}` already associated with argument #{prev} for `{mproperty}{msignature}`.")
483 e
.mtype
= self.visit_expr_subtype
(e
.n_expr
, param
.mtype
)
486 # Number of minimum mandatory remaining parameters
489 # Second, associate remaining parameters
490 var vararg_decl
= args
.length
- msignature
.arity
492 for i
in [0..msignature
.arity
[ do
493 # Skip parameters associated by name
494 if map
.map
.has_key
(i
) then continue
496 var param
= msignature
.mparameters
[i
]
498 # Search the next free argument: skip named arguments since they are already associated
499 while j
< nbargs
and args
[j
] isa ANamedargExpr do j
+= 1
501 if not param
.mtype
isa MNullableType then
511 if i
== vararg_rank
then
513 continue # skip the vararg
516 if not param
.is_vararg
then
517 var paramtype
= param
.mtype
518 self.visit_expr_subtype
(arg
, paramtype
)
520 check_one_vararg
(arg
, param
)
524 if min_arity
> 0 then
525 if last_is_padded
then min_arity
+= 1
526 if min_arity
< msignature
.arity
then
527 modelbuilder
.error
(node
, "Error: expected at least {min_arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
529 modelbuilder
.error
(node
, "Error: expected {min_arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
534 # Third, check varargs
535 if vararg_rank
>= 0 then
536 var paramtype
= msignature
.mparameters
[vararg_rank
].mtype
537 var first
= args
[vararg_rank
]
538 if vararg_decl
== 0 then
539 if not check_one_vararg
(first
, msignature
.mparameters
[vararg_rank
]) then return null
541 first
.vararg_decl
= vararg_decl
+ 1
542 for i
in [vararg_rank
..vararg_rank
+vararg_decl
] do
543 self.visit_expr_subtype
(args
[i
], paramtype
)
551 # Check an expression as a single vararg.
552 # The main point of the method if to handle the case of reversed vararg (see `AVarargExpr`)
553 fun check_one_vararg
(arg
: AExpr, param
: MParameter): Bool
555 var paramtype
= param
.mtype
556 var mclass
= get_mclass
(arg
, "Array")
557 if mclass
== null then return false # Forward error
558 var array_mtype
= mclass
.get_mtype
([paramtype
])
559 if arg
isa AVarargExpr then
560 self.visit_expr_subtype
(arg
.n_expr
, array_mtype
)
561 arg
.mtype
= arg
.n_expr
.mtype
563 # only one vararg, maybe `...` was forgot, so be gentle!
564 var t
= visit_expr
(arg
)
565 if t
== null then return false # Forward error
566 if not is_subtype
(t
, paramtype
) and is_subtype
(t
, array_mtype
) then
567 # Not acceptable but could be a `...`
568 error
(arg
, "Type Error: expected `{paramtype}`, got `{t}`. Is an ellipsis `...` missing on the argument?")
571 # Standard valid vararg, finish the job
573 self.visit_expr_subtype
(arg
, paramtype
)
578 fun error
(node
: ANode, message
: String)
580 self.modelbuilder
.error
(node
, message
)
583 fun get_variable
(node
: AExpr, variable
: Variable): nullable MType
585 if not variable
.is_adapted
then return variable
.declared_type
587 var flow
= node
.after_flow_context
588 if flow
== null then return null # skip error
590 if flow
.vars
.has_key
(variable
) then
591 return flow
.vars
[variable
]
593 #node.debug("*** START Collected for {variable}")
594 var mtypes
= flow
.collect_types
(variable
)
595 #node.debug("**** END Collected for {variable}")
596 if mtypes
.length
== 0 then
597 return variable
.declared_type
598 else if mtypes
.length
== 1 then
601 var res
= merge_types
(node
,mtypes
)
603 res
= variable
.declared_type
604 # Try to fallback to a non-null version
605 if res
!= null and can_be_null
(res
) then do
607 if t
!= null and can_be_null
(t
) then break label
617 # Some variables where type-adapted during the visit
620 # Some loops had been visited during the visit
623 fun set_variable
(node
: AExpr, variable
: Variable, mtype
: nullable MType)
625 var flow
= node
.after_flow_context
628 flow
.set_var
(self, variable
, mtype
)
631 # Find the exact representable most specific common super-type in `col`.
633 # Try to find the most specific common type that is a super-type of each types
635 # In most cases, the result is simply the most general type in `col`.
636 # If nullables types are involved, then the nullable information is correctly preserved.
637 # If incomparable super-types exists in `col`, them no solution is given and the `null`
638 # value is returned (since union types are non representable in Nit)
640 # The `null` values in `col` are ignored, nulltypes (MNullType) are considered.
642 # Returns the `null` value if:
645 # * `col` only have null values
646 # * there is a conflict
648 # Example (with a diamond A,B,C,D):
650 # * merge(A,B,C) -> A, because A is the most general type in {A,B,C}
651 # * merge(C,B) -> null, there is conflict, because `B or C` cannot be represented
652 # * merge(A,nullable B) -> nullable A, because A is the most general type and
653 # the nullable information is preserved
654 fun merge_types
(node
: ANode, col
: Array[nullable MType]): nullable MType
656 if col
.length
== 1 then return col
.first
658 if t1
== null then continue # return null
661 if t2
== null then continue # return null
662 if can_be_null
(t2
) and not can_be_null
(t1
) then
665 if not is_subtype
(t2
, t1
) then found
= false
668 #print "merge {col.join(" ")} -> {t1}"
672 #self.modelbuilder.warning(node, "Type Error: {col.length} conflicting types: <{col.join(", ")}>")
676 # Find a most general common subtype between `type1` and `type2`.
678 # Find the most general type that is a subtype of `type2` and, if possible, a subtype of `type1`.
679 # Basically, this return the most specific type between `type1` and `type2`.
680 # If nullable types are involved, the information is correctly preserved.
681 # If `type1` and `type2` are incomparable then `type2` is preferred (since intersection types
682 # are not representable in Nit).
684 # The `null` value is returned if both `type1` and `type2` are null.
686 # Examples (with diamond A,B,C,D):
688 # * intersect_types(A,B) -> B, because B is a subtype of A
689 # * intersect_types(B,A) -> B, because B is a subtype of A
690 # * intersect_types(B,C) -> C, B and C are incomparable,
691 # `type2` is then preferred (`B and C` cannot be represented)
692 # * intersect_types(nullable B,A) -> B, because B<:A and the non-null information is preserved
693 # * intersect_types(B,nullable C) -> C, `type2` is preferred and the non-null information is preserved
694 fun intersect_types
(node
: ANode, type1
, type2
: nullable MType): nullable MType
696 if type1
== null then return type2
697 if type2
== null then return type1
699 if not can_be_null
(type2
) or not can_be_null
(type1
) then
700 type1
= type1
.as_notnull
701 type2
= type2
.as_notnull
705 if is_subtype
(type1
, type2
) then
713 # Find a most general type that is a subtype of `type1` but not one of `type2`.
715 # Basically, this returns `type1`-`type2` but since there is no substraction type
716 # in Nit this just returns `type1` most of the case.
718 # The few other cases are if `type2` is a super-type and if some nullable information
721 # The `null` value is returned if `type1` is null.
723 # Examples (with diamond A,B,C,D):
725 # * diff_types(A,B) -> A, because the notB cannot be represented
726 # * diff_types(B,A) -> None (absurd type), because B<:A
727 # * diff_types(nullable A, nullable B) -> A, because null is removed
728 # * diff_types(nullable B, A) -> Null, because anything but null is removed
729 fun diff_types
(node
: ANode, type1
, type2
: nullable MType): nullable MType
731 if type1
== null then return null
732 if type2
== null then return type1
734 # if t1 <: t2 then t1-t2 = bottom
735 if is_subtype
(type1
, type2
) then
736 return modelbuilder
.model
.null_type
.as_notnull
739 # else if t1 <: nullable t2 then t1-t2 = nulltype
740 if is_subtype
(type1
, type2
.as_nullable
) then
741 return modelbuilder
.model
.null_type
744 # else t2 can be null and type2 must accept null then null is excluded in t1
745 if can_be_null
(type1
) and (type2
isa MNullableType or type2
isa MNullType) then
746 return type1
.as_notnull
753 # Mapping between parameters and arguments in a call.
755 # Parameters and arguments are not stored in the class but referenced by their position (starting from 0)
757 # The point of this class is to help engine and other things to map arguments in the AST to parameters of the model.
759 # Associate a parameter to an argument
760 var map
= new ArrayMap[Int, Int]
763 # A specific method call site with its associated informations.
769 # The static type of the receiver (possibly unresolved)
772 # The module where the callsite is present
775 # The anchor to use with `recv` or `msignature`
776 var anchor
: nullable MClassType
778 # Is the receiver self?
779 # If "for_self", virtual types of the signature are kept
780 # If "not_for_self", virtual type are erased
781 var recv_is_self
: Bool
783 # The designated method
784 var mproperty
: MMethod
786 # The statically designated method definition
787 # The most specif one, it is.
788 var mpropdef
: MMethodDef
790 # The resolved signature for the receiver
791 var msignature
: MSignature
793 # Is a implicit cast required on erasure typing policy?
794 var erasure_cast
: Bool
796 # The mapping used on the call to associate arguments to parameters
797 # If null then no specific association is required.
798 var signaturemap
: nullable SignatureMap = null
800 private fun check_signature
(v
: TypeVisitor, node
: ANode, args
: Array[AExpr]): Bool
802 var map
= v
.check_signature
(node
, args
, self.mproperty
, self.msignature
)
804 if map
== null then is_broken
= true
808 # Information about the callsite to display on a node
809 fun dump_info
(v
: ASTDump): String do
810 return "{recv}.{mpropdef}{msignature}"
813 redef fun mdoc_or_fallback
do return mproperty
.intro
.mdoc
817 # The declared type of the variable
818 var declared_type
: nullable MType = null is writable
820 # Was the variable type-adapted?
821 # This is used to speedup type retrieval while it remains `false`
822 private var is_adapted
= false
825 redef class FlowContext
826 # Store changes of types because of type evolution
827 private var vars
= new HashMap[Variable, nullable MType]
829 # Adapt the variable to a static type
830 # Warning1: do not modify vars directly.
831 # Warning2: sub-flow may have cached a unadapted variable
832 private fun set_var
(v
: TypeVisitor, variable
: Variable, mtype
: nullable MType)
834 if variable
.declared_type
== mtype
and not variable
.is_adapted
then return
835 if vars
.has_key
(variable
) and vars
[variable
] == mtype
then return
836 self.vars
[variable
] = mtype
838 variable
.is_adapted
= true
839 #node.debug "set {variable} to {mtype or else "X"}"
842 # Look in the flow and previous flow and collect all first reachable type adaptation of a local variable
843 private fun collect_types
(variable
: Variable): Array[nullable MType]
845 #node.debug "flow for {variable}"
846 var res
= new Array[nullable MType]
849 var seen
= new HashSet[FlowContext]
850 while not todo
.is_empty
do
852 if f
.is_unreachable
then continue
853 if seen
.has
(f
) then continue
856 if f
.vars
.has_key
(variable
) then
857 # Found something. Collect it and do not process further on this path
858 res
.add f
.vars
[variable
]
859 #f.node.debug "process {variable}: got {f.vars[variable] or else "X"}"
861 todo
.add_all f
.previous
863 if f
.previous
.is_empty
then
864 # Root flowcontext mean a parameter or something related
865 res
.add variable
.declared_type
866 #f.node.debug "root process {variable}: got {variable.declared_type or else "X"}"
870 #self.node.debug "##### end flow for {variable}: {res.join(" ")}"
876 # The entry point of the whole typing analysis
877 fun do_typing
(modelbuilder
: ModelBuilder)
881 # The variable associated to the receiver (if any)
882 var selfvariable
: nullable Variable
885 redef class AMethPropdef
886 redef fun do_typing
(modelbuilder
: ModelBuilder)
888 var mpropdef
= self.mpropdef
889 if mpropdef
== null then return # skip error
891 var v
= new TypeVisitor(modelbuilder
, mpropdef
)
892 self.selfvariable
= v
.selfvariable
894 var mmethoddef
= self.mpropdef
.as(not null)
895 var msignature
= mmethoddef
.msignature
896 if msignature
== null then return # skip error
897 for i
in [0..msignature
.arity
[ do
898 var mtype
= msignature
.mparameters
[i
].mtype
899 if msignature
.vararg_rank
== i
then
900 var arrayclass
= v
.get_mclass
(self.n_signature
.n_params
[i
], "Array")
901 if arrayclass
== null then return # Skip error
902 mtype
= arrayclass
.get_mtype
([mtype
])
904 var variable
= self.n_signature
.n_params
[i
].variable
905 assert variable
!= null
906 variable
.declared_type
= mtype
909 var nblock
= self.n_block
910 if nblock
== null then return
915 if not v
.has_loop
or not v
.dirty
then break
918 var post_visitor
= new PostTypingVisitor(v
)
919 post_visitor
.enter_visit
(self)
921 if not nblock
.after_flow_context
.is_unreachable
and msignature
.return_mtype
!= null then
922 # We reach the end of the function without having a return, it is bad
923 v
.error
(self, "Error: reached end of function; expected `return` with a value.")
928 private class PostTypingVisitor
930 var type_visitor
: TypeVisitor
931 redef fun visit
(n
) do
933 n
.accept_post_typing
(type_visitor
)
934 if n
isa AExpr and n
.mtype
== null and not n
.is_typed
then
941 private fun accept_post_typing
(v
: TypeVisitor) do end
943 # An additional information message to explain the role of a child expression.
945 # The point of the method is to allow some kind of double dispatch so the parent
946 # choose how to describe its children.
947 private fun bad_expr_message
(child
: AExpr): nullable String do return null
950 redef class AAttrPropdef
951 redef fun do_typing
(modelbuilder
: ModelBuilder)
953 if not has_value
then return
955 var mpropdef
= self.mreadpropdef
956 if mpropdef
== null or mpropdef
.msignature
== null then return # skip error
958 var v
= new TypeVisitor(modelbuilder
, mpropdef
)
959 self.selfvariable
= v
.selfvariable
961 var nexpr
= self.n_expr
962 if nexpr
!= null then
963 var mtype
= self.mtype
964 v
.visit_expr_subtype
(nexpr
, mtype
)
966 var nblock
= self.n_block
967 if nblock
!= null then
969 if not nblock
.after_flow_context
.is_unreachable
then
970 # We reach the end of the init without having a return, it is bad
971 v
.error
(self, "Error: reached end of block; expected `return`.")
980 # The static type of the expression.
981 # null if self is a statement or in case of error
982 var mtype
: nullable MType = null
984 # Is the statement correctly typed?
985 # Used to distinguish errors and statements when `mtype == null`
986 var is_typed
: Bool = false
988 # If required, the following implicit cast `.as(XXX)`
989 # Such a cast may by required after evaluating the expression when
990 # a unsafe operation is detected (silently accepted by the Nit language).
991 # The attribute is computed by `check_subtype`
992 var implicit_cast_to
: nullable MType = null
994 # Return the variable read (if any)
995 # Used to perform adaptive typing
996 fun its_variable
: nullable Variable do return null
998 private fun accept_typing
(v
: TypeVisitor)
1000 v
.error
(self, "no implemented accept_typing for {self.class_name}")
1003 # Is non-null if `self` is a leaf of a comprehension array construction.
1004 # In this case, the enclosing literal array node is designated.
1005 # The result of the evaluation of `self` must be
1006 # stored inside the designated array (there is an implicit `push`)
1007 var comprehension
: nullable AArrayExpr = null
1009 # It indicates the number of arguments collected as a vararg.
1011 # When 0, the argument is used as is, without transformation.
1012 # When 1, the argument is transformed into an singleton array.
1013 # Above 1, the arguments and the next ones are transformed into a common array.
1015 # This attribute is meaning less on expressions not used as attributes.
1016 var vararg_decl
: Int = 0
1018 redef fun dump_info
(v
) do
1020 var mtype
= self.mtype
1021 if mtype
!= null then
1022 res
+= v
.yellow
(":{mtype}")
1024 var ict
= self.implicit_cast_to
1026 res
+= v
.yellow
("(.as({ict}))")
1032 redef class ABlockExpr
1033 redef fun accept_typing
(v
)
1035 for e
in self.n_expr
do v
.visit_stmt
(e
)
1036 self.is_typed
= true
1039 # The type of a blockexpr is the one of the last expression (or null if empty)
1042 if self.n_expr
.is_empty
then return null
1043 return self.n_expr
.last
.mtype
1047 redef class AVardeclExpr
1048 redef fun accept_typing
(v
)
1050 var variable
= self.variable
1051 if variable
== null then return # Skip error
1053 var ntype
= self.n_type
1054 var mtype
: nullable MType
1055 if ntype
== null then
1058 mtype
= v
.resolve_mtype
(ntype
)
1059 if mtype
== null then return # Skip error
1062 var nexpr
= self.n_expr
1063 if nexpr
!= null then
1064 if mtype
!= null then
1065 var etype
= v
.visit_expr_subtype
(nexpr
, mtype
)
1066 if etype
== mtype
then
1067 assert ntype
!= null
1068 v
.modelbuilder
.advice
(ntype
, "useless-type", "Warning: useless type definition for variable `{variable.name}`")
1071 mtype
= v
.visit_expr
(nexpr
)
1072 if mtype
== null then return # Skip error
1076 var decltype
= mtype
1077 if mtype
== null or mtype
isa MNullType then
1078 var objclass
= v
.get_mclass
(self, "Object")
1079 if objclass
== null then return # skip error
1080 decltype
= objclass
.mclass_type
.as_nullable
1081 if mtype
== null then mtype
= decltype
1084 variable
.declared_type
= decltype
1085 v
.set_variable
(self, variable
, mtype
)
1087 #debug("var {variable}: {mtype}")
1090 self.is_typed
= true
1094 redef class AVarExpr
1095 redef fun its_variable
do return self.variable
1096 redef fun accept_typing
(v
)
1098 var variable
= self.variable
1099 if variable
== null then return # Skip error
1101 var mtype
= v
.get_variable
(self, variable
)
1102 if mtype
!= null then
1103 #debug("{variable} is {mtype}")
1105 #debug("{variable} is untyped")
1112 redef class AVarAssignExpr
1113 redef fun accept_typing
(v
)
1115 var variable
= self.variable
1116 assert variable
!= null
1118 var mtype
= v
.visit_expr_subtype
(n_value
, variable
.declared_type
)
1120 v
.set_variable
(self, variable
, mtype
)
1122 self.is_typed
= true
1126 redef class AReassignFormExpr
1127 # The method designed by the reassign operator.
1128 var reassign_callsite
: nullable CallSite
1130 var read_type
: nullable MType = null
1132 # Determine the `reassign_property`
1133 # `readtype` is the type of the reading of the left value.
1134 # `writetype` is the type of the writing of the left value.
1135 # (Because of `ACallReassignExpr`, both can be different.
1136 # Return the static type of the value to store.
1137 private fun resolve_reassignment
(v
: TypeVisitor, readtype
, writetype
: MType): nullable MType
1139 var reassign_name
= self.n_assign_op
.operator
1141 self.read_type
= readtype
1143 var callsite
= v
.build_callsite_by_name
(self.n_assign_op
, readtype
, reassign_name
, false)
1144 if callsite
== null then return null # Skip error
1145 self.reassign_callsite
= callsite
1147 var msignature
= callsite
.msignature
1148 var rettype
= msignature
.return_mtype
1149 assert msignature
.arity
== 1 and rettype
!= null
1151 var value_type
= v
.visit_expr_subtype
(self.n_value
, msignature
.mparameters
.first
.mtype
)
1152 if value_type
== null then return null # Skip error
1154 v
.check_subtype
(self, rettype
, writetype
, false)
1159 redef class AVarReassignExpr
1160 redef fun accept_typing
(v
)
1162 var variable
= self.variable
1163 assert variable
!= null
1165 var readtype
= v
.get_variable
(self, variable
)
1166 if readtype
== null then return
1168 read_type
= readtype
1170 var writetype
= variable
.declared_type
1171 if writetype
== null then return
1173 var rettype
= self.resolve_reassignment
(v
, readtype
, writetype
)
1175 v
.set_variable
(self, variable
, rettype
)
1177 self.is_typed
= rettype
!= null
1181 redef class AContinueExpr
1182 redef fun accept_typing
(v
)
1184 var nexpr
= self.n_expr
1185 if nexpr
!= null then
1188 self.is_typed
= true
1192 redef class ABreakExpr
1193 redef fun accept_typing
(v
)
1195 var nexpr
= self.n_expr
1196 if nexpr
!= null then
1199 self.is_typed
= true
1203 redef class AReturnExpr
1204 redef fun accept_typing
(v
)
1206 var nexpr
= self.n_expr
1208 var mpropdef
= v
.mpropdef
1209 if mpropdef
isa MMethodDef then
1210 ret_type
= mpropdef
.msignature
.return_mtype
1211 else if mpropdef
isa MAttributeDef then
1212 ret_type
= mpropdef
.static_mtype
1216 if nexpr
!= null then
1217 if ret_type
!= null then
1218 v
.visit_expr_subtype
(nexpr
, ret_type
)
1221 v
.error
(nexpr
, "Error: `return` with value in a procedure.")
1224 else if ret_type
!= null then
1225 v
.error
(self, "Error: `return` without value in a function.")
1228 self.is_typed
= true
1232 redef class AAbortExpr
1233 redef fun accept_typing
(v
)
1235 self.is_typed
= true
1240 redef fun accept_typing
(v
)
1242 v
.visit_expr_bool
(n_expr
)
1244 v
.visit_stmt
(n_then
)
1245 v
.visit_stmt
(n_else
)
1247 self.is_typed
= true
1249 if n_then
!= null and n_else
== null then
1250 self.mtype
= n_then
.mtype
1255 redef class AIfexprExpr
1256 redef fun accept_typing
(v
)
1258 v
.visit_expr_bool
(n_expr
)
1260 var t1
= v
.visit_expr
(n_then
)
1261 var t2
= v
.visit_expr
(n_else
)
1263 if t1
== null or t2
== null then
1267 var t
= v
.merge_types
(self, [t1
, t2
])
1269 v
.error
(self, "Type Error: ambiguous type `{t1}` vs `{t2}`.")
1276 redef fun accept_typing
(v
)
1278 v
.visit_stmt
(n_block
)
1279 v
.visit_stmt
(n_catch
)
1280 self.is_typed
= true
1284 redef class AWhileExpr
1285 redef fun accept_typing
(v
)
1288 v
.visit_expr_bool
(n_expr
)
1289 v
.visit_stmt
(n_block
)
1290 self.is_typed
= true
1294 redef class ALoopExpr
1295 redef fun accept_typing
(v
)
1298 v
.visit_stmt
(n_block
)
1299 self.is_typed
= true
1303 redef class AForExpr
1304 redef fun accept_typing
(v
)
1308 for g
in n_groups
do
1309 var mtype
= v
.visit_expr
(g
.n_expr
)
1310 if mtype
== null then return
1311 g
.do_type_iterator
(v
, mtype
)
1312 if g
.is_broken
then is_broken
= true
1315 v
.visit_stmt
(n_block
)
1317 self.mtype
= n_block
.mtype
1318 self.is_typed
= true
1322 redef class AForGroup
1323 var coltype
: nullable MClassType
1325 var method_iterator
: nullable CallSite
1326 var method_is_ok
: nullable CallSite
1327 var method_item
: nullable CallSite
1328 var method_next
: nullable CallSite
1329 var method_key
: nullable CallSite
1330 var method_finish
: nullable CallSite
1332 var method_lt
: nullable CallSite
1333 var method_successor
: nullable CallSite
1335 private fun do_type_iterator
(v
: TypeVisitor, mtype
: MType)
1337 if mtype
isa MNullType then
1338 v
.error
(self, "Type Error: `for` cannot iterate over `null`.")
1343 var objcla
= v
.get_mclass
(self, "Object")
1344 if objcla
== null then return
1346 # check iterator method
1347 var itdef
= v
.build_callsite_by_name
(self, mtype
, "iterator", n_expr
isa ASelfExpr)
1348 if itdef
== null then
1349 v
.error
(self, "Type Error: `for` expects a type providing an `iterator` method, got `{mtype}`.")
1352 self.method_iterator
= itdef
1354 # check that iterator return something
1355 var ittype
= itdef
.msignature
.return_mtype
1356 if ittype
== null then
1357 v
.error
(self, "Type Error: `for` expects the method `iterator` to return an `Iterator` or `MapIterator` type.")
1362 var colit_cla
= v
.try_get_mclass
(self, "Iterator")
1363 var mapit_cla
= v
.try_get_mclass
(self, "MapIterator")
1367 if colit_cla
!= null and v
.is_subtype
(ittype
, colit_cla
.get_mtype
([objcla
.mclass_type
.as_nullable
])) then
1369 var coltype
= ittype
.supertype_to
(v
.mmodule
, v
.anchor
, colit_cla
)
1370 var variables
= self.variables
1371 if variables
.length
!= 1 then
1372 v
.error
(self, "Type Error: `for` expects only one variable when using `Iterator`.")
1374 variables
.first
.declared_type
= coltype
.arguments
.first
1379 if mapit_cla
!= null and v
.is_subtype
(ittype
, mapit_cla
.get_mtype
([objcla
.mclass_type
.as_nullable
, objcla
.mclass_type
.as_nullable
])) then
1381 var coltype
= ittype
.supertype_to
(v
.mmodule
, v
.anchor
, mapit_cla
)
1382 var variables
= self.variables
1383 if variables
.length
!= 2 then
1384 v
.error
(self, "Type Error: `for` expects two variables when using `MapIterator`.")
1386 variables
[0].declared_type
= coltype
.arguments
[0]
1387 variables
[1].declared_type
= coltype
.arguments
[1]
1392 if not is_col
and not is_map
then
1393 v
.error
(self, "Type Error: `for` expects the method `iterator` to return an `Iterator` or `MapIterator` type.")
1397 # anchor formal and virtual types
1398 if mtype
.need_anchor
then mtype
= v
.anchor_to
(mtype
)
1400 mtype
= mtype
.undecorate
1401 self.coltype
= mtype
.as(MClassType)
1403 # get methods is_ok, next, item
1404 var ikdef
= v
.build_callsite_by_name
(self, ittype
, "is_ok", false)
1405 if ikdef
== null then
1406 v
.error
(self, "Type Error: `for` expects a method `is_ok` in type `{ittype}`.")
1409 self.method_is_ok
= ikdef
1411 var itemdef
= v
.build_callsite_by_name
(self, ittype
, "item", false)
1412 if itemdef
== null then
1413 v
.error
(self, "Type Error: `for` expects a method `item` in type `{ittype}`.")
1416 self.method_item
= itemdef
1418 var nextdef
= v
.build_callsite_by_name
(self, ittype
, "next", false)
1419 if nextdef
== null then
1420 v
.error
(self, "Type Error: `for` expects a method `next` in type {ittype}.")
1423 self.method_next
= nextdef
1425 self.method_finish
= v
.try_build_callsite_by_name
(self, ittype
, "finish", false)
1428 var keydef
= v
.build_callsite_by_name
(self, ittype
, "key", false)
1429 if keydef
== null then
1430 v
.error
(self, "Type Error: `for` expects a method `key` in type `{ittype}`.")
1433 self.method_key
= keydef
1436 if self.variables
.length
== 1 and n_expr
isa ARangeExpr then
1437 var variable
= variables
.first
1438 var vtype
= variable
.declared_type
.as(not null)
1440 if n_expr
isa AOrangeExpr then
1441 self.method_lt
= v
.build_callsite_by_name
(self, vtype
, "<", false)
1443 self.method_lt
= v
.build_callsite_by_name
(self, vtype
, "<=", false)
1446 self.method_successor
= v
.build_callsite_by_name
(self, vtype
, "successor", false)
1451 redef class AWithExpr
1452 var method_start
: nullable CallSite
1453 var method_finish
: nullable CallSite
1455 redef fun accept_typing
(v
: TypeVisitor)
1457 var mtype
= v
.visit_expr
(n_expr
)
1458 if mtype
== null then return
1460 method_start
= v
.build_callsite_by_name
(self, mtype
, "start", n_expr
isa ASelfExpr)
1461 method_finish
= v
.build_callsite_by_name
(self, mtype
, "finish", n_expr
isa ASelfExpr)
1463 v
.visit_stmt
(n_block
)
1464 self.mtype
= n_block
.mtype
1465 self.is_typed
= true
1469 redef class AAssertExpr
1470 redef fun accept_typing
(v
)
1472 v
.visit_expr_bool
(n_expr
)
1474 v
.visit_stmt
(n_else
)
1475 self.is_typed
= true
1480 redef fun accept_typing
(v
)
1482 v
.visit_expr_bool
(n_expr
)
1483 v
.visit_expr_bool
(n_expr2
)
1484 self.mtype
= v
.type_bool
(self)
1488 redef class AImpliesExpr
1489 redef fun accept_typing
(v
)
1491 v
.visit_expr_bool
(n_expr
)
1492 v
.visit_expr_bool
(n_expr2
)
1493 self.mtype
= v
.type_bool
(self)
1497 redef class AAndExpr
1498 redef fun accept_typing
(v
)
1500 v
.visit_expr_bool
(n_expr
)
1501 v
.visit_expr_bool
(n_expr2
)
1502 self.mtype
= v
.type_bool
(self)
1506 redef class ANotExpr
1507 redef fun accept_typing
(v
)
1509 v
.visit_expr_bool
(n_expr
)
1510 self.mtype
= v
.type_bool
(self)
1514 redef class AOrElseExpr
1515 redef fun accept_typing
(v
)
1517 var t1
= v
.visit_expr
(n_expr
)
1518 var t2
= v
.visit_expr
(n_expr2
)
1520 if t1
== null or t2
== null then
1524 if t1
isa MNullType then
1527 else if v
.can_be_null
(t1
) then
1531 var t
= v
.merge_types
(self, [t1
, t2
])
1533 var c
= v
.get_mclass
(self, "Object")
1534 if c
== null then return # forward error
1536 if v
.can_be_null
(t2
) then
1539 #v.error(self, "Type Error: ambiguous type {t1} vs {t2}")
1544 redef fun accept_post_typing
(v
)
1546 var t1
= n_expr
.mtype
1550 v
.check_can_be_null
(n_expr
, t1
)
1555 redef class ATrueExpr
1556 redef fun accept_typing
(v
)
1558 self.mtype
= v
.type_bool
(self)
1562 redef class AFalseExpr
1563 redef fun accept_typing
(v
)
1565 self.mtype
= v
.type_bool
(self)
1569 redef class AIntegerExpr
1570 redef fun accept_typing
(v
)
1572 var mclass
: nullable MClass = null
1573 if value
isa Byte then
1574 mclass
= v
.get_mclass
(self, "Byte")
1575 else if value
isa Int then
1576 mclass
= v
.get_mclass
(self, "Int")
1577 else if value
isa Int8 then
1578 mclass
= v
.get_mclass
(self, "Int8")
1579 else if value
isa Int16 then
1580 mclass
= v
.get_mclass
(self, "Int16")
1581 else if value
isa UInt16 then
1582 mclass
= v
.get_mclass
(self, "UInt16")
1583 else if value
isa Int32 then
1584 mclass
= v
.get_mclass
(self, "Int32")
1585 else if value
isa UInt32 then
1586 mclass
= v
.get_mclass
(self, "UInt32")
1588 if mclass
== null then return # Forward error
1589 self.mtype
= mclass
.mclass_type
1593 redef class AFloatExpr
1594 redef fun accept_typing
(v
)
1596 var mclass
= v
.get_mclass
(self, "Float")
1597 if mclass
== null then return # Forward error
1598 self.mtype
= mclass
.mclass_type
1602 redef class ACharExpr
1603 redef fun accept_typing
(v
) do
1604 var mclass
: nullable MClass = null
1605 if is_code_point
then
1606 mclass
= v
.get_mclass
(self, "Int")
1608 mclass
= v
.get_mclass
(self, "Char")
1610 if mclass
== null then return # Forward error
1611 self.mtype
= mclass
.mclass_type
1615 redef class AugmentedStringFormExpr
1618 # Text::to_re, used for prefix `re`
1619 var to_re
: nullable CallSite = null
1620 # Regex::ignore_case, used for suffix `i` on `re`
1621 var ignore_case
: nullable CallSite = null
1622 # Regex::newline, used for suffix `m` on `re`
1623 var newline
: nullable CallSite = null
1624 # Regex::extended, used for suffix `b` on `re`
1625 var extended
: nullable CallSite = null
1626 # CString::to_bytes_with_copy, used for prefix `b`
1627 var to_bytes_with_copy
: nullable CallSite = null
1629 redef fun accept_typing
(v
) do
1630 var mclass
= v
.get_mclass
(self, "String")
1631 if mclass
== null then return # Forward error
1632 if is_bytestring
then
1633 to_bytes_with_copy
= v
.build_callsite_by_name
(self, v
.mmodule
.c_string_type
, "to_bytes_with_copy", false)
1634 mclass
= v
.get_mclass
(self, "Bytes")
1636 to_re
= v
.build_callsite_by_name
(self, mclass
.mclass_type
, "to_re", false)
1637 for i
in suffix
.chars
do
1638 mclass
= v
.get_mclass
(self, "Regex")
1639 if mclass
== null then
1640 v
.error
(self, "Error: `Regex` class unknown")
1645 service
= "ignore_case="
1646 ignore_case
= v
.build_callsite_by_name
(self, mclass
.mclass_type
, service
, false)
1647 else if i
== 'm' then
1648 service
= "newline="
1649 newline
= v
.build_callsite_by_name
(self, mclass
.mclass_type
, service
, false)
1650 else if i
== 'b' then
1651 service
= "extended="
1652 extended
= v
.build_callsite_by_name
(self, mclass
.mclass_type
, service
, false)
1654 v
.error
(self, "Type Error: Unrecognized suffix {i} in prefixed Regex")
1659 if mclass
== null then return # Forward error
1660 mtype
= mclass
.mclass_type
1664 redef class ASuperstringExpr
1665 redef fun accept_typing
(v
)
1668 var objclass
= v
.get_mclass
(self, "Object")
1669 if objclass
== null then return # Forward error
1670 var objtype
= objclass
.mclass_type
1671 for nexpr
in self.n_exprs
do
1672 v
.visit_expr_subtype
(nexpr
, objtype
)
1677 redef class AArrayExpr
1678 # The `with_capacity` method on Array
1679 var with_capacity_callsite
: nullable CallSite
1681 # The `push` method on arrays
1682 var push_callsite
: nullable CallSite
1684 # The element of each type
1685 var element_mtype
: nullable MType
1687 # Set that `self` is a part of comprehension array `na`
1688 # If `self` is a `for`, or a `if`, then `set_comprehension` is recursively applied.
1689 private fun set_comprehension
(n
: nullable AExpr)
1693 else if n
isa AForExpr then
1694 set_comprehension
(n
.n_block
)
1695 else if n
isa AIfExpr then
1696 set_comprehension
(n
.n_then
)
1697 set_comprehension
(n
.n_else
)
1700 n
.comprehension
= self
1703 redef fun accept_typing
(v
)
1705 var mtype
: nullable MType = null
1706 var ntype
= self.n_type
1707 if ntype
!= null then
1708 mtype
= v
.resolve_mtype
(ntype
)
1709 if mtype
== null then return # Skip error
1711 var mtypes
= new Array[nullable MType]
1713 for e
in self.n_exprs
do
1714 var t
= v
.visit_expr
(e
)
1718 set_comprehension
(e
)
1719 if mtype
!= null then
1720 if v
.check_subtype
(e
, t
, mtype
, false) == null then return # Forward error
1721 if t
== mtype
then useless
= true
1726 if mtype
== null then
1727 # Ensure monotony for type adaptation on loops
1728 if self.element_mtype
!= null then mtypes
.add
self.element_mtype
1729 mtype
= v
.merge_types
(self, mtypes
)
1731 if mtype
== null or mtype
isa MNullType then
1732 v
.error
(self, "Type Error: ambiguous array type {mtypes.join(" ")}")
1736 assert ntype
!= null
1737 v
.modelbuilder
.warning
(ntype
, "useless-type", "Warning: useless type declaration `{mtype}` in literal Array since it can be inferred from the elements type.")
1740 self.element_mtype
= mtype
1742 var mclass
= v
.get_mclass
(self, "Array")
1743 if mclass
== null then return # Forward error
1744 var array_mtype
= mclass
.get_mtype
([mtype
])
1746 with_capacity_callsite
= v
.build_callsite_by_name
(self, array_mtype
, "with_capacity", false)
1747 push_callsite
= v
.build_callsite_by_name
(self, array_mtype
, "push", false)
1749 self.mtype
= array_mtype
1753 redef class ARangeExpr
1754 var init_callsite
: nullable CallSite
1756 redef fun accept_typing
(v
)
1758 var discrete_class
= v
.get_mclass
(self, "Discrete")
1759 if discrete_class
== null then return # Forward error
1760 var discrete_type
= discrete_class
.intro
.bound_mtype
1761 var t1
= v
.visit_expr_subtype
(self.n_expr
, discrete_type
)
1762 var t2
= v
.visit_expr_subtype
(self.n_expr2
, discrete_type
)
1763 if t1
== null or t2
== null then return
1764 var mclass
= v
.get_mclass
(self, "Range")
1765 if mclass
== null then return # Forward error
1767 if v
.is_subtype
(t1
, t2
) then
1768 mtype
= mclass
.get_mtype
([t2
])
1769 else if v
.is_subtype
(t2
, t1
) then
1770 mtype
= mclass
.get_mtype
([t1
])
1772 v
.error
(self, "Type Error: cannot create range: `{t1}` vs `{t2}`.")
1778 # get the constructor
1780 if self isa ACrangeExpr then
1781 callsite
= v
.build_callsite_by_name
(self, mtype
, "autoinit", false)
1782 else if self isa AOrangeExpr then
1783 callsite
= v
.build_callsite_by_name
(self, mtype
, "without_last", false)
1787 init_callsite
= callsite
1791 redef class ANullExpr
1792 redef fun accept_typing
(v
)
1794 self.mtype
= v
.mmodule
.model
.null_type
1798 redef class AIsaExpr
1799 # The static type to cast to.
1800 # (different from the static type of the expression that is `Bool`).
1801 var cast_type
: nullable MType
1802 redef fun accept_typing
(v
)
1804 v
.visit_expr
(n_expr
)
1806 var mtype
= v
.resolve_mtype
(n_type
)
1808 self.cast_type
= mtype
1810 var variable
= self.n_expr
.its_variable
1811 if variable
!= null then
1812 var orig
= self.n_expr
.mtype
1813 #var from = if orig != null then orig.to_s else "invalid"
1814 #var to = if mtype != null then mtype.to_s else "invalid"
1815 #debug("adapt {variable}: {from} -> {to}")
1817 var thentype
= v
.intersect_types
(self, orig
, mtype
)
1818 if thentype
!= orig
then
1819 self.after_flow_context
.when_true
.set_var
(v
, variable
, thentype
)
1820 #debug "{variable}:{orig or else "?"} isa {mtype or else "?"} -> then {thentype or else "?"}"
1823 var elsetype
= v
.diff_types
(self, orig
, mtype
)
1824 if elsetype
!= orig
then
1825 self.after_flow_context
.when_false
.set_var
(v
, variable
, elsetype
)
1826 #debug "{variable}:{orig or else "?"} isa {mtype or else "?"} -> else {elsetype or else "?"}"
1830 self.mtype
= v
.type_bool
(self)
1833 redef fun accept_post_typing
(v
)
1835 v
.check_expr_cast
(self, self.n_expr
, self.n_type
)
1838 redef fun dump_info
(v
) do
1840 var mtype
= self.cast_type
1841 if mtype
!= null then
1842 res
+= v
.yellow
(".as({mtype})")
1849 redef class AAsCastExpr
1850 redef fun accept_typing
(v
)
1852 v
.visit_expr
(n_expr
)
1854 self.mtype
= v
.resolve_mtype
(n_type
)
1857 redef fun accept_post_typing
(v
)
1859 v
.check_expr_cast
(self, self.n_expr
, self.n_type
)
1863 redef class AAsNotnullExpr
1864 redef fun accept_typing
(v
)
1866 var mtype
= v
.visit_expr
(self.n_expr
)
1867 if mtype
== null then return # Forward error
1869 if mtype
isa MNullType then
1870 v
.error
(self, "Type Error: `as(not null)` on `null`.")
1874 if v
.can_be_null
(mtype
) then
1875 mtype
= mtype
.as_notnull
1881 redef fun accept_post_typing
(v
)
1883 var mtype
= n_expr
.mtype
1884 if mtype
== null then return
1885 v
.check_can_be_null
(n_expr
, mtype
)
1889 redef class AParExpr
1890 redef fun accept_typing
(v
)
1892 self.mtype
= v
.visit_expr
(self.n_expr
)
1896 redef class AOnceExpr
1897 redef fun accept_typing
(v
)
1899 self.mtype
= v
.visit_expr
(self.n_expr
)
1903 redef class ASelfExpr
1904 redef var its_variable
: nullable Variable
1905 redef fun accept_typing
(v
)
1907 if v
.is_toplevel_context
and not self isa AImplicitSelfExpr then
1908 v
.error
(self, "Error: `self` cannot be used in top-level method.")
1910 var variable
= v
.selfvariable
1911 self.its_variable
= variable
1912 self.mtype
= v
.get_variable
(self, variable
)
1916 redef class AImplicitSelfExpr
1917 # Is the implicit receiver `sys`?
1919 # By default, the implicit receiver is `self`.
1920 # But when there is not method for `self`, `sys` is used as a fall-back.
1921 # Is this case this flag is set to `true`.
1925 ## MESSAGE SENDING AND PROPERTY
1927 redef class ASendExpr
1928 # The property invoked by the send.
1929 var callsite
: nullable CallSite
1931 # Is self a safe call (with `x?.foo`)?
1932 # If so and the receiver is null, then the arguments won't be evaluated
1933 # and the call skipped (replaced with null).
1934 var is_safe
: Bool = false
1936 redef fun bad_expr_message
(child
)
1938 if child
== self.n_expr
then
1939 return "to be the receiver of `{self.property_name}`"
1944 redef fun accept_typing
(v
)
1946 var nrecv
= self.n_expr
1947 var recvtype
= v
.visit_expr
(nrecv
)
1949 if nrecv
isa ASafeExpr then
1950 # Has the receiver the form `x?.foo`?
1951 # For parsing "reasons" the `?` is in the receiver node, not the call node.
1955 var name
= self.property_name
1956 var node
= self.property_node
1958 if recvtype
== null then return # Forward error
1961 var unsafe_type
= v
.anchor_to
(recvtype
)
1962 var mproperty
= v
.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
1963 if mproperty
== null and nrecv
isa AImplicitSelfExpr then
1964 # Special fall-back search in `sys` when noting found in the implicit receiver.
1965 var sysclass
= v
.try_get_mclass
(node
, "Sys")
1966 if sysclass
!= null then
1967 var systype
= sysclass
.mclass_type
1968 mproperty
= v
.try_get_mproperty_by_name2
(node
, systype
, name
)
1969 if mproperty
!= null then
1970 callsite
= v
.build_callsite_by_name
(node
, systype
, name
, false)
1971 if callsite
== null then return # Forward error
1972 # Update information, we are looking at `sys` now, not `self`
1974 nrecv
.its_variable
= null
1975 nrecv
.mtype
= systype
1980 if callsite
== null then
1981 # If still nothing, just exit
1982 callsite
= v
.build_callsite_by_name
(node
, recvtype
, name
, nrecv
isa ASelfExpr)
1983 if callsite
== null then return
1986 self.callsite
= callsite
1987 var msignature
= callsite
.msignature
1989 var args
= compute_raw_arguments
1991 if not self isa ACallrefExpr then
1992 callsite
.check_signature
(v
, node
, args
)
1995 if callsite
.mproperty
.is_init
then
1996 var vmpropdef
= v
.mpropdef
1997 if not (vmpropdef
isa MMethodDef and vmpropdef
.mproperty
.is_init
) then
1998 v
.error
(node
, "Error: an `init` can only be called from another `init`.")
2000 if vmpropdef
isa MMethodDef and vmpropdef
.mproperty
.is_root_init
and not callsite
.mproperty
.is_root_init
then
2001 v
.error
(node
, "Error: `{vmpropdef}` cannot call a factory `{callsite.mproperty}`.")
2005 var ret
= msignature
.return_mtype
2008 # A safe receiver makes that the call is not executed and returns null
2009 ret
= ret
.as_nullable
2013 self.is_typed
= true
2017 # The name of the property
2018 # Each subclass simply provide the correct name.
2019 private fun property_name
: String is abstract
2021 # The node identifying the name (id, operator, etc) for messages.
2023 # Is `self` by default
2024 private fun property_node
: ANode do return self
2026 # An array of all arguments (excluding self)
2027 fun raw_arguments
: Array[AExpr] do return compute_raw_arguments
2029 private fun compute_raw_arguments
: Array[AExpr] is abstract
2031 redef fun dump_info
(v
) do
2033 var callsite
= self.callsite
2034 if callsite
!= null then
2035 res
+= v
.yellow
(" call="+callsite
.dump_info
(v
))
2041 redef class ABinopExpr
2042 redef fun compute_raw_arguments
do return [n_expr2
]
2043 redef fun property_name
do return operator
2044 redef fun property_node
do return n_op
2047 redef class AEqFormExpr
2048 redef fun accept_typing
(v
)
2054 redef fun accept_post_typing
(v
)
2056 var mtype
= n_expr
.mtype
2057 var mtype2
= n_expr2
.mtype
2059 if mtype
== null or mtype2
== null then return
2061 if mtype
== v
.type_bool
(self) and (n_expr2
isa AFalseExpr or n_expr2
isa ATrueExpr) then
2062 v
.modelbuilder
.warning
(self, "useless-truism", "Warning: useless comparison to a Bool literal.")
2065 if not mtype2
isa MNullType then return
2067 v
.check_can_be_null
(n_expr
, mtype
)
2071 redef class AUnaryopExpr
2072 redef fun property_name
do return "unary {operator}"
2073 redef fun compute_raw_arguments
do return new Array[AExpr]
2076 redef class ACallExpr
2077 redef fun property_name
do return n_qid
.n_id
.text
2078 redef fun property_node
do return n_qid
2079 redef fun compute_raw_arguments
do return n_args
.to_a
2082 redef class ACallAssignExpr
2083 redef fun property_name
do return n_qid
.n_id
.text
+ "="
2084 redef fun property_node
do return n_qid
2085 redef fun compute_raw_arguments
2087 var res
= n_args
.to_a
2093 redef class ABraExpr
2094 redef fun property_name
do return "[]"
2095 redef fun compute_raw_arguments
do return n_args
.to_a
2098 redef class ABraAssignExpr
2099 redef fun property_name
do return "[]="
2100 redef fun compute_raw_arguments
2102 var res
= n_args
.to_a
2108 redef class ASendReassignFormExpr
2109 # The property invoked for the writing
2110 var write_callsite
: nullable CallSite
2112 redef fun accept_typing
(v
)
2114 var recvtype
= v
.visit_expr
(self.n_expr
)
2115 var name
= self.property_name
2116 var node
= self.property_node
2118 if recvtype
== null then return # Forward error
2120 var for_self
= self.n_expr
isa ASelfExpr
2121 var callsite
= v
.build_callsite_by_name
(node
, recvtype
, name
, for_self
)
2123 if callsite
== null then return
2124 self.callsite
= callsite
2126 var args
= compute_raw_arguments
2128 callsite
.check_signature
(v
, node
, args
)
2130 var readtype
= callsite
.msignature
.return_mtype
2131 if readtype
== null then
2132 v
.error
(node
, "Error: `{name}` is not a function.")
2136 var wcallsite
= v
.build_callsite_by_name
(node
, recvtype
, name
+ "=", self.n_expr
isa ASelfExpr)
2137 if wcallsite
== null then return
2138 self.write_callsite
= wcallsite
2140 var wtype
= self.resolve_reassignment
(v
, readtype
, wcallsite
.msignature
.mparameters
.last
.mtype
)
2141 if wtype
== null then return
2143 args
= args
.to_a
# duplicate so raw_arguments keeps only the getter args
2144 args
.add
(self.n_value
)
2145 wcallsite
.check_signature
(v
, node
, args
)
2147 self.is_typed
= true
2151 redef class ACallReassignExpr
2152 redef fun property_name
do return n_qid
.n_id
.text
2153 redef fun property_node
do return n_qid
.n_id
2154 redef fun compute_raw_arguments
do return n_args
.to_a
2157 redef class ABraReassignExpr
2158 redef fun property_name
do return "[]"
2159 redef fun compute_raw_arguments
do return n_args
.to_a
2162 redef class AInitExpr
2163 redef fun property_name
do if n_args
.n_exprs
.is_empty
then return "init" else return "autoinit"
2164 redef fun property_node
do return n_kwinit
2165 redef fun compute_raw_arguments
do return n_args
.to_a
2168 redef class ACallrefExpr
2169 redef fun property_name
do return n_qid
.n_id
.text
2170 redef fun property_node
do return n_qid
2171 redef fun compute_raw_arguments
do return n_args
.to_a
2173 redef fun accept_typing
(v
)
2175 super # do the job as if it was a real call
2176 var res
= callsite
.mproperty
2178 var msignature
= callsite
.mpropdef
.msignature
2179 var recv
= callsite
.recv
2180 assert msignature
!= null
2181 var arity
= msignature
.mparameters
.length
2183 var routine_type_name
= "ProcRef"
2184 if msignature
.return_mtype
!= null then
2185 routine_type_name
= "FunRef"
2188 var target_routine_class
= "{routine_type_name}{arity}"
2189 var routine_mclass
= v
.get_mclass
(self, target_routine_class
)
2191 if routine_mclass
== null then
2192 v
.error
(self, "Error: missing functional types, try `import functional`")
2196 var types_list
= new Array[MType]
2197 for param
in msignature
.mparameters
do
2198 if param
.is_vararg
then
2199 types_list
.push
(v
.mmodule
.array_type
(param
.mtype
))
2201 types_list
.push
(param
.mtype
)
2204 if msignature
.return_mtype
!= null then
2205 types_list
.push
(msignature
.return_mtype
.as(not null))
2208 # Why we need an anchor :
2212 # def toto(x: E) do print "{x}"
2215 # var a = new A[Int]
2216 # var f = &a.toto # without anchor : ProcRef1[E]
2217 # # with anchor : ProcRef[Int]
2219 # However, we can only anchor if we can resolve every formal
2220 # parameter, here's an example where we can't.
2223 # fun bar: A[E] do return self
2224 # fun foo: Fun0[A[E]] do return &bar # here we can't anchor
2226 # var f1 = a1.foo # when this expression will be evaluated,
2227 # # `a1` will anchor `&bar` returned by `foo`.
2230 var routine_type
= routine_mclass
.get_mtype
(types_list
)
2231 if not recv
.need_anchor
then
2232 routine_type
= routine_type
.anchor_to
(v
.mmodule
, recv
.as(MClassType))
2235 self.mtype
= routine_type
2240 fun to_a
: Array[AExpr] do return self.n_exprs
.to_a
2245 redef class ASuperExpr
2246 # The method to call if the super is in fact a 'super init call'
2247 # Note: if the super is a normal call-next-method, then this attribute is null
2248 var callsite
: nullable CallSite
2250 # The method to call is the super is a standard `call-next-method` super-call
2251 # Note: if the super is a special super-init-call, then this attribute is null
2252 var mpropdef
: nullable MMethodDef
2254 redef fun accept_typing
(v
)
2256 var anchor
= v
.anchor
2257 var recvtype
= v
.get_variable
(self, v
.selfvariable
)
2258 assert recvtype
!= null
2259 var mproperty
= v
.mpropdef
.mproperty
2260 if not mproperty
isa MMethod then
2261 v
.error
(self, "Error: `super` only usable in a `method`.")
2264 var superprops
= mproperty
.lookup_super_definitions
(v
.mmodule
, anchor
)
2265 if superprops
.length
== 0 then
2266 if mproperty
.is_init
and v
.mpropdef
.is_intro
then
2267 process_superinit
(v
)
2270 v
.error
(self, "Error: no super method to call for `{mproperty}`.")
2273 # FIXME: covariance of return type in linear extension?
2274 var superprop
= superprops
.first
2276 var msignature
= superprop
.msignature
.as(not null)
2277 msignature
= v
.resolve_for
(msignature
, recvtype
, true).as(MSignature)
2278 var args
= self.n_args
.to_a
2279 if args
.length
> 0 then
2280 signaturemap
= v
.check_signature
(self, args
, mproperty
, msignature
)
2282 self.mtype
= msignature
.return_mtype
2283 self.is_typed
= true
2284 v
.mpropdef
.has_supercall
= true
2285 mpropdef
= v
.mpropdef
.as(MMethodDef)
2288 # The mapping used on the call to associate arguments to parameters.
2289 # If null then no specific association is required.
2290 var signaturemap
: nullable SignatureMap
2292 private fun process_superinit
(v
: TypeVisitor)
2294 var anchor
= v
.anchor
2295 var recvtype
= v
.get_variable
(self, v
.selfvariable
)
2296 assert recvtype
!= null
2297 var mpropdef
= v
.mpropdef
2298 assert mpropdef
isa MMethodDef
2299 var mproperty
= mpropdef
.mproperty
2300 var superprop
: nullable MMethodDef = null
2301 for msupertype
in mpropdef
.mclassdef
.supertypes
do
2302 msupertype
= msupertype
.anchor_to
(v
.mmodule
, anchor
)
2303 var errcount
= v
.modelbuilder
.toolcontext
.error_count
2304 var candidate
= v
.try_get_mproperty_by_name2
(self, msupertype
, mproperty
.name
).as(nullable MMethod)
2305 if candidate
== null then
2306 if v
.modelbuilder
.toolcontext
.error_count
> errcount
then return # Forward error
2307 continue # Try next super-class
2309 if superprop
!= null and candidate
.is_root_init
then
2312 if superprop
!= null and superprop
.mproperty
!= candidate
and not superprop
.mproperty
.is_root_init
then
2313 v
.error
(self, "Error: conflicting super constructor to call for `{mproperty}`: `{candidate.full_name}`, `{superprop.mproperty.full_name}`")
2316 var candidatedefs
= candidate
.lookup_definitions
(v
.mmodule
, anchor
)
2317 if superprop
!= null and superprop
.mproperty
== candidate
then
2318 if superprop
== candidatedefs
.first
then continue
2319 candidatedefs
.add
(superprop
)
2321 if candidatedefs
.length
> 1 then
2322 v
.error
(self, "Error: conflicting property definitions for property `{mproperty}` in `{recvtype}`: {candidatedefs.join(", ")}")
2325 superprop
= candidatedefs
.first
2327 if superprop
== null then
2328 v
.error
(self, "Error: no super method to call for `{mproperty}`.")
2332 var msignature
= superprop
.msignature
.as(not null)
2333 msignature
= v
.resolve_for
(msignature
, recvtype
, true).as(MSignature)
2335 var callsite
= new CallSite(hot_location
, recvtype
, v
.mmodule
, v
.anchor
, true, superprop
.mproperty
, superprop
, msignature
, false)
2336 self.callsite
= callsite
2338 var args
= self.n_args
.to_a
2339 if args
.length
> 0 then
2340 callsite
.check_signature
(v
, self, args
)
2342 # Check there is at least enough parameters
2343 if mpropdef
.msignature
.arity
< msignature
.arity
then
2344 v
.error
(self, "Error: not enough implicit arguments to pass. Got `{mpropdef.msignature.arity}`, expected at least `{msignature.arity}`. Signature is `{msignature}`.")
2347 # Check that each needed parameter is conform
2349 for sp
in msignature
.mparameters
do
2350 var p
= mpropdef
.msignature
.mparameters
[i
]
2351 if not v
.is_subtype
(p
.mtype
, sp
.mtype
) then
2352 v
.error
(self, "Type Error: expected argument #{i} of type `{sp.mtype}`, got implicit argument `{p.name}` of type `{p.mtype}`. Signature is {msignature}")
2359 self.is_typed
= true
2362 redef fun dump_info
(v
) do
2364 var callsite
= self.callsite
2365 if callsite
!= null then
2366 res
+= v
.yellow
(" super-init="+callsite
.dump_info
(v
))
2368 var mpropdef
= self.mpropdef
2369 if mpropdef
!= null then
2370 res
+= v
.yellow
(" call-next-method="+mpropdef
.to_s
)
2378 redef class ANewExpr
2379 # The constructor invoked by the new.
2380 var callsite
: nullable CallSite
2382 # The designated type
2383 var recvtype
: nullable MClassType
2385 redef fun accept_typing
(v
)
2387 var recvtype
= v
.resolve_mtype
(self.n_type
)
2388 if recvtype
== null then return
2390 if not recvtype
isa MClassType then
2391 if recvtype
isa MNullableType then
2392 v
.error
(self, "Type Error: cannot instantiate the nullable type `{recvtype}`.")
2394 else if recvtype
isa MFormalType then
2395 v
.error
(self, "Type Error: cannot instantiate the formal type `{recvtype}`.")
2398 v
.error
(self, "Type Error: cannot instantiate the type `{recvtype}`.")
2403 self.recvtype
= recvtype
2404 var kind
= recvtype
.mclass
.kind
2407 var nqid
= self.n_qid
2409 if nqid
!= null then
2410 name
= nqid
.n_id
.text
2416 if name
== "intern" then
2417 if kind
!= concrete_kind
then
2418 v
.error
(self, "Type Error: cannot instantiate {kind} {recvtype}.")
2421 if n_args
.n_exprs
.not_empty
then
2422 v
.error
(n_args
, "Type Error: the intern constructor expects no arguments.")
2426 self.mtype
= recvtype
2430 var callsite
= v
.build_callsite_by_name
(node
, recvtype
, name
, false)
2431 if callsite
== null then return
2433 if not callsite
.mproperty
.is_new
then
2434 if kind
!= concrete_kind
then
2435 v
.error
(self, "Type Error: cannot instantiate {kind} `{recvtype}`.")
2438 self.mtype
= recvtype
2440 self.mtype
= callsite
.msignature
.return_mtype
2441 assert self.mtype
!= null
2444 self.callsite
= callsite
2446 if not callsite
.mproperty
.is_init_for
(recvtype
.mclass
) then
2447 v
.error
(self, "Error: `{name}` is not a constructor.")
2451 var args
= n_args
.to_a
2452 callsite
.check_signature
(v
, node
, args
)
2455 redef fun dump_info
(v
) do
2457 var callsite
= self.callsite
2458 if callsite
!= null then
2459 res
+= v
.yellow
(" call="+callsite
.dump_info
(v
))
2467 redef class AAttrFormExpr
2468 # The attribute accessed.
2469 var mproperty
: nullable MAttribute
2471 # The static type of the attribute.
2472 var attr_type
: nullable MType
2474 # Resolve the attribute accessed.
2475 private fun resolve_property
(v
: TypeVisitor)
2477 var recvtype
= v
.visit_expr
(self.n_expr
)
2478 if recvtype
== null then return # Skip error
2479 var node
= self.n_id
2480 var name
= node
.text
2481 if recvtype
isa MNullType then
2482 v
.error
(node
, "Error: attribute `{name}` access on `null`.")
2486 var unsafe_type
= v
.anchor_to
(recvtype
)
2487 var mproperty
= v
.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
2488 if mproperty
== null then
2489 v
.modelbuilder
.error
(node
, "Error: attribute `{name}` does not exist in `{recvtype}`.")
2492 assert mproperty
isa MAttribute
2493 self.mproperty
= mproperty
2495 var mpropdefs
= mproperty
.lookup_definitions
(v
.mmodule
, unsafe_type
)
2496 assert mpropdefs
.length
== 1
2497 var mpropdef
= mpropdefs
.first
2498 var attr_type
= mpropdef
.static_mtype
2499 if attr_type
== null then return # skip error
2500 attr_type
= v
.resolve_for
(attr_type
, recvtype
, self.n_expr
isa ASelfExpr)
2501 self.attr_type
= attr_type
2504 redef fun dump_info
(v
) do
2506 var mproperty
= self.mproperty
2507 var attr_type
= self.attr_type
2508 if mproperty
!= null then
2509 res
+= v
.yellow
(" attr={mproperty}:{attr_type or else "BROKEN"}")
2515 redef class AAttrExpr
2516 redef fun accept_typing
(v
)
2518 self.resolve_property
(v
)
2519 self.mtype
= self.attr_type
2523 redef class AAttrAssignExpr
2524 redef fun accept_typing
(v
)
2526 self.resolve_property
(v
)
2527 var mtype
= self.attr_type
2529 v
.visit_expr_subtype
(self.n_value
, mtype
)
2530 self.is_typed
= mtype
!= null
2534 redef class AAttrReassignExpr
2535 redef fun accept_typing
(v
)
2537 self.resolve_property
(v
)
2538 var mtype
= self.attr_type
2539 if mtype
== null then return # Skip error
2541 var rettype
= self.resolve_reassignment
(v
, mtype
, mtype
)
2543 self.is_typed
= rettype
!= null
2547 redef class AIssetAttrExpr
2548 redef fun accept_typing
(v
)
2550 self.resolve_property
(v
)
2551 var mtype
= self.attr_type
2552 if mtype
== null then return # Skip error
2554 var recvtype
= self.n_expr
.mtype
.as(not null)
2555 var bound
= v
.resolve_for
(mtype
, recvtype
, false)
2556 if bound
isa MNullableType then
2557 v
.error
(n_id
, "Type Error: `isset` on a nullable attribute.")
2559 self.mtype
= v
.type_bool
(self)
2563 redef class ASafeExpr
2564 redef fun accept_typing
(v
)
2566 var mtype
= v
.visit_expr
(n_expr
)
2567 if mtype
== null then return # Skip error
2569 if mtype
isa MNullType then
2570 # While `null?.foo` is semantically well defined and should not execute `foo` and just return `null`,
2571 # currently `null.foo` is forbidden so it seems coherent to also forbid `null?.foo`
2572 v
.modelbuilder
.error
(self, "Error: safe operator `?` on `null`.")
2576 self.mtype
= mtype
.as_notnull
2578 if not v
.can_be_null
(mtype
) then
2579 v
.modelbuilder
.warning
(self, "useless-safe", "Warning: useless safe operator `?` on non-nullable value.")
2585 redef class AVarargExpr
2586 redef fun accept_typing
(v
)
2588 # This kind of pseudo-expression can be only processed trough a signature
2589 # See `check_signature`
2590 # Other cases are a syntax error.
2591 v
.error
(self, "Syntax Error: unexpected `...`.")
2597 redef class ADebugTypeExpr
2598 redef fun accept_typing
(v
)
2600 var expr
= v
.visit_expr
(self.n_expr
)
2601 if expr
== null then return
2602 var unsafe
= v
.anchor_to
(expr
)
2603 var ntype
= self.n_type
2604 var mtype
= v
.resolve_mtype
(ntype
)
2605 if mtype
!= null and mtype
!= expr
then
2606 var umtype
= v
.anchor_to
(mtype
)
2607 v
.modelbuilder
.warning
(self, "debug", "Found type {expr} (-> {unsafe}), expected {mtype} (-> {umtype})")
2609 self.is_typed
= true