1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2012 Jean Privat <jean@pryen.org>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 # Intraprocedural resolution of static types and OO-services
18 # By OO-services we mean message sending, attribute access, instantiation, etc.
25 redef class ToolContext
26 var typing_phase
: Phase = new TypingPhase(self, [flow_phase
, modelize_property_phase
, local_var_init_phase
])
29 private class TypingPhase
31 redef fun process_npropdef
(npropdef
) do npropdef
.do_typing
(toolcontext
.modelbuilder
)
34 private class TypeVisitor
35 var modelbuilder
: ModelBuilder
37 # The module of the analysis
38 # Used to correctly query the model
39 var mmodule
: MModule is noinit
41 # The static type of the receiver
42 # Mainly used for type tests and type resolutions
43 var anchor
: MClassType is noinit
45 # The analyzed mclassdef
46 var mclassdef
: MClassDef is noinit
48 # The analyzed property
49 var mpropdef
: MPropDef
51 var selfvariable
= new Variable("self")
53 # Is `self` use restricted?
54 # * no explicit `self`
55 # * method called on the implicit self must be top-level
56 # Currently only used for `new` factory since there is no valid receiver inside
57 var is_toplevel_context
= false
61 var mpropdef
= self.mpropdef
62 var mclassdef
= mpropdef
.mclassdef
63 mmodule
= mclassdef
.mmodule
64 self.mclassdef
= mclassdef
65 self.anchor
= mclassdef
.bound_mtype
67 var mclass
= mclassdef
.mclass
69 var selfvariable
= new Variable("self")
70 self.selfvariable
= selfvariable
71 selfvariable
.declared_type
= mclass
.mclass_type
73 var mprop
= mpropdef
.mproperty
74 if mprop
isa MMethod and mprop
.is_new
then
75 is_toplevel_context
= true
79 fun anchor_to
(mtype
: MType): MType
81 return mtype
.anchor_to
(mmodule
, anchor
)
84 fun is_subtype
(sub
, sup
: MType): Bool
86 return sub
.is_subtype
(mmodule
, anchor
, sup
)
89 fun resolve_for
(mtype
, subtype
: MType, for_self
: Bool): MType
91 #print "resolve_for {mtype} sub={subtype} forself={for_self} mmodule={mmodule} anchor={anchor}"
92 var res
= mtype
.resolve_for
(subtype
, anchor
, mmodule
, not for_self
)
96 # Check that `sub` is a subtype of `sup`.
97 # If `sub` is not a valid suptype, then display an error on `node` and return `null`.
98 # If `sub` is a safe subtype of `sup`, then return `sub`.
99 # If `sub` is an unsafe subtype (i.e., an implicit cast is required), then return `sup`.
101 # The point of the return type is to determinate the usable type on an expression when `autocast` is true:
102 # If the suptype is safe, then the return type is the one on the expression typed by `sub`.
103 # Is the subtype is unsafe, then the return type is the one of an implicit cast on `sup`.
104 fun check_subtype
(node
: ANode, sub
, sup
: MType, autocast
: Bool): nullable MType
106 if self.is_subtype
(sub
, sup
) then return sub
107 if autocast
and self.is_subtype
(sub
, self.anchor_to
(sup
)) then
108 # FIXME workaround to the current unsafe typing policy. To remove once fixed virtual types exists.
109 #node.debug("Unsafe typing: expected {sup}, got {sub}")
112 if sup
isa MErrorType then return null # Skip error
113 if sub
.need_anchor
then
114 var u
= anchor_to
(sub
)
115 self.modelbuilder
.error
(node
, "Type Error: expected `{sup}`, got `{sub}: {u}`.")
117 self.modelbuilder
.error
(node
, "Type Error: expected `{sup}`, got `{sub}`.")
122 # Visit an expression and do not care about the return value
123 fun visit_stmt
(nexpr
: nullable AExpr)
125 if nexpr
== null then return
126 nexpr
.accept_typing
(self)
129 # Visit an expression and expects that it is not a statement
130 # Return the type of the expression
131 # Display an error and return null if:
132 # * the type cannot be determined or
133 # * `nexpr` is a statement
134 fun visit_expr
(nexpr
: AExpr): nullable MType
136 nexpr
.accept_typing
(self)
137 var mtype
= nexpr
.mtype
138 if mtype
!= null then return mtype
139 if not nexpr
.is_typed
then
140 if not self.modelbuilder
.toolcontext
.error_count
> 0 then # check that there is really an error
141 if self.modelbuilder
.toolcontext
.verbose_level
> 1 then
142 nexpr
.debug
("No return type but no error.")
145 return null # forward error
147 var more_message
= null
149 if p
!= null then more_message
= p
.bad_expr_message
(nexpr
)
150 if more_message
== null then more_message
= "" else more_message
= " " + more_message
151 self.error
(nexpr
, "Error: expected an expression{more_message}.")
155 # Visit an expression and expect its static type is a least a `sup`
156 # Return the type of the expression or null if
157 # * the type cannot be determined or
158 # * `nexpr` is a statement or
159 # * `nexpr` is not a `sup`
160 fun visit_expr_subtype
(nexpr
: AExpr, sup
: nullable MType): nullable MType
162 var sub
= visit_expr
(nexpr
)
163 if sub
== null then return null # Forward error
165 if sup
== null then return null # Forward error
167 var res
= check_subtype
(nexpr
, sub
, sup
, true)
169 nexpr
.implicit_cast_to
= res
174 # Visit an expression and expect its static type is a `Bool`
175 # Return the type of the expression or null if
176 # * the type cannot be determined or
177 # * `nexpr` is a statement or
178 # * `nexpr` is not a `Bool`
179 fun visit_expr_bool
(nexpr
: AExpr): nullable MType
181 return self.visit_expr_subtype
(nexpr
, self.type_bool
(nexpr
))
184 fun check_expr_cast
(node
: ANode, nexpr
: AExpr, ntype
: AType): nullable MType
186 var sub
= nexpr
.mtype
187 if sub
== null then return null # Forward error
189 var sup
= ntype
.mtype
190 if sup
== null then return null # Forward error
193 self.modelbuilder
.warning
(node
, "useless-type-test", "Warning: expression is already a `{sup}`.")
194 else if self.is_subtype
(sub
, sup
) then
195 self.modelbuilder
.warning
(node
, "useless-type-test", "Warning: expression is already a `{sup}` since it is a `{sub}`.")
200 # Can `mtype` be null (up to the current knowledge)?
201 fun can_be_null
(mtype
: MType): Bool
203 if mtype
isa MNullableType or mtype
isa MNullType then return true
204 if mtype
isa MFormalType then
205 var x
= anchor_to
(mtype
)
206 if x
isa MNullableType or x
isa MNullType then return true
211 # Check that `mtype` can be null (up to the current knowledge).
213 # If not then display a `useless-null-test` warning on node and return false.
215 fun check_can_be_null
(anode
: ANode, mtype
: MType): Bool
217 if mtype
isa MNullType then
218 modelbuilder
.warning
(anode
, "useless-null-test", "Warning: expression is always `null`.")
221 if can_be_null
(mtype
) then return true
223 if mtype
isa MFormalType then
224 var res
= anchor_to
(mtype
)
225 modelbuilder
.warning
(anode
, "useless-null-test", "Warning: expression is not null, since it is a `{mtype}: {res}`.")
227 modelbuilder
.warning
(anode
, "useless-null-test", "Warning: expression is not null, since it is a `{mtype}`.")
232 # Special verification on != and == for null
234 fun null_test
(anode
: ABinopExpr)
236 var mtype
= anode
.n_expr
.mtype
237 var mtype2
= anode
.n_expr2
.mtype
239 if mtype
== null or mtype2
== null then return
241 if not mtype2
isa MNullType then return
243 # Check of useless null
244 if not can_be_null
(mtype
) then return
246 if mtype
isa MNullType then
247 # Because of type adaptation, we cannot just stop here
248 # so return use `null` as a bottom type that will be merged easily (cf) `merge_types`
251 mtype
= mtype
.as_notnull
254 # Check for type adaptation
255 var variable
= anode
.n_expr
.its_variable
256 if variable
== null then return
258 # One is null (mtype2 see above) the other is not null
259 if anode
isa AEqExpr then
260 anode
.after_flow_context
.when_true
.set_var
(self, variable
, mtype2
)
261 anode
.after_flow_context
.when_false
.set_var
(self, variable
, mtype
)
262 else if anode
isa ANeExpr then
263 anode
.after_flow_context
.when_false
.set_var
(self, variable
, mtype2
)
264 anode
.after_flow_context
.when_true
.set_var
(self, variable
, mtype
)
270 fun try_get_mproperty_by_name2
(anode
: ANode, mtype
: MType, name
: String): nullable MProperty
272 return self.modelbuilder
.try_get_mproperty_by_name2
(anode
, mmodule
, mtype
, name
)
275 fun resolve_mtype
(node
: AType): nullable MType
277 return self.modelbuilder
.resolve_mtype
(mclassdef
, node
)
280 fun try_get_mclass
(node
: ANode, name
: String): nullable MClass
282 var mclass
= modelbuilder
.try_get_mclass_by_name
(node
, mmodule
, name
)
286 fun get_mclass
(node
: ANode, name
: String): nullable MClass
288 var mclass
= modelbuilder
.get_mclass_by_name
(node
, mmodule
, name
)
292 fun type_bool
(node
: ANode): nullable MType
294 var mclass
= self.get_mclass
(node
, "Bool")
295 if mclass
== null then return null
296 return mclass
.mclass_type
299 # Construction of a specific callsite according to the current context.
300 # Three entry points exist to create a callsite based on knowledge.
301 # The `build_callsite_by_name` is a top entry point, the method find the mpropdefs to call by the name of this.
302 # see `build_callsite_by_property` and `build_callsite_by_propdef` for more detail.
303 # If you already know the mpropdef to call use directly the `get_method_by_propdef` method
304 # If you just know the mproperty use the `build_callsite_by_property` method to display error if no `mpropdef` is found in the context
305 fun build_callsite_by_name
(node
: ANode, recvtype
: MType, name
: String, recv_is_self
: Bool): nullable CallSite
307 var unsafe_type
= self.anchor_to
(recvtype
)
309 #debug("recv: {recvtype} (aka {unsafe_type})")
310 if recvtype
isa MNullType then
311 var objclass
= get_mclass
(node
, "Object")
312 if objclass
== null then return null # Forward error
313 unsafe_type
= objclass
.mclass_type
316 var mproperty
= self.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
317 if name
== "new" and mproperty
== null then
319 mproperty
= self.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
320 if mproperty
== null then
322 mproperty
= self.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
326 if mproperty
== null then
328 # FIXME This test was added to display a more explicit error when a potential duplication of root object class.
329 if name
== "init" then
330 self.modelbuilder
.error
(node
, "Possible duplication of the root class `Object`")
332 self.modelbuilder
.error
(node
, "Error: method or variable `{name}` unknown in `{recvtype}`.")
334 else if recvtype
.need_anchor
then
335 self.modelbuilder
.error
(node
, "Error: method `{name}` does not exists in `{recvtype}: {unsafe_type}`.")
337 self.modelbuilder
.error
(node
, "Error: method `{name}` does not exists in `{recvtype}`.")
342 assert mproperty
isa MMethod
344 return build_callsite_by_property
(node
, recvtype
, mproperty
, recv_is_self
)
347 # The `build_callsite_by_property` finds the mpropdefs to call by the `MMethod`.
348 # If the mpropdef is found in the context it builds a new `Callsite`.
349 fun build_callsite_by_property
(node
: ANode, recvtype
: MType, mproperty
: MMethod, recv_is_self
: Bool): nullable CallSite
351 var unsafe_type
= self.anchor_to
(recvtype
)
353 if recvtype
isa MNullType then
354 var objclass
= get_mclass
(node
, "Object")
355 if objclass
== null then return null # Forward error
356 unsafe_type
= objclass
.mclass_type
358 # `null` only accepts some methods of object.
359 if recvtype
isa MNullType and not mproperty
.is_null_safe
then
360 self.error
(node
, "Error: method `{mproperty.name}` called on `null`.")
362 else if unsafe_type
isa MNullableType and not mproperty
.is_null_safe
then
363 modelbuilder
.advice
(node
, "call-on-nullable", "Warning: method call on a nullable receiver `{recvtype}`.")
366 if is_toplevel_context
and recv_is_self
and not mproperty
.is_toplevel
then
367 error
(node
, "Error: `{mproperty.name}` is not a top-level method, thus need a receiver.")
369 if not recv_is_self
and mproperty
.is_toplevel
then
370 error
(node
, "Error: cannot call `{mproperty.name}`, a top-level method, with a receiver.")
373 if mproperty
.visibility
== protected_visibility
and not recv_is_self
and self.mmodule
.visibility_for
(mproperty
.intro_mclassdef
.mmodule
) < intrude_visibility
and not modelbuilder
.toolcontext
.opt_ignore_visibility
.value
then
374 self.modelbuilder
.error
(node
, "Error: method `{mproperty.name}` is protected and can only accessed by `self`.")
378 var info
= mproperty
.deprecation
379 if info
!= null and self.mpropdef
.mproperty
.deprecation
== null then
382 self.modelbuilder
.warning
(node
, "deprecated-method", "Deprecation Warning: method `{mproperty.name}` is deprecated: {mdoc.content.first}")
384 self.modelbuilder
.warning
(node
, "deprecated-method", "Deprecation Warning: method `{mproperty.name}` is deprecated.")
388 var propdefs
= mproperty
.lookup_definitions
(self.mmodule
, unsafe_type
)
390 if propdefs
.length
== 0 then
391 self.modelbuilder
.error
(node
, "Type Error: no definition found for property `{mproperty.name}` in `{unsafe_type}`.")
394 else if propdefs
.length
== 1 then
395 mpropdef
= propdefs
.first
397 self.modelbuilder
.warning
(node
, "property-conflict", "Warning: conflicting property definitions for property `{mproperty.name}` in `{unsafe_type}`: {propdefs.join(" ")}")
398 mpropdef
= mproperty
.intro
401 return build_callsite_by_propdef
(node
, recvtype
, mpropdef
, recv_is_self
)
404 # The `build_callsite_by_propdef` builds the callsite directly with the `mprodef` passed in argument.
405 fun build_callsite_by_propdef
(node
: ANode, recvtype
: MType, mpropdef
: MMethodDef, recv_is_self
: Bool): nullable CallSite
407 var msignature
= mpropdef
.msignature
408 if msignature
== null then return null # skip error
409 msignature
= resolve_for
(msignature
, recvtype
, recv_is_self
).as(MSignature)
411 var erasure_cast
= false
412 var rettype
= mpropdef
.msignature
.return_mtype
413 if not recv_is_self
and rettype
!= null then
414 rettype
= rettype
.undecorate
415 if rettype
isa MParameterType then
416 var erased_rettype
= msignature
.return_mtype
417 assert erased_rettype
!= null
418 #node.debug("Erasure cast: Really a {rettype} but unsafely a {erased_rettype}")
423 var callsite
= new CallSite(node
.hot_location
, recvtype
, mmodule
, anchor
, recv_is_self
, mpropdef
.mproperty
, mpropdef
, msignature
, erasure_cast
)
427 fun try_build_callsite_by_name
(node
: ANode, recvtype
: MType, name
: String, recv_is_self
: Bool): nullable CallSite
429 var unsafe_type
= self.anchor_to
(recvtype
)
430 var mproperty
= self.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
431 if mproperty
== null then return null
432 return build_callsite_by_name
(node
, recvtype
, name
, recv_is_self
)
435 # Visit the expressions of args and check their conformity with the corresponding type in signature
436 # The point of this method is to handle varargs correctly
437 # Note: The signature must be correctly adapted
438 fun check_signature
(node
: ANode, args
: Array[AExpr], mproperty
: MProperty, msignature
: MSignature): nullable SignatureMap
440 var vararg_rank
= msignature
.vararg_rank
441 if vararg_rank
>= 0 then
442 if args
.length
< msignature
.arity
then
443 modelbuilder
.error
(node
, "Error: expected at least {msignature.arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
446 else if args
.length
!= msignature
.arity
then
448 if args
.length
> msignature
.arity
then
449 modelbuilder
.error
(node
, "Error: expected {msignature.arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
452 # Other cases are managed later
455 #debug("CALL {unsafe_type}.{msignature}")
457 # Associate each parameter to a position in the arguments
458 var map
= new SignatureMap
460 # Special case for the isolated last argument
461 # TODO: reify this method characteristics (where? the param, the signature, the method?)
462 var last_is_padded
= mproperty
.name
.chars
.last
== '='
463 var nbargs
= args
.length
464 if last_is_padded
then
466 assert not args
.last
isa ANamedargExpr
467 map
.map
[msignature
.arity
- 1] = args
.length
- 1
468 self.visit_expr_subtype
(args
.last
, msignature
.mparameters
.last
.mtype
)
471 # First, handle named arguments
472 for i
in [0..args
.length
[ do
474 if not e
isa ANamedargExpr then continue
475 var name
= e
.n_id
.text
476 var param
= msignature
.mparameter_by_name
(name
)
477 if param
== null then
478 modelbuilder
.error
(e
.n_id
, "Error: no parameter `{name}` for `{mproperty}{msignature}`.")
481 var idx
= msignature
.mparameters
.index_of
(param
)
482 var prev
= map
.map
.get_or_null
(idx
)
484 modelbuilder
.error
(e
, "Error: parameter `{name}` already associated with argument #{prev} for `{mproperty}{msignature}`.")
488 e
.mtype
= self.visit_expr_subtype
(e
.n_expr
, param
.mtype
)
491 # Number of minimum mandatory remaining parameters
494 # Second, associate remaining parameters
495 var vararg_decl
= args
.length
- msignature
.arity
497 for i
in [0..msignature
.arity
[ do
498 # Skip parameters associated by name
499 if map
.map
.has_key
(i
) then continue
501 var param
= msignature
.mparameters
[i
]
503 # Search the next free argument: skip named arguments since they are already associated
504 while j
< nbargs
and args
[j
] isa ANamedargExpr do j
+= 1
506 if not param
.mtype
isa MNullableType then
516 if i
== vararg_rank
then
518 continue # skip the vararg
521 if not param
.is_vararg
then
522 var paramtype
= param
.mtype
523 self.visit_expr_subtype
(arg
, paramtype
)
525 check_one_vararg
(arg
, param
)
529 if min_arity
> 0 then
530 if last_is_padded
then min_arity
+= 1
531 if min_arity
< msignature
.arity
then
532 modelbuilder
.error
(node
, "Error: expected at least {min_arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
534 modelbuilder
.error
(node
, "Error: expected {min_arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
539 # Third, check varargs
540 if vararg_rank
>= 0 then
541 var paramtype
= msignature
.mparameters
[vararg_rank
].mtype
542 var first
= args
[vararg_rank
]
543 if vararg_decl
== 0 then
544 if not check_one_vararg
(first
, msignature
.mparameters
[vararg_rank
]) then return null
546 first
.vararg_decl
= vararg_decl
+ 1
547 for i
in [vararg_rank
..vararg_rank
+vararg_decl
] do
548 self.visit_expr_subtype
(args
[i
], paramtype
)
556 # Check an expression as a single vararg.
557 # The main point of the method if to handle the case of reversed vararg (see `AVarargExpr`)
558 fun check_one_vararg
(arg
: AExpr, param
: MParameter): Bool
560 var paramtype
= param
.mtype
561 var mclass
= get_mclass
(arg
, "Array")
562 if mclass
== null then return false # Forward error
563 var array_mtype
= mclass
.get_mtype
([paramtype
])
564 if arg
isa AVarargExpr then
565 self.visit_expr_subtype
(arg
.n_expr
, array_mtype
)
566 arg
.mtype
= arg
.n_expr
.mtype
568 # only one vararg, maybe `...` was forgot, so be gentle!
569 var t
= visit_expr
(arg
)
570 if t
== null then return false # Forward error
571 if not is_subtype
(t
, paramtype
) and is_subtype
(t
, array_mtype
) then
572 # Not acceptable but could be a `...`
573 error
(arg
, "Type Error: expected `{paramtype}`, got `{t}`. Is an ellipsis `...` missing on the argument?")
576 # Standard valid vararg, finish the job
578 self.visit_expr_subtype
(arg
, paramtype
)
583 fun error
(node
: ANode, message
: String)
585 self.modelbuilder
.error
(node
, message
)
588 fun get_variable
(node
: AExpr, variable
: Variable): nullable MType
590 if not variable
.is_adapted
then return variable
.declared_type
592 var flow
= node
.after_flow_context
593 if flow
== null then return null # skip error
595 if flow
.vars
.has_key
(variable
) then
596 return flow
.vars
[variable
]
598 #node.debug("*** START Collected for {variable}")
599 var mtypes
= flow
.collect_types
(variable
)
600 #node.debug("**** END Collected for {variable}")
601 if mtypes
.length
== 0 then
602 return variable
.declared_type
603 else if mtypes
.length
== 1 then
606 var res
= merge_types
(node
,mtypes
)
608 res
= variable
.declared_type
609 # Try to fallback to a non-null version
610 if res
!= null and can_be_null
(res
) then do
612 if t
!= null and can_be_null
(t
) then break label
622 # Some variables where type-adapted during the visit
625 # Some loops had been visited during the visit
628 fun set_variable
(node
: AExpr, variable
: Variable, mtype
: nullable MType)
630 var flow
= node
.after_flow_context
633 flow
.set_var
(self, variable
, mtype
)
636 # Find the exact representable most specific common super-type in `col`.
638 # Try to find the most specific common type that is a super-type of each types
640 # In most cases, the result is simply the most general type in `col`.
641 # If nullables types are involved, then the nullable information is correctly preserved.
642 # If incomparable super-types exists in `col`, them no solution is given and the `null`
643 # value is returned (since union types are non representable in Nit)
645 # The `null` values in `col` are ignored, nulltypes (MNullType) are considered.
647 # Returns the `null` value if:
650 # * `col` only have null values
651 # * there is a conflict
653 # Example (with a diamond A,B,C,D):
655 # * merge(A,B,C) -> A, because A is the most general type in {A,B,C}
656 # * merge(C,B) -> null, there is conflict, because `B or C` cannot be represented
657 # * merge(A,nullable B) -> nullable A, because A is the most general type and
658 # the nullable information is preserved
659 fun merge_types
(node
: ANode, col
: Array[nullable MType]): nullable MType
661 if col
.length
== 1 then return col
.first
663 if t1
== null then continue # return null
666 if t2
== null then continue # return null
667 if can_be_null
(t2
) and not can_be_null
(t1
) then
670 if not is_subtype
(t2
, t1
) then found
= false
673 #print "merge {col.join(" ")} -> {t1}"
677 #self.modelbuilder.warning(node, "Type Error: {col.length} conflicting types: <{col.join(", ")}>")
681 # Find a most general common subtype between `type1` and `type2`.
683 # Find the most general type that is a subtype of `type2` and, if possible, a subtype of `type1`.
684 # Basically, this return the most specific type between `type1` and `type2`.
685 # If nullable types are involved, the information is correctly preserved.
686 # If `type1` and `type2` are incomparable then `type2` is preferred (since intersection types
687 # are not representable in Nit).
689 # The `null` value is returned if both `type1` and `type2` are null.
691 # Examples (with diamond A,B,C,D):
693 # * intersect_types(A,B) -> B, because B is a subtype of A
694 # * intersect_types(B,A) -> B, because B is a subtype of A
695 # * intersect_types(B,C) -> C, B and C are incomparable,
696 # `type2` is then preferred (`B and C` cannot be represented)
697 # * intersect_types(nullable B,A) -> B, because B<:A and the non-null information is preserved
698 # * intersect_types(B,nullable C) -> C, `type2` is preferred and the non-null information is preserved
699 fun intersect_types
(node
: ANode, type1
, type2
: nullable MType): nullable MType
701 if type1
== null then return type2
702 if type2
== null then return type1
704 if not can_be_null
(type2
) or not can_be_null
(type1
) then
705 type1
= type1
.as_notnull
706 type2
= type2
.as_notnull
710 if is_subtype
(type1
, type2
) then
718 # Find a most general type that is a subtype of `type1` but not one of `type2`.
720 # Basically, this returns `type1`-`type2` but since there is no substraction type
721 # in Nit this just returns `type1` most of the case.
723 # The few other cases are if `type2` is a super-type and if some nullable information
726 # The `null` value is returned if `type1` is null.
728 # Examples (with diamond A,B,C,D):
730 # * diff_types(A,B) -> A, because the notB cannot be represented
731 # * diff_types(B,A) -> None (absurd type), because B<:A
732 # * diff_types(nullable A, nullable B) -> A, because null is removed
733 # * diff_types(nullable B, A) -> Null, because anything but null is removed
734 fun diff_types
(node
: ANode, type1
, type2
: nullable MType): nullable MType
736 if type1
== null then return null
737 if type2
== null then return type1
739 # if t1 <: t2 then t1-t2 = bottom
740 if is_subtype
(type1
, type2
) then
741 return modelbuilder
.model
.null_type
.as_notnull
744 # else if t1 <: nullable t2 then t1-t2 = nulltype
745 if is_subtype
(type1
, type2
.as_nullable
) then
746 return modelbuilder
.model
.null_type
749 # else t2 can be null and type2 must accept null then null is excluded in t1
750 if can_be_null
(type1
) and (type2
isa MNullableType or type2
isa MNullType) then
751 return type1
.as_notnull
758 # Mapping between parameters and arguments in a call.
760 # Parameters and arguments are not stored in the class but referenced by their position (starting from 0)
762 # The point of this class is to help engine and other things to map arguments in the AST to parameters of the model.
764 # Associate a parameter to an argument
765 var map
= new ArrayMap[Int, Int]
768 # A specific method call site with its associated informations.
774 # The static type of the receiver (possibly unresolved)
777 # The module where the callsite is present
780 # The anchor to use with `recv` or `msignature`
781 var anchor
: nullable MClassType
783 # Is the receiver self?
784 # If "for_self", virtual types of the signature are kept
785 # If "not_for_self", virtual type are erased
786 var recv_is_self
: Bool
788 # The designated method
789 var mproperty
: MMethod
791 # The statically designated method definition
792 # The most specif one, it is.
793 var mpropdef
: MMethodDef
795 # The resolved signature for the receiver
796 var msignature
: MSignature
798 # Is a implicit cast required on erasure typing policy?
799 var erasure_cast
: Bool
801 # The mapping used on the call to associate arguments to parameters
802 # If null then no specific association is required.
803 var signaturemap
: nullable SignatureMap = null
805 private fun check_signature
(v
: TypeVisitor, node
: ANode, args
: Array[AExpr]): Bool
807 var map
= v
.check_signature
(node
, args
, self.mproperty
, self.msignature
)
809 if map
== null then is_broken
= true
813 # Information about the callsite to display on a node
814 fun dump_info
(v
: ASTDump): String do
815 return "{recv}.{mpropdef}{msignature}"
818 redef fun mdoc_or_fallback
do return mproperty
.intro
.mdoc
822 # The declared type of the variable
823 var declared_type
: nullable MType = null is writable
825 # Was the variable type-adapted?
826 # This is used to speedup type retrieval while it remains `false`
827 private var is_adapted
= false
830 redef class FlowContext
831 # Store changes of types because of type evolution
832 private var vars
= new HashMap[Variable, nullable MType]
834 # Adapt the variable to a static type
835 # Warning1: do not modify vars directly.
836 # Warning2: sub-flow may have cached a unadapted variable
837 private fun set_var
(v
: TypeVisitor, variable
: Variable, mtype
: nullable MType)
839 if variable
.declared_type
== mtype
and not variable
.is_adapted
then return
840 if vars
.has_key
(variable
) and vars
[variable
] == mtype
then return
841 self.vars
[variable
] = mtype
843 variable
.is_adapted
= true
844 #node.debug "set {variable} to {mtype or else "X"}"
847 # Look in the flow and previous flow and collect all first reachable type adaptation of a local variable
848 private fun collect_types
(variable
: Variable): Array[nullable MType]
850 #node.debug "flow for {variable}"
851 var res
= new Array[nullable MType]
854 var seen
= new HashSet[FlowContext]
855 while not todo
.is_empty
do
857 if f
.is_unreachable
then continue
858 if seen
.has
(f
) then continue
861 if f
.vars
.has_key
(variable
) then
862 # Found something. Collect it and do not process further on this path
863 res
.add f
.vars
[variable
]
864 #f.node.debug "process {variable}: got {f.vars[variable] or else "X"}"
866 todo
.add_all f
.previous
868 if f
.previous
.is_empty
then
869 # Root flowcontext mean a parameter or something related
870 res
.add variable
.declared_type
871 #f.node.debug "root process {variable}: got {variable.declared_type or else "X"}"
875 #self.node.debug "##### end flow for {variable}: {res.join(" ")}"
881 # The entry point of the whole typing analysis
882 fun do_typing
(modelbuilder
: ModelBuilder)
886 # The variable associated to the receiver (if any)
887 var selfvariable
: nullable Variable
890 redef class AMethPropdef
891 redef fun do_typing
(modelbuilder
: ModelBuilder)
893 var mpropdef
= self.mpropdef
894 if mpropdef
== null then return # skip error
896 var v
= new TypeVisitor(modelbuilder
, mpropdef
)
897 self.selfvariable
= v
.selfvariable
899 var mmethoddef
= self.mpropdef
.as(not null)
900 var msignature
= mmethoddef
.msignature
901 if msignature
== null then return # skip error
902 for i
in [0..msignature
.arity
[ do
903 var mtype
= msignature
.mparameters
[i
].mtype
904 if msignature
.vararg_rank
== i
then
905 var arrayclass
= v
.get_mclass
(self.n_signature
.n_params
[i
], "Array")
906 if arrayclass
== null then return # Skip error
907 mtype
= arrayclass
.get_mtype
([mtype
])
909 var variable
= self.n_signature
.n_params
[i
].variable
910 assert variable
!= null
911 variable
.declared_type
= mtype
914 var nblock
= self.n_block
915 if nblock
== null then return
920 if not v
.has_loop
or not v
.dirty
then break
923 var post_visitor
= new PostTypingVisitor(v
)
924 post_visitor
.enter_visit
(self)
926 if not nblock
.after_flow_context
.is_unreachable
and msignature
.return_mtype
!= null then
927 # We reach the end of the function without having a return, it is bad
928 v
.error
(self, "Error: reached end of function; expected `return` with a value.")
933 private class PostTypingVisitor
935 var type_visitor
: TypeVisitor
936 redef fun visit
(n
) do
938 n
.accept_post_typing
(type_visitor
)
939 if n
isa AExpr and n
.mtype
== null and not n
.is_typed
then
946 private fun accept_post_typing
(v
: TypeVisitor) do end
948 # An additional information message to explain the role of a child expression.
950 # The point of the method is to allow some kind of double dispatch so the parent
951 # choose how to describe its children.
952 private fun bad_expr_message
(child
: AExpr): nullable String do return null
955 redef class AAttrPropdef
956 redef fun do_typing
(modelbuilder
: ModelBuilder)
958 if not has_value
then return
960 var mpropdef
= self.mreadpropdef
961 if mpropdef
== null or mpropdef
.msignature
== null then return # skip error
963 var v
= new TypeVisitor(modelbuilder
, mpropdef
)
964 self.selfvariable
= v
.selfvariable
966 var nexpr
= self.n_expr
967 if nexpr
!= null then
968 var mtype
= self.mtype
969 v
.visit_expr_subtype
(nexpr
, mtype
)
971 var nblock
= self.n_block
972 if nblock
!= null then
974 if not nblock
.after_flow_context
.is_unreachable
then
975 # We reach the end of the init without having a return, it is bad
976 v
.error
(self, "Error: reached end of block; expected `return`.")
985 # The static type of the expression.
986 # null if self is a statement or in case of error
987 var mtype
: nullable MType = null
989 # Is the statement correctly typed?
990 # Used to distinguish errors and statements when `mtype == null`
991 var is_typed
: Bool = false
993 # If required, the following implicit cast `.as(XXX)`
994 # Such a cast may by required after evaluating the expression when
995 # a unsafe operation is detected (silently accepted by the Nit language).
996 # The attribute is computed by `check_subtype`
997 var implicit_cast_to
: nullable MType = null
999 # Return the variable read (if any)
1000 # Used to perform adaptive typing
1001 fun its_variable
: nullable Variable do return null
1003 private fun accept_typing
(v
: TypeVisitor)
1005 v
.error
(self, "no implemented accept_typing for {self.class_name}")
1008 # Is non-null if `self` is a leaf of a comprehension array construction.
1009 # In this case, the enclosing literal array node is designated.
1010 # The result of the evaluation of `self` must be
1011 # stored inside the designated array (there is an implicit `push`)
1012 var comprehension
: nullable AArrayExpr = null
1014 # It indicates the number of arguments collected as a vararg.
1016 # When 0, the argument is used as is, without transformation.
1017 # When 1, the argument is transformed into an singleton array.
1018 # Above 1, the arguments and the next ones are transformed into a common array.
1020 # This attribute is meaning less on expressions not used as attributes.
1021 var vararg_decl
: Int = 0
1023 redef fun dump_info
(v
) do
1025 var mtype
= self.mtype
1026 if mtype
!= null then
1027 res
+= v
.yellow
(":{mtype}")
1029 var ict
= self.implicit_cast_to
1031 res
+= v
.yellow
("(.as({ict}))")
1037 redef class ABlockExpr
1038 redef fun accept_typing
(v
)
1040 for e
in self.n_expr
do v
.visit_stmt
(e
)
1041 self.is_typed
= true
1044 # The type of a blockexpr is the one of the last expression (or null if empty)
1047 if self.n_expr
.is_empty
then return null
1048 return self.n_expr
.last
.mtype
1052 redef class AVardeclExpr
1053 redef fun accept_typing
(v
)
1055 var variable
= self.variable
1056 if variable
== null then return # Skip error
1058 var ntype
= self.n_type
1059 var mtype
: nullable MType
1060 if ntype
== null then
1063 mtype
= v
.resolve_mtype
(ntype
)
1064 if mtype
== null then return # Skip error
1067 var nexpr
= self.n_expr
1068 if nexpr
!= null then
1069 if mtype
!= null then
1070 var etype
= v
.visit_expr_subtype
(nexpr
, mtype
)
1071 if etype
== mtype
then
1072 assert ntype
!= null
1073 v
.modelbuilder
.advice
(ntype
, "useless-type", "Warning: useless type definition for variable `{variable.name}`")
1076 mtype
= v
.visit_expr
(nexpr
)
1077 if mtype
== null then return # Skip error
1081 var decltype
= mtype
1082 if mtype
== null or mtype
isa MNullType then
1083 var objclass
= v
.get_mclass
(self, "Object")
1084 if objclass
== null then return # skip error
1085 decltype
= objclass
.mclass_type
.as_nullable
1086 if mtype
== null then mtype
= decltype
1089 variable
.declared_type
= decltype
1090 v
.set_variable
(self, variable
, mtype
)
1092 #debug("var {variable}: {mtype}")
1095 self.is_typed
= true
1099 redef class AVarExpr
1100 redef fun its_variable
do return self.variable
1101 redef fun accept_typing
(v
)
1103 var variable
= self.variable
1104 if variable
== null then return # Skip error
1106 var mtype
= v
.get_variable
(self, variable
)
1107 if mtype
!= null then
1108 #debug("{variable} is {mtype}")
1110 #debug("{variable} is untyped")
1117 redef class AVarAssignExpr
1118 redef fun accept_typing
(v
)
1120 var variable
= self.variable
1121 assert variable
!= null
1123 var mtype
= v
.visit_expr_subtype
(n_value
, variable
.declared_type
)
1125 v
.set_variable
(self, variable
, mtype
)
1127 self.is_typed
= true
1131 redef class AReassignFormExpr
1132 # The method designed by the reassign operator.
1133 var reassign_callsite
: nullable CallSite
1135 var read_type
: nullable MType = null
1137 # Determine the `reassign_property`
1138 # `readtype` is the type of the reading of the left value.
1139 # `writetype` is the type of the writing of the left value.
1140 # (Because of `ACallReassignExpr`, both can be different.
1141 # Return the static type of the value to store.
1142 private fun resolve_reassignment
(v
: TypeVisitor, readtype
, writetype
: MType): nullable MType
1144 var reassign_name
= self.n_assign_op
.operator
1146 self.read_type
= readtype
1148 var callsite
= v
.build_callsite_by_name
(self.n_assign_op
, readtype
, reassign_name
, false)
1149 if callsite
== null then return null # Skip error
1150 self.reassign_callsite
= callsite
1152 var msignature
= callsite
.msignature
1153 var rettype
= msignature
.return_mtype
1154 assert msignature
.arity
== 1 and rettype
!= null
1156 var value_type
= v
.visit_expr_subtype
(self.n_value
, msignature
.mparameters
.first
.mtype
)
1157 if value_type
== null then return null # Skip error
1159 v
.check_subtype
(self, rettype
, writetype
, false)
1164 redef class AVarReassignExpr
1165 redef fun accept_typing
(v
)
1167 var variable
= self.variable
1168 assert variable
!= null
1170 var readtype
= v
.get_variable
(self, variable
)
1171 if readtype
== null then return
1173 read_type
= readtype
1175 var writetype
= variable
.declared_type
1176 if writetype
== null then return
1178 var rettype
= self.resolve_reassignment
(v
, readtype
, writetype
)
1180 v
.set_variable
(self, variable
, rettype
)
1182 self.is_typed
= rettype
!= null
1186 redef class AContinueExpr
1187 redef fun accept_typing
(v
)
1189 var nexpr
= self.n_expr
1190 if nexpr
!= null then
1193 self.is_typed
= true
1197 redef class ABreakExpr
1198 redef fun accept_typing
(v
)
1200 var nexpr
= self.n_expr
1201 if nexpr
!= null then
1204 self.is_typed
= true
1208 redef class AReturnExpr
1209 redef fun accept_typing
(v
)
1211 var nexpr
= self.n_expr
1213 var mpropdef
= v
.mpropdef
1214 if mpropdef
isa MMethodDef then
1215 ret_type
= mpropdef
.msignature
.return_mtype
1216 else if mpropdef
isa MAttributeDef then
1217 ret_type
= mpropdef
.static_mtype
1221 if nexpr
!= null then
1222 if ret_type
!= null then
1223 v
.visit_expr_subtype
(nexpr
, ret_type
)
1226 v
.error
(nexpr
, "Error: `return` with value in a procedure.")
1229 else if ret_type
!= null then
1230 v
.error
(self, "Error: `return` without value in a function.")
1233 self.is_typed
= true
1237 redef class AAbortExpr
1238 redef fun accept_typing
(v
)
1240 self.is_typed
= true
1245 redef fun accept_typing
(v
)
1247 v
.visit_expr_bool
(n_expr
)
1249 v
.visit_stmt
(n_then
)
1250 v
.visit_stmt
(n_else
)
1252 self.is_typed
= true
1254 if n_then
!= null and n_else
== null then
1255 self.mtype
= n_then
.mtype
1260 redef class AIfexprExpr
1261 redef fun accept_typing
(v
)
1263 v
.visit_expr_bool
(n_expr
)
1265 var t1
= v
.visit_expr
(n_then
)
1266 var t2
= v
.visit_expr
(n_else
)
1268 if t1
== null or t2
== null then
1272 var t
= v
.merge_types
(self, [t1
, t2
])
1274 v
.error
(self, "Type Error: ambiguous type `{t1}` vs `{t2}`.")
1281 redef fun accept_typing
(v
)
1283 v
.visit_stmt
(n_block
)
1284 v
.visit_stmt
(n_catch
)
1285 self.is_typed
= true
1289 redef class AWhileExpr
1290 redef fun accept_typing
(v
)
1293 v
.visit_expr_bool
(n_expr
)
1294 v
.visit_stmt
(n_block
)
1295 self.is_typed
= true
1299 redef class ALoopExpr
1300 redef fun accept_typing
(v
)
1303 v
.visit_stmt
(n_block
)
1304 self.is_typed
= true
1308 redef class AForExpr
1309 redef fun accept_typing
(v
)
1313 for g
in n_groups
do
1314 var mtype
= v
.visit_expr
(g
.n_expr
)
1315 if mtype
== null then return
1316 g
.do_type_iterator
(v
, mtype
)
1317 if g
.is_broken
then is_broken
= true
1320 v
.visit_stmt
(n_block
)
1322 self.mtype
= n_block
.mtype
1323 self.is_typed
= true
1327 redef class AForGroup
1328 var coltype
: nullable MClassType
1330 var method_iterator
: nullable CallSite
1331 var method_is_ok
: nullable CallSite
1332 var method_item
: nullable CallSite
1333 var method_next
: nullable CallSite
1334 var method_key
: nullable CallSite
1335 var method_finish
: nullable CallSite
1337 var method_lt
: nullable CallSite
1338 var method_successor
: nullable CallSite
1340 private fun do_type_iterator
(v
: TypeVisitor, mtype
: MType)
1342 if mtype
isa MNullType then
1343 v
.error
(self, "Type Error: `for` cannot iterate over `null`.")
1348 var objcla
= v
.get_mclass
(self, "Object")
1349 if objcla
== null then return
1351 # check iterator method
1352 var itdef
= v
.build_callsite_by_name
(self, mtype
, "iterator", n_expr
isa ASelfExpr)
1353 if itdef
== null then
1354 v
.error
(self, "Type Error: `for` expects a type providing an `iterator` method, got `{mtype}`.")
1357 self.method_iterator
= itdef
1359 # check that iterator return something
1360 var ittype
= itdef
.msignature
.return_mtype
1361 if ittype
== null then
1362 v
.error
(self, "Type Error: `for` expects the method `iterator` to return an `Iterator` or `MapIterator` type.")
1367 var colit_cla
= v
.try_get_mclass
(self, "Iterator")
1368 var mapit_cla
= v
.try_get_mclass
(self, "MapIterator")
1372 if colit_cla
!= null and v
.is_subtype
(ittype
, colit_cla
.get_mtype
([objcla
.mclass_type
.as_nullable
])) then
1374 var coltype
= ittype
.supertype_to
(v
.mmodule
, v
.anchor
, colit_cla
)
1375 var variables
= self.variables
1376 if variables
.length
!= 1 then
1377 v
.error
(self, "Type Error: `for` expects only one variable when using `Iterator`.")
1379 variables
.first
.declared_type
= coltype
.arguments
.first
1384 if mapit_cla
!= null and v
.is_subtype
(ittype
, mapit_cla
.get_mtype
([objcla
.mclass_type
.as_nullable
, objcla
.mclass_type
.as_nullable
])) then
1386 var coltype
= ittype
.supertype_to
(v
.mmodule
, v
.anchor
, mapit_cla
)
1387 var variables
= self.variables
1388 if variables
.length
!= 2 then
1389 v
.error
(self, "Type Error: `for` expects two variables when using `MapIterator`.")
1391 variables
[0].declared_type
= coltype
.arguments
[0]
1392 variables
[1].declared_type
= coltype
.arguments
[1]
1397 if not is_col
and not is_map
then
1398 v
.error
(self, "Type Error: `for` expects the method `iterator` to return an `Iterator` or `MapIterator` type.")
1402 # anchor formal and virtual types
1403 if mtype
.need_anchor
then mtype
= v
.anchor_to
(mtype
)
1405 mtype
= mtype
.undecorate
1406 self.coltype
= mtype
.as(MClassType)
1408 # get methods is_ok, next, item
1409 var ikdef
= v
.build_callsite_by_name
(self, ittype
, "is_ok", false)
1410 if ikdef
== null then
1411 v
.error
(self, "Type Error: `for` expects a method `is_ok` in type `{ittype}`.")
1414 self.method_is_ok
= ikdef
1416 var itemdef
= v
.build_callsite_by_name
(self, ittype
, "item", false)
1417 if itemdef
== null then
1418 v
.error
(self, "Type Error: `for` expects a method `item` in type `{ittype}`.")
1421 self.method_item
= itemdef
1423 var nextdef
= v
.build_callsite_by_name
(self, ittype
, "next", false)
1424 if nextdef
== null then
1425 v
.error
(self, "Type Error: `for` expects a method `next` in type {ittype}.")
1428 self.method_next
= nextdef
1430 self.method_finish
= v
.try_build_callsite_by_name
(self, ittype
, "finish", false)
1433 var keydef
= v
.build_callsite_by_name
(self, ittype
, "key", false)
1434 if keydef
== null then
1435 v
.error
(self, "Type Error: `for` expects a method `key` in type `{ittype}`.")
1438 self.method_key
= keydef
1441 if self.variables
.length
== 1 and n_expr
isa ARangeExpr then
1442 var variable
= variables
.first
1443 var vtype
= variable
.declared_type
.as(not null)
1445 if n_expr
isa AOrangeExpr then
1446 self.method_lt
= v
.build_callsite_by_name
(self, vtype
, "<", false)
1448 self.method_lt
= v
.build_callsite_by_name
(self, vtype
, "<=", false)
1451 self.method_successor
= v
.build_callsite_by_name
(self, vtype
, "successor", false)
1456 redef class AWithExpr
1457 var method_start
: nullable CallSite
1458 var method_finish
: nullable CallSite
1460 redef fun accept_typing
(v
: TypeVisitor)
1462 var mtype
= v
.visit_expr
(n_expr
)
1463 if mtype
== null then return
1465 method_start
= v
.build_callsite_by_name
(self, mtype
, "start", n_expr
isa ASelfExpr)
1466 method_finish
= v
.build_callsite_by_name
(self, mtype
, "finish", n_expr
isa ASelfExpr)
1468 v
.visit_stmt
(n_block
)
1469 self.mtype
= n_block
.mtype
1470 self.is_typed
= true
1474 redef class AAssertExpr
1475 redef fun accept_typing
(v
)
1477 v
.visit_expr_bool
(n_expr
)
1479 v
.visit_stmt
(n_else
)
1480 self.is_typed
= true
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 AImpliesExpr
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 AAndExpr
1503 redef fun accept_typing
(v
)
1505 v
.visit_expr_bool
(n_expr
)
1506 v
.visit_expr_bool
(n_expr2
)
1507 self.mtype
= v
.type_bool
(self)
1511 redef class ANotExpr
1512 redef fun accept_typing
(v
)
1514 v
.visit_expr_bool
(n_expr
)
1515 self.mtype
= v
.type_bool
(self)
1519 redef class AOrElseExpr
1520 redef fun accept_typing
(v
)
1522 var t1
= v
.visit_expr
(n_expr
)
1523 var t2
= v
.visit_expr
(n_expr2
)
1525 if t1
== null or t2
== null then
1529 if t1
isa MNullType then
1532 else if v
.can_be_null
(t1
) then
1536 var t
= v
.merge_types
(self, [t1
, t2
])
1538 var c
= v
.get_mclass
(self, "Object")
1539 if c
== null then return # forward error
1541 if v
.can_be_null
(t2
) then
1544 #v.error(self, "Type Error: ambiguous type {t1} vs {t2}")
1549 redef fun accept_post_typing
(v
)
1551 var t1
= n_expr
.mtype
1555 v
.check_can_be_null
(n_expr
, t1
)
1560 redef class ATrueExpr
1561 redef fun accept_typing
(v
)
1563 self.mtype
= v
.type_bool
(self)
1567 redef class AFalseExpr
1568 redef fun accept_typing
(v
)
1570 self.mtype
= v
.type_bool
(self)
1574 redef class AIntegerExpr
1575 redef fun accept_typing
(v
)
1577 var mclass
: nullable MClass = null
1578 if value
isa Byte then
1579 mclass
= v
.get_mclass
(self, "Byte")
1580 else if value
isa Int then
1581 mclass
= v
.get_mclass
(self, "Int")
1582 else if value
isa Int8 then
1583 mclass
= v
.get_mclass
(self, "Int8")
1584 else if value
isa Int16 then
1585 mclass
= v
.get_mclass
(self, "Int16")
1586 else if value
isa UInt16 then
1587 mclass
= v
.get_mclass
(self, "UInt16")
1588 else if value
isa Int32 then
1589 mclass
= v
.get_mclass
(self, "Int32")
1590 else if value
isa UInt32 then
1591 mclass
= v
.get_mclass
(self, "UInt32")
1593 if mclass
== null then return # Forward error
1594 self.mtype
= mclass
.mclass_type
1598 redef class AFloatExpr
1599 redef fun accept_typing
(v
)
1601 var mclass
= v
.get_mclass
(self, "Float")
1602 if mclass
== null then return # Forward error
1603 self.mtype
= mclass
.mclass_type
1607 redef class ACharExpr
1608 redef fun accept_typing
(v
) do
1609 var mclass
: nullable MClass = null
1610 if is_code_point
then
1611 mclass
= v
.get_mclass
(self, "Int")
1613 mclass
= v
.get_mclass
(self, "Char")
1615 if mclass
== null then return # Forward error
1616 self.mtype
= mclass
.mclass_type
1620 redef class AugmentedStringFormExpr
1623 # Text::to_re, used for prefix `re`
1624 var to_re
: nullable CallSite = null
1625 # Regex::ignore_case, used for suffix `i` on `re`
1626 var ignore_case
: nullable CallSite = null
1627 # Regex::newline, used for suffix `m` on `re`
1628 var newline
: nullable CallSite = null
1629 # Regex::extended, used for suffix `b` on `re`
1630 var extended
: nullable CallSite = null
1631 # CString::to_bytes_with_copy, used for prefix `b`
1632 var to_bytes_with_copy
: nullable CallSite = null
1634 redef fun accept_typing
(v
) do
1635 var mclass
= v
.get_mclass
(self, "String")
1636 if mclass
== null then return # Forward error
1637 if is_bytestring
then
1638 to_bytes_with_copy
= v
.build_callsite_by_name
(self, v
.mmodule
.c_string_type
, "to_bytes_with_copy", false)
1639 mclass
= v
.get_mclass
(self, "Bytes")
1641 to_re
= v
.build_callsite_by_name
(self, mclass
.mclass_type
, "to_re", false)
1642 for i
in suffix
.chars
do
1643 mclass
= v
.get_mclass
(self, "Regex")
1644 if mclass
== null then
1645 v
.error
(self, "Error: `Regex` class unknown")
1650 service
= "ignore_case="
1651 ignore_case
= v
.build_callsite_by_name
(self, mclass
.mclass_type
, service
, false)
1652 else if i
== 'm' then
1653 service
= "newline="
1654 newline
= v
.build_callsite_by_name
(self, mclass
.mclass_type
, service
, false)
1655 else if i
== 'b' then
1656 service
= "extended="
1657 extended
= v
.build_callsite_by_name
(self, mclass
.mclass_type
, service
, false)
1659 v
.error
(self, "Type Error: Unrecognized suffix {i} in prefixed Regex")
1664 if mclass
== null then return # Forward error
1665 mtype
= mclass
.mclass_type
1669 redef class ASuperstringExpr
1670 redef fun accept_typing
(v
)
1673 var objclass
= v
.get_mclass
(self, "Object")
1674 if objclass
== null then return # Forward error
1675 var objtype
= objclass
.mclass_type
1676 for nexpr
in self.n_exprs
do
1677 v
.visit_expr_subtype
(nexpr
, objtype
)
1682 redef class AArrayExpr
1683 # The `with_capacity` method on Array
1684 var with_capacity_callsite
: nullable CallSite
1686 # The `push` method on arrays
1687 var push_callsite
: nullable CallSite
1689 # The element of each type
1690 var element_mtype
: nullable MType
1692 # Set that `self` is a part of comprehension array `na`
1693 # If `self` is a `for`, or a `if`, then `set_comprehension` is recursively applied.
1694 private fun set_comprehension
(n
: nullable AExpr)
1698 else if n
isa AForExpr then
1699 set_comprehension
(n
.n_block
)
1700 else if n
isa AIfExpr then
1701 set_comprehension
(n
.n_then
)
1702 set_comprehension
(n
.n_else
)
1705 n
.comprehension
= self
1708 redef fun accept_typing
(v
)
1710 var mtype
: nullable MType = null
1711 var ntype
= self.n_type
1712 if ntype
!= null then
1713 mtype
= v
.resolve_mtype
(ntype
)
1714 if mtype
== null then return # Skip error
1716 var mtypes
= new Array[nullable MType]
1718 for e
in self.n_exprs
do
1719 var t
= v
.visit_expr
(e
)
1723 set_comprehension
(e
)
1724 if mtype
!= null then
1725 if v
.check_subtype
(e
, t
, mtype
, false) == null then return # Forward error
1726 if t
== mtype
then useless
= true
1731 if mtype
== null then
1732 # Ensure monotony for type adaptation on loops
1733 if self.element_mtype
!= null then mtypes
.add
self.element_mtype
1734 mtype
= v
.merge_types
(self, mtypes
)
1736 if mtype
== null or mtype
isa MNullType then
1737 v
.error
(self, "Type Error: ambiguous array type {mtypes.join(" ")}")
1741 assert ntype
!= null
1742 v
.modelbuilder
.warning
(ntype
, "useless-type", "Warning: useless type declaration `{mtype}` in literal Array since it can be inferred from the elements type.")
1745 self.element_mtype
= mtype
1747 var mclass
= v
.get_mclass
(self, "Array")
1748 if mclass
== null then return # Forward error
1749 var array_mtype
= mclass
.get_mtype
([mtype
])
1751 with_capacity_callsite
= v
.build_callsite_by_name
(self, array_mtype
, "with_capacity", false)
1752 push_callsite
= v
.build_callsite_by_name
(self, array_mtype
, "push", false)
1754 self.mtype
= array_mtype
1758 redef class ARangeExpr
1759 var init_callsite
: nullable CallSite
1761 redef fun accept_typing
(v
)
1763 var discrete_class
= v
.get_mclass
(self, "Discrete")
1764 if discrete_class
== null then return # Forward error
1765 var discrete_type
= discrete_class
.intro
.bound_mtype
1766 var t1
= v
.visit_expr_subtype
(self.n_expr
, discrete_type
)
1767 var t2
= v
.visit_expr_subtype
(self.n_expr2
, discrete_type
)
1768 if t1
== null or t2
== null then return
1769 var mclass
= v
.get_mclass
(self, "Range")
1770 if mclass
== null then return # Forward error
1772 if v
.is_subtype
(t1
, t2
) then
1773 mtype
= mclass
.get_mtype
([t2
])
1774 else if v
.is_subtype
(t2
, t1
) then
1775 mtype
= mclass
.get_mtype
([t1
])
1777 v
.error
(self, "Type Error: cannot create range: `{t1}` vs `{t2}`.")
1783 # get the constructor
1785 if self isa ACrangeExpr then
1786 callsite
= v
.build_callsite_by_name
(self, mtype
, "defaultinit", false)
1787 else if self isa AOrangeExpr then
1788 callsite
= v
.build_callsite_by_name
(self, mtype
, "without_last", false)
1792 init_callsite
= callsite
1796 redef class ANullExpr
1797 redef fun accept_typing
(v
)
1799 self.mtype
= v
.mmodule
.model
.null_type
1803 redef class AIsaExpr
1804 # The static type to cast to.
1805 # (different from the static type of the expression that is `Bool`).
1806 var cast_type
: nullable MType
1807 redef fun accept_typing
(v
)
1809 v
.visit_expr
(n_expr
)
1811 var mtype
= v
.resolve_mtype
(n_type
)
1813 self.cast_type
= mtype
1815 var variable
= self.n_expr
.its_variable
1816 if variable
!= null then
1817 var orig
= self.n_expr
.mtype
1818 #var from = if orig != null then orig.to_s else "invalid"
1819 #var to = if mtype != null then mtype.to_s else "invalid"
1820 #debug("adapt {variable}: {from} -> {to}")
1822 var thentype
= v
.intersect_types
(self, orig
, mtype
)
1823 if thentype
!= orig
then
1824 self.after_flow_context
.when_true
.set_var
(v
, variable
, thentype
)
1825 #debug "{variable}:{orig or else "?"} isa {mtype or else "?"} -> then {thentype or else "?"}"
1828 var elsetype
= v
.diff_types
(self, orig
, mtype
)
1829 if elsetype
!= orig
then
1830 self.after_flow_context
.when_false
.set_var
(v
, variable
, elsetype
)
1831 #debug "{variable}:{orig or else "?"} isa {mtype or else "?"} -> else {elsetype or else "?"}"
1835 self.mtype
= v
.type_bool
(self)
1838 redef fun accept_post_typing
(v
)
1840 v
.check_expr_cast
(self, self.n_expr
, self.n_type
)
1843 redef fun dump_info
(v
) do
1845 var mtype
= self.cast_type
1846 if mtype
!= null then
1847 res
+= v
.yellow
(".as({mtype})")
1854 redef class AAsCastExpr
1855 redef fun accept_typing
(v
)
1857 v
.visit_expr
(n_expr
)
1859 self.mtype
= v
.resolve_mtype
(n_type
)
1862 redef fun accept_post_typing
(v
)
1864 v
.check_expr_cast
(self, self.n_expr
, self.n_type
)
1868 redef class AAsNotnullExpr
1869 redef fun accept_typing
(v
)
1871 var mtype
= v
.visit_expr
(self.n_expr
)
1872 if mtype
== null then return # Forward error
1874 if mtype
isa MNullType then
1875 v
.error
(self, "Type Error: `as(not null)` on `null`.")
1879 if v
.can_be_null
(mtype
) then
1880 mtype
= mtype
.as_notnull
1886 redef fun accept_post_typing
(v
)
1888 var mtype
= n_expr
.mtype
1889 if mtype
== null then return
1890 v
.check_can_be_null
(n_expr
, mtype
)
1894 redef class AParExpr
1895 redef fun accept_typing
(v
)
1897 self.mtype
= v
.visit_expr
(self.n_expr
)
1901 redef class AOnceExpr
1902 redef fun accept_typing
(v
)
1904 self.mtype
= v
.visit_expr
(self.n_expr
)
1908 redef class ASelfExpr
1909 redef var its_variable
: nullable Variable
1910 redef fun accept_typing
(v
)
1912 if v
.is_toplevel_context
and not self isa AImplicitSelfExpr then
1913 v
.error
(self, "Error: `self` cannot be used in top-level method.")
1915 var variable
= v
.selfvariable
1916 self.its_variable
= variable
1917 self.mtype
= v
.get_variable
(self, variable
)
1921 redef class AImplicitSelfExpr
1922 # Is the implicit receiver `sys`?
1924 # By default, the implicit receiver is `self`.
1925 # But when there is not method for `self`, `sys` is used as a fall-back.
1926 # Is this case this flag is set to `true`.
1930 ## MESSAGE SENDING AND PROPERTY
1932 redef class ASendExpr
1933 # The property invoked by the send.
1934 var callsite
: nullable CallSite
1936 # Is self a safe call (with `x?.foo`)?
1937 # If so and the receiver is null, then the arguments won't be evaluated
1938 # and the call skipped (replaced with null).
1939 var is_safe
: Bool = false
1941 redef fun bad_expr_message
(child
)
1943 if child
== self.n_expr
then
1944 return "to be the receiver of `{self.property_name}`"
1949 redef fun accept_typing
(v
)
1951 var nrecv
= self.n_expr
1952 var recvtype
= v
.visit_expr
(nrecv
)
1954 if nrecv
isa ASafeExpr then
1955 # Has the receiver the form `x?.foo`?
1956 # For parsing "reasons" the `?` is in the receiver node, not the call node.
1960 var name
= self.property_name
1961 var node
= self.property_node
1963 if recvtype
== null then return # Forward error
1966 var unsafe_type
= v
.anchor_to
(recvtype
)
1967 var mproperty
= v
.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
1968 if mproperty
== null and nrecv
isa AImplicitSelfExpr then
1969 # Special fall-back search in `sys` when noting found in the implicit receiver.
1970 var sysclass
= v
.try_get_mclass
(node
, "Sys")
1971 if sysclass
!= null then
1972 var systype
= sysclass
.mclass_type
1973 mproperty
= v
.try_get_mproperty_by_name2
(node
, systype
, name
)
1974 if mproperty
!= null then
1975 callsite
= v
.build_callsite_by_name
(node
, systype
, name
, false)
1976 if callsite
== null then return # Forward error
1977 # Update information, we are looking at `sys` now, not `self`
1979 nrecv
.its_variable
= null
1980 nrecv
.mtype
= systype
1985 if callsite
== null then
1986 # If still nothing, just exit
1987 callsite
= v
.build_callsite_by_name
(node
, recvtype
, name
, nrecv
isa ASelfExpr)
1988 if callsite
== null then return
1991 self.callsite
= callsite
1992 var msignature
= callsite
.msignature
1994 var args
= compute_raw_arguments
1996 if not self isa ACallrefExpr then
1997 callsite
.check_signature
(v
, node
, args
)
2000 if callsite
.mproperty
.is_init
then
2001 var vmpropdef
= v
.mpropdef
2002 if not (vmpropdef
isa MMethodDef and vmpropdef
.mproperty
.is_init
) then
2003 v
.error
(node
, "Error: an `init` can only be called from another `init`.")
2005 if vmpropdef
isa MMethodDef and vmpropdef
.mproperty
.is_root_init
and not callsite
.mproperty
.is_root_init
then
2006 v
.error
(node
, "Error: `{vmpropdef}` cannot call a factory `{callsite.mproperty}`.")
2010 var ret
= msignature
.return_mtype
2013 # A safe receiver makes that the call is not executed and returns null
2014 ret
= ret
.as_nullable
2018 self.is_typed
= true
2022 # The name of the property
2023 # Each subclass simply provide the correct name.
2024 private fun property_name
: String is abstract
2026 # The node identifying the name (id, operator, etc) for messages.
2028 # Is `self` by default
2029 private fun property_node
: ANode do return self
2031 # An array of all arguments (excluding self)
2032 fun raw_arguments
: Array[AExpr] do return compute_raw_arguments
2034 private fun compute_raw_arguments
: Array[AExpr] is abstract
2036 redef fun dump_info
(v
) do
2038 var callsite
= self.callsite
2039 if callsite
!= null then
2040 res
+= v
.yellow
(" call="+callsite
.dump_info
(v
))
2046 redef class ABinopExpr
2047 redef fun compute_raw_arguments
do return [n_expr2
]
2048 redef fun property_name
do return operator
2049 redef fun property_node
do return n_op
2052 redef class AEqFormExpr
2053 redef fun accept_typing
(v
)
2059 redef fun accept_post_typing
(v
)
2061 var mtype
= n_expr
.mtype
2062 var mtype2
= n_expr2
.mtype
2064 if mtype
== null or mtype2
== null then return
2066 if mtype
== v
.type_bool
(self) and (n_expr2
isa AFalseExpr or n_expr2
isa ATrueExpr) then
2067 v
.modelbuilder
.warning
(self, "useless-truism", "Warning: useless comparison to a Bool literal.")
2070 if not mtype2
isa MNullType then return
2072 v
.check_can_be_null
(n_expr
, mtype
)
2076 redef class AUnaryopExpr
2077 redef fun property_name
do return "unary {operator}"
2078 redef fun compute_raw_arguments
do return new Array[AExpr]
2081 redef class ACallExpr
2082 redef fun property_name
do return n_qid
.n_id
.text
2083 redef fun property_node
do return n_qid
2084 redef fun compute_raw_arguments
do return n_args
.to_a
2087 redef class ACallAssignExpr
2088 redef fun property_name
do return n_qid
.n_id
.text
+ "="
2089 redef fun property_node
do return n_qid
2090 redef fun compute_raw_arguments
2092 var res
= n_args
.to_a
2098 redef class ABraExpr
2099 redef fun property_name
do return "[]"
2100 redef fun compute_raw_arguments
do return n_args
.to_a
2103 redef class ABraAssignExpr
2104 redef fun property_name
do return "[]="
2105 redef fun compute_raw_arguments
2107 var res
= n_args
.to_a
2113 redef class ASendReassignFormExpr
2114 # The property invoked for the writing
2115 var write_callsite
: nullable CallSite
2117 redef fun accept_typing
(v
)
2119 var recvtype
= v
.visit_expr
(self.n_expr
)
2120 var name
= self.property_name
2121 var node
= self.property_node
2123 if recvtype
== null then return # Forward error
2125 var for_self
= self.n_expr
isa ASelfExpr
2126 var callsite
= v
.build_callsite_by_name
(node
, recvtype
, name
, for_self
)
2128 if callsite
== null then return
2129 self.callsite
= callsite
2131 var args
= compute_raw_arguments
2133 callsite
.check_signature
(v
, node
, args
)
2135 var readtype
= callsite
.msignature
.return_mtype
2136 if readtype
== null then
2137 v
.error
(node
, "Error: `{name}` is not a function.")
2141 var wcallsite
= v
.build_callsite_by_name
(node
, recvtype
, name
+ "=", self.n_expr
isa ASelfExpr)
2142 if wcallsite
== null then return
2143 self.write_callsite
= wcallsite
2145 var wtype
= self.resolve_reassignment
(v
, readtype
, wcallsite
.msignature
.mparameters
.last
.mtype
)
2146 if wtype
== null then return
2148 args
= args
.to_a
# duplicate so raw_arguments keeps only the getter args
2149 args
.add
(self.n_value
)
2150 wcallsite
.check_signature
(v
, node
, args
)
2152 self.is_typed
= true
2156 redef class ACallReassignExpr
2157 redef fun property_name
do return n_qid
.n_id
.text
2158 redef fun property_node
do return n_qid
.n_id
2159 redef fun compute_raw_arguments
do return n_args
.to_a
2162 redef class ABraReassignExpr
2163 redef fun property_name
do return "[]"
2164 redef fun compute_raw_arguments
do return n_args
.to_a
2167 redef class AInitExpr
2168 redef fun property_name
do if n_args
.n_exprs
.is_empty
then return "init" else return "defaultinit"
2169 redef fun property_node
do return n_kwinit
2170 redef fun compute_raw_arguments
do return n_args
.to_a
2173 redef class ACallrefExpr
2174 redef fun property_name
do return n_qid
.n_id
.text
2175 redef fun property_node
do return n_qid
2176 redef fun compute_raw_arguments
do return n_args
.to_a
2178 redef fun accept_typing
(v
)
2180 super # do the job as if it was a real call
2181 var res
= callsite
.mproperty
2183 var msignature
= callsite
.mpropdef
.msignature
2184 var recv
= callsite
.recv
2185 assert msignature
!= null
2186 var arity
= msignature
.mparameters
.length
2188 var routine_type_name
= "ProcRef"
2189 if msignature
.return_mtype
!= null then
2190 routine_type_name
= "FunRef"
2193 var target_routine_class
= "{routine_type_name}{arity}"
2194 var routine_mclass
= v
.get_mclass
(self, target_routine_class
)
2196 if routine_mclass
== null then
2197 v
.error
(self, "Error: missing functional types, try `import functional`")
2201 var types_list
= new Array[MType]
2202 for param
in msignature
.mparameters
do
2203 if param
.is_vararg
then
2204 types_list
.push
(v
.mmodule
.array_type
(param
.mtype
))
2206 types_list
.push
(param
.mtype
)
2209 if msignature
.return_mtype
!= null then
2210 types_list
.push
(msignature
.return_mtype
.as(not null))
2213 # Why we need an anchor :
2217 # def toto(x: E) do print "{x}"
2220 # var a = new A[Int]
2221 # var f = &a.toto # without anchor : ProcRef1[E]
2222 # # with anchor : ProcRef[Int]
2224 # However, we can only anchor if we can resolve every formal
2225 # parameter, here's an example where we can't.
2228 # fun bar: A[E] do return self
2229 # fun foo: Fun0[A[E]] do return &bar # here we can't anchor
2231 # var f1 = a1.foo # when this expression will be evaluated,
2232 # # `a1` will anchor `&bar` returned by `foo`.
2235 var routine_type
= routine_mclass
.get_mtype
(types_list
)
2236 if not recv
.need_anchor
then
2237 routine_type
= routine_type
.anchor_to
(v
.mmodule
, recv
.as(MClassType))
2240 self.mtype
= routine_type
2245 fun to_a
: Array[AExpr] do return self.n_exprs
.to_a
2250 redef class ASuperExpr
2251 # The method to call if the super is in fact a 'super init call'
2252 # Note: if the super is a normal call-next-method, then this attribute is null
2253 var callsite
: nullable CallSite
2255 # The method to call is the super is a standard `call-next-method` super-call
2256 # Note: if the super is a special super-init-call, then this attribute is null
2257 var mpropdef
: nullable MMethodDef
2259 redef fun accept_typing
(v
)
2261 var anchor
= v
.anchor
2262 var recvtype
= v
.get_variable
(self, v
.selfvariable
)
2263 assert recvtype
!= null
2264 var mproperty
= v
.mpropdef
.mproperty
2265 if not mproperty
isa MMethod then
2266 v
.error
(self, "Error: `super` only usable in a `method`.")
2269 var superprops
= mproperty
.lookup_super_definitions
(v
.mmodule
, anchor
)
2270 if superprops
.length
== 0 then
2271 if mproperty
.is_init
and v
.mpropdef
.is_intro
then
2272 process_superinit
(v
)
2275 v
.error
(self, "Error: no super method to call for `{mproperty}`.")
2278 # FIXME: covariance of return type in linear extension?
2279 var superprop
= superprops
.first
2281 var msignature
= superprop
.msignature
.as(not null)
2282 msignature
= v
.resolve_for
(msignature
, recvtype
, true).as(MSignature)
2283 var args
= self.n_args
.to_a
2284 if args
.length
> 0 then
2285 signaturemap
= v
.check_signature
(self, args
, mproperty
, msignature
)
2287 self.mtype
= msignature
.return_mtype
2288 self.is_typed
= true
2289 v
.mpropdef
.has_supercall
= true
2290 mpropdef
= v
.mpropdef
.as(MMethodDef)
2293 # The mapping used on the call to associate arguments to parameters.
2294 # If null then no specific association is required.
2295 var signaturemap
: nullable SignatureMap
2297 private fun process_superinit
(v
: TypeVisitor)
2299 var anchor
= v
.anchor
2300 var recvtype
= v
.get_variable
(self, v
.selfvariable
)
2301 assert recvtype
!= null
2302 var mpropdef
= v
.mpropdef
2303 assert mpropdef
isa MMethodDef
2304 var mproperty
= mpropdef
.mproperty
2305 var superprop
: nullable MMethodDef = null
2306 for msupertype
in mpropdef
.mclassdef
.supertypes
do
2307 msupertype
= msupertype
.anchor_to
(v
.mmodule
, anchor
)
2308 var errcount
= v
.modelbuilder
.toolcontext
.error_count
2309 var candidate
= v
.try_get_mproperty_by_name2
(self, msupertype
, mproperty
.name
).as(nullable MMethod)
2310 if candidate
== null then
2311 if v
.modelbuilder
.toolcontext
.error_count
> errcount
then return # Forward error
2312 continue # Try next super-class
2314 if superprop
!= null and candidate
.is_root_init
then
2317 if superprop
!= null and superprop
.mproperty
!= candidate
and not superprop
.mproperty
.is_root_init
then
2318 v
.error
(self, "Error: conflicting super constructor to call for `{mproperty}`: `{candidate.full_name}`, `{superprop.mproperty.full_name}`")
2321 var candidatedefs
= candidate
.lookup_definitions
(v
.mmodule
, anchor
)
2322 if superprop
!= null and superprop
.mproperty
== candidate
then
2323 if superprop
== candidatedefs
.first
then continue
2324 candidatedefs
.add
(superprop
)
2326 if candidatedefs
.length
> 1 then
2327 v
.error
(self, "Error: conflicting property definitions for property `{mproperty}` in `{recvtype}`: {candidatedefs.join(", ")}")
2330 superprop
= candidatedefs
.first
2332 if superprop
== null then
2333 v
.error
(self, "Error: no super method to call for `{mproperty}`.")
2337 var msignature
= superprop
.msignature
.as(not null)
2338 msignature
= v
.resolve_for
(msignature
, recvtype
, true).as(MSignature)
2340 var callsite
= new CallSite(hot_location
, recvtype
, v
.mmodule
, v
.anchor
, true, superprop
.mproperty
, superprop
, msignature
, false)
2341 self.callsite
= callsite
2343 var args
= self.n_args
.to_a
2344 if args
.length
> 0 then
2345 callsite
.check_signature
(v
, self, args
)
2347 # Check there is at least enough parameters
2348 if mpropdef
.msignature
.arity
< msignature
.arity
then
2349 v
.error
(self, "Error: not enough implicit arguments to pass. Got `{mpropdef.msignature.arity}`, expected at least `{msignature.arity}`. Signature is `{msignature}`.")
2352 # Check that each needed parameter is conform
2354 for sp
in msignature
.mparameters
do
2355 var p
= mpropdef
.msignature
.mparameters
[i
]
2356 if not v
.is_subtype
(p
.mtype
, sp
.mtype
) then
2357 v
.error
(self, "Type Error: expected argument #{i} of type `{sp.mtype}`, got implicit argument `{p.name}` of type `{p.mtype}`. Signature is {msignature}")
2364 self.is_typed
= true
2367 redef fun dump_info
(v
) do
2369 var callsite
= self.callsite
2370 if callsite
!= null then
2371 res
+= v
.yellow
(" super-init="+callsite
.dump_info
(v
))
2373 var mpropdef
= self.mpropdef
2374 if mpropdef
!= null then
2375 res
+= v
.yellow
(" call-next-method="+mpropdef
.to_s
)
2383 redef class ANewExpr
2384 # The constructor invoked by the new.
2385 var callsite
: nullable CallSite
2387 # The designated type
2388 var recvtype
: nullable MClassType
2390 redef fun accept_typing
(v
)
2392 var recvtype
= v
.resolve_mtype
(self.n_type
)
2393 if recvtype
== null then return
2395 if not recvtype
isa MClassType then
2396 if recvtype
isa MNullableType then
2397 v
.error
(self, "Type Error: cannot instantiate the nullable type `{recvtype}`.")
2399 else if recvtype
isa MFormalType then
2400 v
.error
(self, "Type Error: cannot instantiate the formal type `{recvtype}`.")
2403 v
.error
(self, "Type Error: cannot instantiate the type `{recvtype}`.")
2408 self.recvtype
= recvtype
2409 var kind
= recvtype
.mclass
.kind
2412 var nqid
= self.n_qid
2414 if nqid
!= null then
2415 name
= nqid
.n_id
.text
2421 if name
== "intern" then
2422 if kind
!= concrete_kind
then
2423 v
.error
(self, "Type Error: cannot instantiate {kind} {recvtype}.")
2426 if n_args
.n_exprs
.not_empty
then
2427 v
.error
(n_args
, "Type Error: the intern constructor expects no arguments.")
2431 self.mtype
= recvtype
2435 var callsite
= v
.build_callsite_by_name
(node
, recvtype
, name
, false)
2436 if callsite
== null then return
2438 if not callsite
.mproperty
.is_new
then
2439 if kind
!= concrete_kind
then
2440 v
.error
(self, "Type Error: cannot instantiate {kind} `{recvtype}`.")
2443 self.mtype
= recvtype
2445 self.mtype
= callsite
.msignature
.return_mtype
2446 assert self.mtype
!= null
2449 self.callsite
= callsite
2451 if not callsite
.mproperty
.is_init_for
(recvtype
.mclass
) then
2452 v
.error
(self, "Error: `{name}` is not a constructor.")
2456 var args
= n_args
.to_a
2457 callsite
.check_signature
(v
, node
, args
)
2460 redef fun dump_info
(v
) do
2462 var callsite
= self.callsite
2463 if callsite
!= null then
2464 res
+= v
.yellow
(" call="+callsite
.dump_info
(v
))
2472 redef class AAttrFormExpr
2473 # The attribute accessed.
2474 var mproperty
: nullable MAttribute
2476 # The static type of the attribute.
2477 var attr_type
: nullable MType
2479 # Resolve the attribute accessed.
2480 private fun resolve_property
(v
: TypeVisitor)
2482 var recvtype
= v
.visit_expr
(self.n_expr
)
2483 if recvtype
== null then return # Skip error
2484 var node
= self.n_id
2485 var name
= node
.text
2486 if recvtype
isa MNullType then
2487 v
.error
(node
, "Error: attribute `{name}` access on `null`.")
2491 var unsafe_type
= v
.anchor_to
(recvtype
)
2492 var mproperty
= v
.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
2493 if mproperty
== null then
2494 v
.modelbuilder
.error
(node
, "Error: attribute `{name}` does not exist in `{recvtype}`.")
2497 assert mproperty
isa MAttribute
2498 self.mproperty
= mproperty
2500 var mpropdefs
= mproperty
.lookup_definitions
(v
.mmodule
, unsafe_type
)
2501 assert mpropdefs
.length
== 1
2502 var mpropdef
= mpropdefs
.first
2503 var attr_type
= mpropdef
.static_mtype
2504 if attr_type
== null then return # skip error
2505 attr_type
= v
.resolve_for
(attr_type
, recvtype
, self.n_expr
isa ASelfExpr)
2506 self.attr_type
= attr_type
2509 redef fun dump_info
(v
) do
2511 var mproperty
= self.mproperty
2512 var attr_type
= self.attr_type
2513 if mproperty
!= null then
2514 res
+= v
.yellow
(" attr={mproperty}:{attr_type or else "BROKEN"}")
2520 redef class AAttrExpr
2521 redef fun accept_typing
(v
)
2523 self.resolve_property
(v
)
2524 self.mtype
= self.attr_type
2528 redef class AAttrAssignExpr
2529 redef fun accept_typing
(v
)
2531 self.resolve_property
(v
)
2532 var mtype
= self.attr_type
2534 v
.visit_expr_subtype
(self.n_value
, mtype
)
2535 self.is_typed
= mtype
!= null
2539 redef class AAttrReassignExpr
2540 redef fun accept_typing
(v
)
2542 self.resolve_property
(v
)
2543 var mtype
= self.attr_type
2544 if mtype
== null then return # Skip error
2546 var rettype
= self.resolve_reassignment
(v
, mtype
, mtype
)
2548 self.is_typed
= rettype
!= null
2552 redef class AIssetAttrExpr
2553 redef fun accept_typing
(v
)
2555 self.resolve_property
(v
)
2556 var mtype
= self.attr_type
2557 if mtype
== null then return # Skip error
2559 var recvtype
= self.n_expr
.mtype
.as(not null)
2560 var bound
= v
.resolve_for
(mtype
, recvtype
, false)
2561 if bound
isa MNullableType then
2562 v
.error
(n_id
, "Type Error: `isset` on a nullable attribute.")
2564 self.mtype
= v
.type_bool
(self)
2568 redef class ASafeExpr
2569 redef fun accept_typing
(v
)
2571 var mtype
= v
.visit_expr
(n_expr
)
2572 if mtype
== null then return # Skip error
2574 if mtype
isa MNullType then
2575 # While `null?.foo` is semantically well defined and should not execute `foo` and just return `null`,
2576 # currently `null.foo` is forbidden so it seems coherent to also forbid `null?.foo`
2577 v
.modelbuilder
.error
(self, "Error: safe operator `?` on `null`.")
2581 self.mtype
= mtype
.as_notnull
2583 if not v
.can_be_null
(mtype
) then
2584 v
.modelbuilder
.warning
(self, "useless-safe", "Warning: useless safe operator `?` on non-nullable value.")
2590 redef class AVarargExpr
2591 redef fun accept_typing
(v
)
2593 # This kind of pseudo-expression can be only processed trough a signature
2594 # See `check_signature`
2595 # Other cases are a syntax error.
2596 v
.error
(self, "Syntax Error: unexpected `...`.")
2602 redef class ADebugTypeExpr
2603 redef fun accept_typing
(v
)
2605 var expr
= v
.visit_expr
(self.n_expr
)
2606 if expr
== null then return
2607 var unsafe
= v
.anchor_to
(expr
)
2608 var ntype
= self.n_type
2609 var mtype
= v
.resolve_mtype
(ntype
)
2610 if mtype
!= null and mtype
!= expr
then
2611 var umtype
= v
.anchor_to
(mtype
)
2612 v
.modelbuilder
.warning
(self, "debug", "Found type {expr} (-> {unsafe}), expected {mtype} (-> {umtype})")
2614 self.is_typed
= true