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
))
185 fun check_expr_cast
(node
: ANode, nexpr
: AExpr, ntype
: AType): nullable MType
187 var sub
= nexpr
.mtype
188 if sub
== null then return null # Forward error
190 var sup
= ntype
.mtype
191 if sup
== null then return null # Forward error
194 self.modelbuilder
.warning
(node
, "useless-type-test", "Warning: expression is already a `{sup}`.")
195 else if self.is_subtype
(sub
, sup
) then
196 self.modelbuilder
.warning
(node
, "useless-type-test", "Warning: expression is already a `{sup}` since it is a `{sub}`.")
201 # Can `mtype` be null (up to the current knowledge)?
202 fun can_be_null
(mtype
: MType): Bool
204 if mtype
isa MNullableType or mtype
isa MNullType then return true
205 if mtype
isa MFormalType then
206 var x
= anchor_to
(mtype
)
207 if x
isa MNullableType or x
isa MNullType then return true
212 # Check that `mtype` can be null (up to the current knowledge).
214 # If not then display a `useless-null-test` warning on node and return false.
216 fun check_can_be_null
(anode
: ANode, mtype
: MType): Bool
218 if mtype
isa MNullType then
219 modelbuilder
.warning
(anode
, "useless-null-test", "Warning: expression is always `null`.")
222 if can_be_null
(mtype
) then return true
224 if mtype
isa MFormalType then
225 var res
= anchor_to
(mtype
)
226 modelbuilder
.warning
(anode
, "useless-null-test", "Warning: expression is not null, since it is a `{mtype}: {res}`.")
228 modelbuilder
.warning
(anode
, "useless-null-test", "Warning: expression is not null, since it is a `{mtype}`.")
233 # Special verification on != and == for null
235 fun null_test
(anode
: ABinopExpr)
237 var mtype
= anode
.n_expr
.mtype
238 var mtype2
= anode
.n_expr2
.mtype
240 if mtype
== null or mtype2
== null then return
242 if not mtype2
isa MNullType then return
244 # Check of useless null
245 if not can_be_null
(mtype
) then return
247 if mtype
isa MNullType then
248 # Because of type adaptation, we cannot just stop here
249 # so return use `null` as a bottom type that will be merged easily (cf) `merge_types`
252 mtype
= mtype
.as_notnull
255 # Check for type adaptation
256 var variable
= anode
.n_expr
.its_variable
257 if variable
== null then return
259 # One is null (mtype2 see above) the other is not null
260 if anode
isa AEqExpr then
261 anode
.after_flow_context
.when_true
.set_var
(self, variable
, mtype2
)
262 anode
.after_flow_context
.when_false
.set_var
(self, variable
, mtype
)
263 else if anode
isa ANeExpr then
264 anode
.after_flow_context
.when_false
.set_var
(self, variable
, mtype2
)
265 anode
.after_flow_context
.when_true
.set_var
(self, variable
, mtype
)
271 fun try_get_mproperty_by_name2
(anode
: ANode, mtype
: MType, name
: String): nullable MProperty
273 return self.modelbuilder
.try_get_mproperty_by_name2
(anode
, mmodule
, mtype
, name
)
276 fun resolve_mtype
(node
: AType): nullable MType
278 return self.modelbuilder
.resolve_mtype
(mclassdef
, node
)
281 fun try_get_mclass
(node
: ANode, name
: String): nullable MClass
283 var mclass
= modelbuilder
.try_get_mclass_by_name
(node
, mmodule
, name
)
287 fun get_mclass
(node
: ANode, name
: String): nullable MClass
289 var mclass
= modelbuilder
.get_mclass_by_name
(node
, mmodule
, name
)
293 fun type_bool
(node
: ANode): nullable MType
295 var mclass
= self.get_mclass
(node
, "Bool")
296 if mclass
== null then return null
297 return mclass
.mclass_type
300 # Construction of a specific callsite according to the current context.
301 # Three entry points exist to create a callsite based on knowledge.
302 # The `build_callsite_by_name` is a top entry point, the method find the mpropdefs to call by the name of this.
303 # see `build_callsite_by_property` and `build_callsite_by_propdef` for more detail.
304 # If you already know the mpropdef to call use directly the `get_method_by_propdef` method
305 # If you just know the mproperty use the `build_callsite_by_property` method to display error if no `mpropdef` is found in the context
306 fun build_callsite_by_name
(node
: ANode, recvtype
: MType, name
: String, recv_is_self
: Bool): nullable CallSite
308 var unsafe_type
= self.anchor_to
(recvtype
)
310 #debug("recv: {recvtype} (aka {unsafe_type})")
311 if recvtype
isa MNullType then
312 var objclass
= get_mclass
(node
, "Object")
313 if objclass
== null then return null # Forward error
314 unsafe_type
= objclass
.mclass_type
317 var mproperty
= self.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
318 if name
== "new" and mproperty
== null then
320 mproperty
= self.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
323 if mproperty
== null then
325 self.modelbuilder
.error
(node
, "Error: method or variable `{name}` unknown in `{recvtype}`.")
326 else if recvtype
.need_anchor
then
327 self.modelbuilder
.error
(node
, "Error: method `{name}` does not exists in `{recvtype}: {unsafe_type}`.")
329 self.modelbuilder
.error
(node
, "Error: method `{name}` does not exists in `{recvtype}`.")
334 assert mproperty
isa MMethod
336 return build_callsite_by_property
(node
, recvtype
, mproperty
, recv_is_self
)
339 # The `build_callsite_by_property` finds the mpropdefs to call by the `MMethod`.
340 # If the mpropdef is found in the context it builds a new `Callsite`.
341 fun build_callsite_by_property
(node
: ANode, recvtype
: MType, mproperty
: MMethod, recv_is_self
: Bool): nullable CallSite
343 var unsafe_type
= self.anchor_to
(recvtype
)
345 if recvtype
isa MNullType then
346 var objclass
= get_mclass
(node
, "Object")
347 if objclass
== null then return null # Forward error
348 unsafe_type
= objclass
.mclass_type
350 # `null` only accepts some methods of object.
351 if recvtype
isa MNullType and not mproperty
.is_null_safe
then
352 self.error
(node
, "Error: method `{mproperty.name}` called on `null`.")
354 else if unsafe_type
isa MNullableType and not mproperty
.is_null_safe
then
355 modelbuilder
.advice
(node
, "call-on-nullable", "Warning: method call on a nullable receiver `{recvtype}`.")
358 if is_toplevel_context
and recv_is_self
and not mproperty
.is_toplevel
then
359 error
(node
, "Error: `{mproperty.name}` is not a top-level method, thus need a receiver.")
361 if not recv_is_self
and mproperty
.is_toplevel
then
362 error
(node
, "Error: cannot call `{mproperty.name}`, a top-level method, with a receiver.")
365 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
366 self.modelbuilder
.error
(node
, "Error: method `{mproperty.name}` is protected and can only accessed by `self`.")
370 var info
= mproperty
.deprecation
371 if info
!= null and self.mpropdef
.mproperty
.deprecation
== null then
374 self.modelbuilder
.warning
(node
, "deprecated-method", "Deprecation Warning: method `{mproperty.name}` is deprecated: {mdoc.content.first}")
376 self.modelbuilder
.warning
(node
, "deprecated-method", "Deprecation Warning: method `{mproperty.name}` is deprecated.")
380 var propdefs
= mproperty
.lookup_definitions
(self.mmodule
, unsafe_type
)
382 if propdefs
.length
== 0 then
383 self.modelbuilder
.error
(node
, "Type Error: no definition found for property `{mproperty.name}` in `{unsafe_type}`.")
386 else if propdefs
.length
== 1 then
387 mpropdef
= propdefs
.first
389 self.modelbuilder
.warning
(node
, "property-conflict", "Warning: conflicting property definitions for property `{mproperty.name}` in `{unsafe_type}`: {propdefs.join(" ")}")
390 mpropdef
= mproperty
.intro
393 return build_callsite_by_propdef
(node
, recvtype
, mpropdef
, recv_is_self
)
396 # The `build_callsite_by_propdef` builds the callsite directly with the `mprodef` passed in argument.
397 fun build_callsite_by_propdef
(node
: ANode, recvtype
: MType, mpropdef
: MMethodDef, recv_is_self
: Bool): nullable CallSite
399 var msignature
= mpropdef
.new_msignature
or else mpropdef
.msignature
400 if msignature
== null then return null # skip error
401 msignature
= resolve_for
(msignature
, recvtype
, recv_is_self
).as(MSignature)
403 var erasure_cast
= false
404 var rettype
= mpropdef
.msignature
.return_mtype
405 if not recv_is_self
and rettype
!= null then
406 rettype
= rettype
.undecorate
407 if rettype
isa MParameterType then
408 var erased_rettype
= msignature
.return_mtype
409 assert erased_rettype
!= null
410 #node.debug("Erasure cast: Really a {rettype} but unsafely a {erased_rettype}")
415 var callsite
= new CallSite(node
.hot_location
, recvtype
, mmodule
, anchor
, recv_is_self
, mpropdef
.mproperty
, mpropdef
, msignature
, erasure_cast
)
419 fun try_build_callsite_by_name
(node
: ANode, recvtype
: MType, name
: String, recv_is_self
: Bool): nullable CallSite
421 var unsafe_type
= self.anchor_to
(recvtype
)
422 var mproperty
= self.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
423 if mproperty
== null then return null
424 return build_callsite_by_name
(node
, recvtype
, name
, recv_is_self
)
428 # Visit the expressions of args and check their conformity with the corresponding type in signature
429 # The point of this method is to handle varargs correctly
430 # Note: The signature must be correctly adapted
431 fun check_signature
(node
: ANode, args
: Array[AExpr], mproperty
: MProperty, msignature
: MSignature): nullable SignatureMap
433 var vararg_rank
= msignature
.vararg_rank
434 if vararg_rank
>= 0 then
435 if args
.length
< msignature
.arity
then
436 modelbuilder
.error
(node
, "Error: expected at least {msignature.arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
439 else if args
.length
!= msignature
.arity
then
441 if args
.length
> msignature
.arity
then
442 modelbuilder
.error
(node
, "Error: expected {msignature.arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
445 # Other cases are managed later
449 #debug("CALL {unsafe_type}.{msignature}")
451 # Associate each parameter to a position in the arguments
452 var map
= new SignatureMap
454 # Special case for the isolated last argument
455 # TODO: reify this method characteristics (where? the param, the signature, the method?)
456 var last_is_padded
= mproperty
.name
.chars
.last
== '='
457 var nbargs
= args
.length
458 if last_is_padded
then
460 assert not args
.last
isa ANamedargExpr
461 map
.map
[msignature
.arity
- 1] = args
.length
- 1
462 self.visit_expr_subtype
(args
.last
, msignature
.mparameters
.last
.mtype
)
465 # First, handle named arguments
466 for i
in [0..args
.length
[ do
468 if not e
isa ANamedargExpr then continue
469 var name
= e
.n_id
.text
470 var param
= msignature
.mparameter_by_name
(name
)
471 if param
== null then
472 modelbuilder
.error
(e
.n_id
, "Error: no parameter `{name}` for `{mproperty}{msignature}`.")
475 var idx
= msignature
.mparameters
.index_of
(param
)
476 var prev
= map
.map
.get_or_null
(idx
)
478 modelbuilder
.error
(e
, "Error: parameter `{name}` already associated with argument #{prev} for `{mproperty}{msignature}`.")
482 e
.mtype
= self.visit_expr_subtype
(e
.n_expr
, param
.mtype
)
485 # Number of minimum mandatory remaining parameters
488 # Second, associate remaining parameters
489 var vararg_decl
= args
.length
- msignature
.arity
491 for i
in [0..msignature
.arity
[ do
492 # Skip parameters associated by name
493 if map
.map
.has_key
(i
) then continue
495 var param
= msignature
.mparameters
[i
]
497 # Search the next free argument: skip named arguments since they are already associated
498 while j
< nbargs
and args
[j
] isa ANamedargExpr do j
+= 1
500 if not param
.mtype
isa MNullableType then
510 if i
== vararg_rank
then
512 continue # skip the vararg
515 if not param
.is_vararg
then
516 var paramtype
= param
.mtype
517 self.visit_expr_subtype
(arg
, paramtype
)
519 check_one_vararg
(arg
, param
)
523 if min_arity
> 0 then
524 if last_is_padded
then min_arity
+= 1
525 if min_arity
< msignature
.arity
then
526 modelbuilder
.error
(node
, "Error: expected at least {min_arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
528 modelbuilder
.error
(node
, "Error: expected {min_arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
533 # Third, check varargs
534 if vararg_rank
>= 0 then
535 var paramtype
= msignature
.mparameters
[vararg_rank
].mtype
536 var first
= args
[vararg_rank
]
537 if vararg_decl
== 0 then
538 if not check_one_vararg
(first
, msignature
.mparameters
[vararg_rank
]) then return null
540 first
.vararg_decl
= vararg_decl
+ 1
541 for i
in [vararg_rank
..vararg_rank
+vararg_decl
] do
542 self.visit_expr_subtype
(args
[i
], paramtype
)
550 # Check an expression as a single vararg.
551 # The main point of the method if to handle the case of reversed vararg (see `AVarargExpr`)
552 fun check_one_vararg
(arg
: AExpr, param
: MParameter): Bool
554 var paramtype
= param
.mtype
555 var mclass
= get_mclass
(arg
, "Array")
556 if mclass
== null then return false # Forward error
557 var array_mtype
= mclass
.get_mtype
([paramtype
])
558 if arg
isa AVarargExpr then
559 self.visit_expr_subtype
(arg
.n_expr
, array_mtype
)
560 arg
.mtype
= arg
.n_expr
.mtype
562 # only one vararg, maybe `...` was forgot, so be gentle!
563 var t
= visit_expr
(arg
)
564 if t
== null then return false # Forward error
565 if not is_subtype
(t
, paramtype
) and is_subtype
(t
, array_mtype
) then
566 # Not acceptable but could be a `...`
567 error
(arg
, "Type Error: expected `{paramtype}`, got `{t}`. Is an ellipsis `...` missing on the argument?")
570 # Standard valid vararg, finish the job
572 self.visit_expr_subtype
(arg
, paramtype
)
577 fun error
(node
: ANode, message
: String)
579 self.modelbuilder
.error
(node
, message
)
582 fun get_variable
(node
: AExpr, variable
: Variable): nullable MType
584 if not variable
.is_adapted
then return variable
.declared_type
586 var flow
= node
.after_flow_context
587 if flow
== null then return null # skip error
589 if flow
.vars
.has_key
(variable
) then
590 return flow
.vars
[variable
]
592 #node.debug("*** START Collected for {variable}")
593 var mtypes
= flow
.collect_types
(variable
)
594 #node.debug("**** END Collected for {variable}")
595 if mtypes
.length
== 0 then
596 return variable
.declared_type
597 else if mtypes
.length
== 1 then
600 var res
= merge_types
(node
,mtypes
)
602 res
= variable
.declared_type
603 # Try to fallback to a non-null version
604 if res
!= null and can_be_null
(res
) then do
606 if t
!= null and can_be_null
(t
) then break label
616 # Some variables where type-adapted during the visit
619 # Some loops had been visited during the visit
622 fun set_variable
(node
: AExpr, variable
: Variable, mtype
: nullable MType)
624 var flow
= node
.after_flow_context
627 flow
.set_var
(self, variable
, mtype
)
630 # Find the exact representable most specific common super-type in `col`.
632 # Try to find the most specific common type that is a super-type of each types
634 # In most cases, the result is simply the most general type in `col`.
635 # If nullables types are involved, then the nullable information is correctly preserved.
636 # If incomparable super-types exists in `col`, them no solution is given and the `null`
637 # value is returned (since union types are non representable in Nit)
639 # The `null` values in `col` are ignored, nulltypes (MNullType) are considered.
641 # Returns the `null` value if:
644 # * `col` only have null values
645 # * there is a conflict
647 # Example (with a diamond A,B,C,D):
649 # * merge(A,B,C) -> A, because A is the most general type in {A,B,C}
650 # * merge(C,B) -> null, there is conflict, because `B or C` cannot be represented
651 # * merge(A,nullable B) -> nullable A, because A is the most general type and
652 # the nullable information is preserved
653 fun merge_types
(node
: ANode, col
: Array[nullable MType]): nullable MType
655 if col
.length
== 1 then return col
.first
657 if t1
== null then continue # return null
660 if t2
== null then continue # return null
661 if can_be_null
(t2
) and not can_be_null
(t1
) then
664 if not is_subtype
(t2
, t1
) then found
= false
667 #print "merge {col.join(" ")} -> {t1}"
671 #self.modelbuilder.warning(node, "Type Error: {col.length} conflicting types: <{col.join(", ")}>")
675 # Find a most general common subtype between `type1` and `type2`.
677 # Find the most general type that is a subtype of `type2` and, if possible, a subtype of `type1`.
678 # Basically, this return the most specific type between `type1` and `type2`.
679 # If nullable types are involved, the information is correctly preserved.
680 # If `type1` and `type2` are incomparable then `type2` is preferred (since intersection types
681 # are not representable in Nit).
683 # The `null` value is returned if both `type1` and `type2` are null.
685 # Examples (with diamond A,B,C,D):
687 # * intersect_types(A,B) -> B, because B is a subtype of A
688 # * intersect_types(B,A) -> B, because B is a subtype of A
689 # * intersect_types(B,C) -> C, B and C are incomparable,
690 # `type2` is then preferred (`B and C` cannot be represented)
691 # * intersect_types(nullable B,A) -> B, because B<:A and the non-null information is preserved
692 # * intersect_types(B,nullable C) -> C, `type2` is preferred and the non-null information is preserved
693 fun intersect_types
(node
: ANode, type1
, type2
: nullable MType): nullable MType
695 if type1
== null then return type2
696 if type2
== null then return type1
698 if not can_be_null
(type2
) or not can_be_null
(type1
) then
699 type1
= type1
.as_notnull
700 type2
= type2
.as_notnull
704 if is_subtype
(type1
, type2
) then
712 # Find a most general type that is a subtype of `type1` but not one of `type2`.
714 # Basically, this returns `type1`-`type2` but since there is no substraction type
715 # in Nit this just returns `type1` most of the case.
717 # The few other cases are if `type2` is a super-type and if some nullable information
720 # The `null` value is returned if `type1` is null.
722 # Examples (with diamond A,B,C,D):
724 # * diff_types(A,B) -> A, because the notB cannot be represented
725 # * diff_types(B,A) -> None (absurd type), because B<:A
726 # * diff_types(nullable A, nullable B) -> A, because null is removed
727 # * diff_types(nullable B, A) -> Null, because anything but null is removed
728 fun diff_types
(node
: ANode, type1
, type2
: nullable MType): nullable MType
730 if type1
== null then return null
731 if type2
== null then return type1
733 # if t1 <: t2 then t1-t2 = bottom
734 if is_subtype
(type1
, type2
) then
735 return modelbuilder
.model
.null_type
.as_notnull
738 # else if t1 <: nullable t2 then t1-t2 = nulltype
739 if is_subtype
(type1
, type2
.as_nullable
) then
740 return modelbuilder
.model
.null_type
743 # else t2 can be null and type2 must accept null then null is excluded in t1
744 if can_be_null
(type1
) and (type2
isa MNullableType or type2
isa MNullType) then
745 return type1
.as_notnull
752 # Mapping between parameters and arguments in a call.
754 # Parameters and arguments are not stored in the class but referenced by their position (starting from 0)
756 # The point of this class is to help engine and other things to map arguments in the AST to parameters of the model.
758 # Associate a parameter to an argument
759 var map
= new ArrayMap[Int, Int]
762 # A specific method call site with its associated informations.
768 # The static type of the receiver (possibly unresolved)
771 # The module where the callsite is present
774 # The anchor to use with `recv` or `msignature`
775 var anchor
: nullable MClassType
777 # Is the receiver self?
778 # If "for_self", virtual types of the signature are kept
779 # If "not_for_self", virtual type are erased
780 var recv_is_self
: Bool
782 # The designated method
783 var mproperty
: MMethod
785 # The statically designated method definition
786 # The most specif one, it is.
787 var mpropdef
: MMethodDef
789 # The resolved signature for the receiver
790 var msignature
: MSignature
792 # Is a implicit cast required on erasure typing policy?
793 var erasure_cast
: Bool
795 # The mapping used on the call to associate arguments to parameters
796 # If null then no specific association is required.
797 var signaturemap
: nullable SignatureMap = null
799 private fun check_signature
(v
: TypeVisitor, node
: ANode, args
: Array[AExpr]): Bool
801 var map
= v
.check_signature
(node
, args
, self.mproperty
, self.msignature
)
803 if map
== null then is_broken
= true
807 # Information about the callsite to display on a node
808 fun dump_info
(v
: ASTDump): String do
809 return "{recv}.{mpropdef}{msignature}"
812 redef fun mdoc_or_fallback
do return mproperty
.intro
.mdoc
816 # The declared type of the variable
817 var declared_type
: nullable MType = null is writable
819 # Was the variable type-adapted?
820 # This is used to speedup type retrieval while it remains `false`
821 private var is_adapted
= false
824 redef class FlowContext
825 # Store changes of types because of type evolution
826 private var vars
= new HashMap[Variable, nullable MType]
828 # Adapt the variable to a static type
829 # Warning1: do not modify vars directly.
830 # Warning2: sub-flow may have cached a unadapted variable
831 private fun set_var
(v
: TypeVisitor, variable
: Variable, mtype
: nullable MType)
833 if variable
.declared_type
== mtype
and not variable
.is_adapted
then return
834 if vars
.has_key
(variable
) and vars
[variable
] == mtype
then return
835 self.vars
[variable
] = mtype
837 variable
.is_adapted
= true
838 #node.debug "set {variable} to {mtype or else "X"}"
841 # Look in the flow and previous flow and collect all first reachable type adaptation of a local variable
842 private fun collect_types
(variable
: Variable): Array[nullable MType]
844 #node.debug "flow for {variable}"
845 var res
= new Array[nullable MType]
848 var seen
= new HashSet[FlowContext]
849 while not todo
.is_empty
do
851 if f
.is_unreachable
then continue
852 if seen
.has
(f
) then continue
855 if f
.vars
.has_key
(variable
) then
856 # Found something. Collect it and do not process further on this path
857 res
.add f
.vars
[variable
]
858 #f.node.debug "process {variable}: got {f.vars[variable] or else "X"}"
860 todo
.add_all f
.previous
862 if f
.previous
.is_empty
then
863 # Root flowcontext mean a parameter or something related
864 res
.add variable
.declared_type
865 #f.node.debug "root process {variable}: got {variable.declared_type or else "X"}"
869 #self.node.debug "##### end flow for {variable}: {res.join(" ")}"
875 # The entry point of the whole typing analysis
876 fun do_typing
(modelbuilder
: ModelBuilder)
880 # The variable associated to the receiver (if any)
881 var selfvariable
: nullable Variable
884 redef class AMethPropdef
885 redef fun do_typing
(modelbuilder
: ModelBuilder)
887 var mpropdef
= self.mpropdef
888 if mpropdef
== null then return # skip error
890 var v
= new TypeVisitor(modelbuilder
, mpropdef
)
891 self.selfvariable
= v
.selfvariable
893 var mmethoddef
= self.mpropdef
.as(not null)
894 var msignature
= mmethoddef
.msignature
895 if msignature
== null then return # skip error
896 for i
in [0..msignature
.arity
[ do
897 var mtype
= msignature
.mparameters
[i
].mtype
898 if msignature
.vararg_rank
== i
then
899 var arrayclass
= v
.get_mclass
(self.n_signature
.n_params
[i
], "Array")
900 if arrayclass
== null then return # Skip error
901 mtype
= arrayclass
.get_mtype
([mtype
])
903 var variable
= self.n_signature
.n_params
[i
].variable
904 assert variable
!= null
905 variable
.declared_type
= mtype
908 var nblock
= self.n_block
909 if nblock
== null then return
914 if not v
.has_loop
or not v
.dirty
then break
917 var post_visitor
= new PostTypingVisitor(v
)
918 post_visitor
.enter_visit
(self)
920 if not nblock
.after_flow_context
.is_unreachable
and msignature
.return_mtype
!= null then
921 # We reach the end of the function without having a return, it is bad
922 v
.error
(self, "Error: reached end of function; expected `return` with a value.")
927 private class PostTypingVisitor
929 var type_visitor
: TypeVisitor
930 redef fun visit
(n
) do
932 n
.accept_post_typing
(type_visitor
)
933 if n
isa AExpr and n
.mtype
== null and not n
.is_typed
then
940 private fun accept_post_typing
(v
: TypeVisitor) do end
942 # An additional information message to explain the role of a child expression.
944 # The point of the method is to allow some kind of double dispatch so the parent
945 # choose how to describe its children.
946 private fun bad_expr_message
(child
: AExpr): nullable String do return null
949 redef class AAttrPropdef
950 redef fun do_typing
(modelbuilder
: ModelBuilder)
952 if not has_value
then return
954 var mpropdef
= self.mreadpropdef
955 if mpropdef
== null or mpropdef
.msignature
== null then return # skip error
957 var v
= new TypeVisitor(modelbuilder
, mpropdef
)
958 self.selfvariable
= v
.selfvariable
960 var nexpr
= self.n_expr
961 if nexpr
!= null then
962 var mtype
= self.mtype
963 v
.visit_expr_subtype
(nexpr
, mtype
)
965 var nblock
= self.n_block
966 if nblock
!= null then
968 if not nblock
.after_flow_context
.is_unreachable
then
969 # We reach the end of the init without having a return, it is bad
970 v
.error
(self, "Error: reached end of block; expected `return`.")
979 # The static type of the expression.
980 # null if self is a statement or in case of error
981 var mtype
: nullable MType = null
983 # Is the statement correctly typed?
984 # Used to distinguish errors and statements when `mtype == null`
985 var is_typed
: Bool = false
987 # If required, the following implicit cast `.as(XXX)`
988 # Such a cast may by required after evaluating the expression when
989 # a unsafe operation is detected (silently accepted by the Nit language).
990 # The attribute is computed by `check_subtype`
991 var implicit_cast_to
: nullable MType = null
993 # Return the variable read (if any)
994 # Used to perform adaptive typing
995 fun its_variable
: nullable Variable do return null
997 private fun accept_typing
(v
: TypeVisitor)
999 v
.error
(self, "no implemented accept_typing for {self.class_name}")
1002 # Is non-null if `self` is a leaf of a comprehension array construction.
1003 # In this case, the enclosing literal array node is designated.
1004 # The result of the evaluation of `self` must be
1005 # stored inside the designated array (there is an implicit `push`)
1006 var comprehension
: nullable AArrayExpr = null
1008 # It indicates the number of arguments collected as a vararg.
1010 # When 0, the argument is used as is, without transformation.
1011 # When 1, the argument is transformed into an singleton array.
1012 # Above 1, the arguments and the next ones are transformed into a common array.
1014 # This attribute is meaning less on expressions not used as attributes.
1015 var vararg_decl
: Int = 0
1017 redef fun dump_info
(v
) do
1019 var mtype
= self.mtype
1020 if mtype
!= null then
1021 res
+= v
.yellow
(":{mtype}")
1023 var ict
= self.implicit_cast_to
1025 res
+= v
.yellow
("(.as({ict}))")
1031 redef class ABlockExpr
1032 redef fun accept_typing
(v
)
1034 for e
in self.n_expr
do v
.visit_stmt
(e
)
1035 self.is_typed
= true
1038 # The type of a blockexpr is the one of the last expression (or null if empty)
1041 if self.n_expr
.is_empty
then return null
1042 return self.n_expr
.last
.mtype
1046 redef class AVardeclExpr
1047 redef fun accept_typing
(v
)
1049 var variable
= self.variable
1050 if variable
== null then return # Skip error
1052 var ntype
= self.n_type
1053 var mtype
: nullable MType
1054 if ntype
== null then
1057 mtype
= v
.resolve_mtype
(ntype
)
1058 if mtype
== null then return # Skip error
1061 var nexpr
= self.n_expr
1062 if nexpr
!= null then
1063 if mtype
!= null then
1064 var etype
= v
.visit_expr_subtype
(nexpr
, mtype
)
1065 if etype
== mtype
then
1066 assert ntype
!= null
1067 v
.modelbuilder
.advice
(ntype
, "useless-type", "Warning: useless type definition for variable `{variable.name}`")
1070 mtype
= v
.visit_expr
(nexpr
)
1071 if mtype
== null then return # Skip error
1075 var decltype
= mtype
1076 if mtype
== null or mtype
isa MNullType then
1077 var objclass
= v
.get_mclass
(self, "Object")
1078 if objclass
== null then return # skip error
1079 decltype
= objclass
.mclass_type
.as_nullable
1080 if mtype
== null then mtype
= decltype
1083 variable
.declared_type
= decltype
1084 v
.set_variable
(self, variable
, mtype
)
1086 #debug("var {variable}: {mtype}")
1089 self.is_typed
= true
1093 redef class AVarExpr
1094 redef fun its_variable
do return self.variable
1095 redef fun accept_typing
(v
)
1097 var variable
= self.variable
1098 if variable
== null then return # Skip error
1100 var mtype
= v
.get_variable
(self, variable
)
1101 if mtype
!= null then
1102 #debug("{variable} is {mtype}")
1104 #debug("{variable} is untyped")
1111 redef class AVarAssignExpr
1112 redef fun accept_typing
(v
)
1114 var variable
= self.variable
1115 assert variable
!= null
1117 var mtype
= v
.visit_expr_subtype
(n_value
, variable
.declared_type
)
1119 v
.set_variable
(self, variable
, mtype
)
1121 self.is_typed
= true
1125 redef class AReassignFormExpr
1126 # The method designed by the reassign operator.
1127 var reassign_callsite
: nullable CallSite
1129 var read_type
: nullable MType = null
1131 # Determine the `reassign_property`
1132 # `readtype` is the type of the reading of the left value.
1133 # `writetype` is the type of the writing of the left value.
1134 # (Because of `ACallReassignExpr`, both can be different.
1135 # Return the static type of the value to store.
1136 private fun resolve_reassignment
(v
: TypeVisitor, readtype
, writetype
: MType): nullable MType
1138 var reassign_name
= self.n_assign_op
.operator
1140 self.read_type
= readtype
1142 var callsite
= v
.build_callsite_by_name
(self.n_assign_op
, readtype
, reassign_name
, false)
1143 if callsite
== null then return null # Skip error
1144 self.reassign_callsite
= callsite
1146 var msignature
= callsite
.msignature
1147 var rettype
= msignature
.return_mtype
1148 assert msignature
.arity
== 1 and rettype
!= null
1150 var value_type
= v
.visit_expr_subtype
(self.n_value
, msignature
.mparameters
.first
.mtype
)
1151 if value_type
== null then return null # Skip error
1153 v
.check_subtype
(self, rettype
, writetype
, false)
1158 redef class AVarReassignExpr
1159 redef fun accept_typing
(v
)
1161 var variable
= self.variable
1162 assert variable
!= null
1164 var readtype
= v
.get_variable
(self, variable
)
1165 if readtype
== null then return
1167 read_type
= readtype
1169 var writetype
= variable
.declared_type
1170 if writetype
== null then return
1172 var rettype
= self.resolve_reassignment
(v
, readtype
, writetype
)
1174 v
.set_variable
(self, variable
, rettype
)
1176 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)
1507 redef class ANotExpr
1508 redef fun accept_typing
(v
)
1510 v
.visit_expr_bool
(n_expr
)
1511 self.mtype
= v
.type_bool
(self)
1515 redef class AOrElseExpr
1516 redef fun accept_typing
(v
)
1518 var t1
= v
.visit_expr
(n_expr
)
1519 var t2
= v
.visit_expr
(n_expr2
)
1521 if t1
== null or t2
== null then
1525 if t1
isa MNullType then
1528 else if v
.can_be_null
(t1
) then
1532 var t
= v
.merge_types
(self, [t1
, t2
])
1534 var c
= v
.get_mclass
(self, "Object")
1535 if c
== null then return # forward error
1537 if v
.can_be_null
(t2
) then
1540 #v.error(self, "Type Error: ambiguous type {t1} vs {t2}")
1545 redef fun accept_post_typing
(v
)
1547 var t1
= n_expr
.mtype
1551 v
.check_can_be_null
(n_expr
, t1
)
1556 redef class ATrueExpr
1557 redef fun accept_typing
(v
)
1559 self.mtype
= v
.type_bool
(self)
1563 redef class AFalseExpr
1564 redef fun accept_typing
(v
)
1566 self.mtype
= v
.type_bool
(self)
1570 redef class AIntegerExpr
1571 redef fun accept_typing
(v
)
1573 var mclass
: nullable MClass = null
1574 if value
isa Byte then
1575 mclass
= v
.get_mclass
(self, "Byte")
1576 else if value
isa Int then
1577 mclass
= v
.get_mclass
(self, "Int")
1578 else if value
isa Int8 then
1579 mclass
= v
.get_mclass
(self, "Int8")
1580 else if value
isa Int16 then
1581 mclass
= v
.get_mclass
(self, "Int16")
1582 else if value
isa UInt16 then
1583 mclass
= v
.get_mclass
(self, "UInt16")
1584 else if value
isa Int32 then
1585 mclass
= v
.get_mclass
(self, "Int32")
1586 else if value
isa UInt32 then
1587 mclass
= v
.get_mclass
(self, "UInt32")
1589 if mclass
== null then return # Forward error
1590 self.mtype
= mclass
.mclass_type
1594 redef class AFloatExpr
1595 redef fun accept_typing
(v
)
1597 var mclass
= v
.get_mclass
(self, "Float")
1598 if mclass
== null then return # Forward error
1599 self.mtype
= mclass
.mclass_type
1603 redef class ACharExpr
1604 redef fun accept_typing
(v
) do
1605 var mclass
: nullable MClass = null
1606 if is_code_point
then
1607 mclass
= v
.get_mclass
(self, "Int")
1609 mclass
= v
.get_mclass
(self, "Char")
1611 if mclass
== null then return # Forward error
1612 self.mtype
= mclass
.mclass_type
1616 redef class AugmentedStringFormExpr
1619 # Text::to_re, used for prefix `re`
1620 var to_re
: nullable CallSite = null
1621 # Regex::ignore_case, used for suffix `i` on `re`
1622 var ignore_case
: nullable CallSite = null
1623 # Regex::newline, used for suffix `m` on `re`
1624 var newline
: nullable CallSite = null
1625 # Regex::extended, used for suffix `b` on `re`
1626 var extended
: nullable CallSite = null
1627 # CString::to_bytes_with_copy, used for prefix `b`
1628 var to_bytes_with_copy
: nullable CallSite = null
1630 redef fun accept_typing
(v
) do
1631 var mclass
= v
.get_mclass
(self, "String")
1632 if mclass
== null then return # Forward error
1633 if is_bytestring
then
1634 to_bytes_with_copy
= v
.build_callsite_by_name
(self, v
.mmodule
.c_string_type
, "to_bytes_with_copy", false)
1635 mclass
= v
.get_mclass
(self, "Bytes")
1637 to_re
= v
.build_callsite_by_name
(self, mclass
.mclass_type
, "to_re", false)
1638 for i
in suffix
.chars
do
1639 mclass
= v
.get_mclass
(self, "Regex")
1640 if mclass
== null then
1641 v
.error
(self, "Error: `Regex` class unknown")
1646 service
= "ignore_case="
1647 ignore_case
= v
.build_callsite_by_name
(self, mclass
.mclass_type
, service
, false)
1648 else if i
== 'm' then
1649 service
= "newline="
1650 newline
= v
.build_callsite_by_name
(self, mclass
.mclass_type
, service
, false)
1651 else if i
== 'b' then
1652 service
= "extended="
1653 extended
= v
.build_callsite_by_name
(self, mclass
.mclass_type
, service
, false)
1655 v
.error
(self, "Type Error: Unrecognized suffix {i} in prefixed Regex")
1660 if mclass
== null then return # Forward error
1661 mtype
= mclass
.mclass_type
1665 redef class ASuperstringExpr
1666 redef fun accept_typing
(v
)
1669 var objclass
= v
.get_mclass
(self, "Object")
1670 if objclass
== null then return # Forward error
1671 var objtype
= objclass
.mclass_type
1672 for nexpr
in self.n_exprs
do
1673 v
.visit_expr_subtype
(nexpr
, objtype
)
1678 redef class AArrayExpr
1679 # The `with_capacity` method on Array
1680 var with_capacity_callsite
: nullable CallSite
1682 # The `push` method on arrays
1683 var push_callsite
: nullable CallSite
1685 # The element of each type
1686 var element_mtype
: nullable MType
1688 # Set that `self` is a part of comprehension array `na`
1689 # If `self` is a `for`, or a `if`, then `set_comprehension` is recursively applied.
1690 private fun set_comprehension
(n
: nullable AExpr)
1694 else if n
isa AForExpr then
1695 set_comprehension
(n
.n_block
)
1696 else if n
isa AIfExpr then
1697 set_comprehension
(n
.n_then
)
1698 set_comprehension
(n
.n_else
)
1701 n
.comprehension
= self
1704 redef fun accept_typing
(v
)
1706 var mtype
: nullable MType = null
1707 var ntype
= self.n_type
1708 if ntype
!= null then
1709 mtype
= v
.resolve_mtype
(ntype
)
1710 if mtype
== null then return # Skip error
1712 var mtypes
= new Array[nullable MType]
1714 for e
in self.n_exprs
do
1715 var t
= v
.visit_expr
(e
)
1719 set_comprehension
(e
)
1720 if mtype
!= null then
1721 if v
.check_subtype
(e
, t
, mtype
, false) == null then return # Forward error
1722 if t
== mtype
then useless
= true
1727 if mtype
== null then
1728 # Ensure monotony for type adaptation on loops
1729 if self.element_mtype
!= null then mtypes
.add
self.element_mtype
1730 mtype
= v
.merge_types
(self, mtypes
)
1732 if mtype
== null or mtype
isa MNullType then
1733 v
.error
(self, "Type Error: ambiguous array type {mtypes.join(" ")}")
1737 assert ntype
!= null
1738 v
.modelbuilder
.warning
(ntype
, "useless-type", "Warning: useless type declaration `{mtype}` in literal Array since it can be inferred from the elements type.")
1741 self.element_mtype
= mtype
1743 var mclass
= v
.get_mclass
(self, "Array")
1744 if mclass
== null then return # Forward error
1745 var array_mtype
= mclass
.get_mtype
([mtype
])
1747 with_capacity_callsite
= v
.build_callsite_by_name
(self, array_mtype
, "with_capacity", false)
1748 push_callsite
= v
.build_callsite_by_name
(self, array_mtype
, "push", false)
1750 self.mtype
= array_mtype
1754 redef class ARangeExpr
1755 var init_callsite
: nullable CallSite
1757 redef fun accept_typing
(v
)
1759 var discrete_class
= v
.get_mclass
(self, "Discrete")
1760 if discrete_class
== null then return # Forward error
1761 var discrete_type
= discrete_class
.intro
.bound_mtype
1762 var t1
= v
.visit_expr_subtype
(self.n_expr
, discrete_type
)
1763 var t2
= v
.visit_expr_subtype
(self.n_expr2
, discrete_type
)
1764 if t1
== null or t2
== null then return
1765 var mclass
= v
.get_mclass
(self, "Range")
1766 if mclass
== null then return # Forward error
1768 if v
.is_subtype
(t1
, t2
) then
1769 mtype
= mclass
.get_mtype
([t2
])
1770 else if v
.is_subtype
(t2
, t1
) then
1771 mtype
= mclass
.get_mtype
([t1
])
1773 v
.error
(self, "Type Error: cannot create range: `{t1}` vs `{t2}`.")
1779 # get the constructor
1781 if self isa ACrangeExpr then
1782 callsite
= v
.build_callsite_by_name
(self, mtype
, "init", false)
1783 else if self isa AOrangeExpr then
1784 callsite
= v
.build_callsite_by_name
(self, mtype
, "without_last", false)
1788 init_callsite
= callsite
1792 redef class ANullExpr
1793 redef fun accept_typing
(v
)
1795 self.mtype
= v
.mmodule
.model
.null_type
1799 redef class AIsaExpr
1800 # The static type to cast to.
1801 # (different from the static type of the expression that is `Bool`).
1802 var cast_type
: nullable MType
1803 redef fun accept_typing
(v
)
1805 v
.visit_expr
(n_expr
)
1807 var mtype
= v
.resolve_mtype
(n_type
)
1809 self.cast_type
= mtype
1811 var variable
= self.n_expr
.its_variable
1812 if variable
!= null then
1813 var orig
= self.n_expr
.mtype
1814 #var from = if orig != null then orig.to_s else "invalid"
1815 #var to = if mtype != null then mtype.to_s else "invalid"
1816 #debug("adapt {variable}: {from} -> {to}")
1818 var thentype
= v
.intersect_types
(self, orig
, mtype
)
1819 if thentype
!= orig
then
1820 self.after_flow_context
.when_true
.set_var
(v
, variable
, thentype
)
1821 #debug "{variable}:{orig or else "?"} isa {mtype or else "?"} -> then {thentype or else "?"}"
1824 var elsetype
= v
.diff_types
(self, orig
, mtype
)
1825 if elsetype
!= orig
then
1826 self.after_flow_context
.when_false
.set_var
(v
, variable
, elsetype
)
1827 #debug "{variable}:{orig or else "?"} isa {mtype or else "?"} -> else {elsetype or else "?"}"
1831 self.mtype
= v
.type_bool
(self)
1834 redef fun accept_post_typing
(v
)
1836 v
.check_expr_cast
(self, self.n_expr
, self.n_type
)
1839 redef fun dump_info
(v
) do
1841 var mtype
= self.cast_type
1842 if mtype
!= null then
1843 res
+= v
.yellow
(".as({mtype})")
1850 redef class AAsCastExpr
1851 redef fun accept_typing
(v
)
1853 v
.visit_expr
(n_expr
)
1855 self.mtype
= v
.resolve_mtype
(n_type
)
1858 redef fun accept_post_typing
(v
)
1860 v
.check_expr_cast
(self, self.n_expr
, self.n_type
)
1864 redef class AAsNotnullExpr
1865 redef fun accept_typing
(v
)
1867 var mtype
= v
.visit_expr
(self.n_expr
)
1868 if mtype
== null then return # Forward error
1870 if mtype
isa MNullType then
1871 v
.error
(self, "Type Error: `as(not null)` on `null`.")
1875 if v
.can_be_null
(mtype
) then
1876 mtype
= mtype
.as_notnull
1882 redef fun accept_post_typing
(v
)
1884 var mtype
= n_expr
.mtype
1885 if mtype
== null then return
1886 v
.check_can_be_null
(n_expr
, mtype
)
1890 redef class AParExpr
1891 redef fun accept_typing
(v
)
1893 self.mtype
= v
.visit_expr
(self.n_expr
)
1897 redef class AOnceExpr
1898 redef fun accept_typing
(v
)
1900 self.mtype
= v
.visit_expr
(self.n_expr
)
1904 redef class ASelfExpr
1905 redef var its_variable
: nullable Variable
1906 redef fun accept_typing
(v
)
1908 if v
.is_toplevel_context
and not self isa AImplicitSelfExpr then
1909 v
.error
(self, "Error: `self` cannot be used in top-level method.")
1911 var variable
= v
.selfvariable
1912 self.its_variable
= variable
1913 self.mtype
= v
.get_variable
(self, variable
)
1917 redef class AImplicitSelfExpr
1918 # Is the implicit receiver `sys`?
1920 # By default, the implicit receiver is `self`.
1921 # But when there is not method for `self`, `sys` is used as a fall-back.
1922 # Is this case this flag is set to `true`.
1926 ## MESSAGE SENDING AND PROPERTY
1928 redef class ASendExpr
1929 # The property invoked by the send.
1930 var callsite
: nullable CallSite
1932 # Is self a safe call (with `x?.foo`)?
1933 # If so and the receiver is null, then the arguments won't be evaluated
1934 # and the call skipped (replaced with null).
1935 var is_safe
: Bool = false
1937 redef fun bad_expr_message
(child
)
1939 if child
== self.n_expr
then
1940 return "to be the receiver of `{self.property_name}`"
1945 redef fun accept_typing
(v
)
1947 var nrecv
= self.n_expr
1948 var recvtype
= v
.visit_expr
(nrecv
)
1950 if nrecv
isa ASafeExpr then
1951 # Has the receiver the form `x?.foo`?
1952 # For parsing "reasons" the `?` is in the receiver node, not the call node.
1956 var name
= self.property_name
1957 var node
= self.property_node
1959 if recvtype
== null then return # Forward error
1962 var unsafe_type
= v
.anchor_to
(recvtype
)
1963 var mproperty
= v
.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
1964 if mproperty
== null and nrecv
isa AImplicitSelfExpr then
1965 # Special fall-back search in `sys` when noting found in the implicit receiver.
1966 var sysclass
= v
.try_get_mclass
(node
, "Sys")
1967 if sysclass
!= null then
1968 var systype
= sysclass
.mclass_type
1969 mproperty
= v
.try_get_mproperty_by_name2
(node
, systype
, name
)
1970 if mproperty
!= null then
1971 callsite
= v
.build_callsite_by_name
(node
, systype
, name
, false)
1972 if callsite
== null then return # Forward error
1973 # Update information, we are looking at `sys` now, not `self`
1975 nrecv
.its_variable
= null
1976 nrecv
.mtype
= systype
1981 if callsite
== null then
1982 # If still nothing, just exit
1983 callsite
= v
.build_callsite_by_name
(node
, recvtype
, name
, nrecv
isa ASelfExpr)
1984 if callsite
== null then return
1987 self.callsite
= callsite
1988 var msignature
= callsite
.msignature
1990 var args
= compute_raw_arguments
1992 if not self isa ACallrefExpr then
1993 callsite
.check_signature
(v
, node
, args
)
1996 if callsite
.mproperty
.is_init
then
1997 var vmpropdef
= v
.mpropdef
1998 if not (vmpropdef
isa MMethodDef and vmpropdef
.mproperty
.is_init
) then
1999 v
.error
(node
, "Error: an `init` can only be called from another `init`.")
2001 if vmpropdef
isa MMethodDef and vmpropdef
.mproperty
.is_root_init
and not callsite
.mproperty
.is_root_init
then
2002 v
.error
(node
, "Error: `{vmpropdef}` cannot call a factory `{callsite.mproperty}`.")
2006 var ret
= msignature
.return_mtype
2009 # A safe receiver makes that the call is not executed and returns null
2010 ret
= ret
.as_nullable
2014 self.is_typed
= true
2018 # The name of the property
2019 # Each subclass simply provide the correct name.
2020 private fun property_name
: String is abstract
2022 # The node identifying the name (id, operator, etc) for messages.
2024 # Is `self` by default
2025 private fun property_node
: ANode do return self
2027 # An array of all arguments (excluding self)
2028 fun raw_arguments
: Array[AExpr] do return compute_raw_arguments
2030 private fun compute_raw_arguments
: Array[AExpr] is abstract
2032 redef fun dump_info
(v
) do
2034 var callsite
= self.callsite
2035 if callsite
!= null then
2036 res
+= v
.yellow
(" call="+callsite
.dump_info
(v
))
2042 redef class ABinopExpr
2043 redef fun compute_raw_arguments
do return [n_expr2
]
2044 redef fun property_name
do return operator
2045 redef fun property_node
do return n_op
2048 redef class AEqFormExpr
2049 redef fun accept_typing
(v
)
2055 redef fun accept_post_typing
(v
)
2057 var mtype
= n_expr
.mtype
2058 var mtype2
= n_expr2
.mtype
2060 if mtype
== null or mtype2
== null then return
2062 if mtype
== v
.type_bool
(self) and (n_expr2
isa AFalseExpr or n_expr2
isa ATrueExpr) then
2063 v
.modelbuilder
.warning
(self, "useless-truism", "Warning: useless comparison to a Bool literal.")
2066 if not mtype2
isa MNullType then return
2068 v
.check_can_be_null
(n_expr
, mtype
)
2072 redef class AUnaryopExpr
2073 redef fun property_name
do return "unary {operator}"
2074 redef fun compute_raw_arguments
do return new Array[AExpr]
2078 redef class ACallExpr
2079 redef fun property_name
do return n_qid
.n_id
.text
2080 redef fun property_node
do return n_qid
2081 redef fun compute_raw_arguments
do return n_args
.to_a
2084 redef class ACallAssignExpr
2085 redef fun property_name
do return n_qid
.n_id
.text
+ "="
2086 redef fun property_node
do return n_qid
2087 redef fun compute_raw_arguments
2089 var res
= n_args
.to_a
2095 redef class ABraExpr
2096 redef fun property_name
do return "[]"
2097 redef fun compute_raw_arguments
do return n_args
.to_a
2100 redef class ABraAssignExpr
2101 redef fun property_name
do return "[]="
2102 redef fun compute_raw_arguments
2104 var res
= n_args
.to_a
2110 redef class ASendReassignFormExpr
2111 # The property invoked for the writing
2112 var write_callsite
: nullable CallSite
2114 redef fun accept_typing
(v
)
2116 var recvtype
= v
.visit_expr
(self.n_expr
)
2117 var name
= self.property_name
2118 var node
= self.property_node
2120 if recvtype
== null then return # Forward error
2122 var for_self
= self.n_expr
isa ASelfExpr
2123 var callsite
= v
.build_callsite_by_name
(node
, recvtype
, name
, for_self
)
2125 if callsite
== null then return
2126 self.callsite
= callsite
2128 var args
= compute_raw_arguments
2130 callsite
.check_signature
(v
, node
, args
)
2132 var readtype
= callsite
.msignature
.return_mtype
2133 if readtype
== null then
2134 v
.error
(node
, "Error: `{name}` is not a function.")
2138 var wcallsite
= v
.build_callsite_by_name
(node
, recvtype
, name
+ "=", self.n_expr
isa ASelfExpr)
2139 if wcallsite
== null then return
2140 self.write_callsite
= wcallsite
2142 var wtype
= self.resolve_reassignment
(v
, readtype
, wcallsite
.msignature
.mparameters
.last
.mtype
)
2143 if wtype
== null then return
2145 args
= args
.to_a
# duplicate so raw_arguments keeps only the getter args
2146 args
.add
(self.n_value
)
2147 wcallsite
.check_signature
(v
, node
, args
)
2149 self.is_typed
= true
2153 redef class ACallReassignExpr
2154 redef fun property_name
do return n_qid
.n_id
.text
2155 redef fun property_node
do return n_qid
.n_id
2156 redef fun compute_raw_arguments
do return n_args
.to_a
2159 redef class ABraReassignExpr
2160 redef fun property_name
do return "[]"
2161 redef fun compute_raw_arguments
do return n_args
.to_a
2164 redef class AInitExpr
2165 redef fun property_name
do return "init"
2166 redef fun property_node
do return n_kwinit
2167 redef fun compute_raw_arguments
do return n_args
.to_a
2170 redef class ACallrefExpr
2171 redef fun property_name
do return n_qid
.n_id
.text
2172 redef fun property_node
do return n_qid
2173 redef fun compute_raw_arguments
do return n_args
.to_a
2175 redef fun accept_typing
(v
)
2177 super # do the job as if it was a real call
2178 var res
= callsite
.mproperty
2180 var msignature
= callsite
.mpropdef
.msignature
2181 var recv
= callsite
.recv
2182 assert msignature
!= null
2183 var arity
= msignature
.mparameters
.length
2185 var routine_type_name
= "ProcRef"
2186 if msignature
.return_mtype
!= null then
2187 routine_type_name
= "FunRef"
2190 var target_routine_class
= "{routine_type_name}{arity}"
2191 var routine_mclass
= v
.get_mclass
(self, target_routine_class
)
2193 if routine_mclass
== null then
2194 v
.error
(self, "Error: missing functional types, try `import functional`")
2198 var types_list
= new Array[MType]
2199 for param
in msignature
.mparameters
do
2200 if param
.is_vararg
then
2201 types_list
.push
(v
.mmodule
.array_type
(param
.mtype
))
2203 types_list
.push
(param
.mtype
)
2206 if msignature
.return_mtype
!= null then
2207 types_list
.push
(msignature
.return_mtype
.as(not null))
2210 # Why we need an anchor :
2214 # def toto(x: E) do print "{x}"
2217 # var a = new A[Int]
2218 # var f = &a.toto <- without anchor : ProcRef1[E]
2219 # ^--- with anchor : ProcRef[Int]
2221 var routine_type
= routine_mclass
.get_mtype
(types_list
).anchor_to
(v
.mmodule
, recv
.as(MClassType))
2224 self.mtype
= routine_type
2229 fun to_a
: Array[AExpr] do return self.n_exprs
.to_a
2234 redef class ASuperExpr
2235 # The method to call if the super is in fact a 'super init call'
2236 # Note: if the super is a normal call-next-method, then this attribute is null
2237 var callsite
: nullable CallSite
2239 # The method to call is the super is a standard `call-next-method` super-call
2240 # Note: if the super is a special super-init-call, then this attribute is null
2241 var mpropdef
: nullable MMethodDef
2243 redef fun accept_typing
(v
)
2245 var anchor
= v
.anchor
2246 var recvtype
= v
.get_variable
(self, v
.selfvariable
)
2247 assert recvtype
!= null
2248 var mproperty
= v
.mpropdef
.mproperty
2249 if not mproperty
isa MMethod then
2250 v
.error
(self, "Error: `super` only usable in a `method`.")
2253 var superprops
= mproperty
.lookup_super_definitions
(v
.mmodule
, anchor
)
2254 if superprops
.length
== 0 then
2255 if mproperty
.is_init
and v
.mpropdef
.is_intro
then
2256 process_superinit
(v
)
2259 v
.error
(self, "Error: no super method to call for `{mproperty}`.")
2262 # FIXME: covariance of return type in linear extension?
2263 var superprop
= superprops
.first
2265 var msignature
= superprop
.msignature
.as(not null)
2266 msignature
= v
.resolve_for
(msignature
, recvtype
, true).as(MSignature)
2267 var args
= self.n_args
.to_a
2268 if args
.length
> 0 then
2269 signaturemap
= v
.check_signature
(self, args
, mproperty
, msignature
)
2271 self.mtype
= msignature
.return_mtype
2272 self.is_typed
= true
2273 v
.mpropdef
.has_supercall
= true
2274 mpropdef
= v
.mpropdef
.as(MMethodDef)
2277 # The mapping used on the call to associate arguments to parameters.
2278 # If null then no specific association is required.
2279 var signaturemap
: nullable SignatureMap
2281 private fun process_superinit
(v
: TypeVisitor)
2283 var anchor
= v
.anchor
2284 var recvtype
= v
.get_variable
(self, v
.selfvariable
)
2285 assert recvtype
!= null
2286 var mpropdef
= v
.mpropdef
2287 assert mpropdef
isa MMethodDef
2288 var mproperty
= mpropdef
.mproperty
2289 var superprop
: nullable MMethodDef = null
2290 for msupertype
in mpropdef
.mclassdef
.supertypes
do
2291 msupertype
= msupertype
.anchor_to
(v
.mmodule
, anchor
)
2292 var errcount
= v
.modelbuilder
.toolcontext
.error_count
2293 var candidate
= v
.try_get_mproperty_by_name2
(self, msupertype
, mproperty
.name
).as(nullable MMethod)
2294 if candidate
== null then
2295 if v
.modelbuilder
.toolcontext
.error_count
> errcount
then return # Forward error
2296 continue # Try next super-class
2298 if superprop
!= null and candidate
.is_root_init
then
2301 if superprop
!= null and superprop
.mproperty
!= candidate
and not superprop
.mproperty
.is_root_init
then
2302 v
.error
(self, "Error: conflicting super constructor to call for `{mproperty}`: `{candidate.full_name}`, `{superprop.mproperty.full_name}`")
2305 var candidatedefs
= candidate
.lookup_definitions
(v
.mmodule
, anchor
)
2306 if superprop
!= null and superprop
.mproperty
== candidate
then
2307 if superprop
== candidatedefs
.first
then continue
2308 candidatedefs
.add
(superprop
)
2310 if candidatedefs
.length
> 1 then
2311 v
.error
(self, "Error: conflicting property definitions for property `{mproperty}` in `{recvtype}`: {candidatedefs.join(", ")}")
2314 superprop
= candidatedefs
.first
2316 if superprop
== null then
2317 v
.error
(self, "Error: no super method to call for `{mproperty}`.")
2321 var msignature
= superprop
.new_msignature
or else superprop
.msignature
.as(not null)
2322 msignature
= v
.resolve_for
(msignature
, recvtype
, true).as(MSignature)
2324 var callsite
= new CallSite(hot_location
, recvtype
, v
.mmodule
, v
.anchor
, true, superprop
.mproperty
, superprop
, msignature
, false)
2325 self.callsite
= callsite
2327 var args
= self.n_args
.to_a
2328 if args
.length
> 0 then
2329 callsite
.check_signature
(v
, self, args
)
2331 # Check there is at least enough parameters
2332 if mpropdef
.msignature
.arity
< msignature
.arity
then
2333 v
.error
(self, "Error: not enough implicit arguments to pass. Got `{mpropdef.msignature.arity}`, expected at least `{msignature.arity}`. Signature is `{msignature}`.")
2336 # Check that each needed parameter is conform
2338 for sp
in msignature
.mparameters
do
2339 var p
= mpropdef
.msignature
.mparameters
[i
]
2340 if not v
.is_subtype
(p
.mtype
, sp
.mtype
) then
2341 v
.error
(self, "Type Error: expected argument #{i} of type `{sp.mtype}`, got implicit argument `{p.name}` of type `{p.mtype}`. Signature is {msignature}")
2348 self.is_typed
= true
2351 redef fun dump_info
(v
) do
2353 var callsite
= self.callsite
2354 if callsite
!= null then
2355 res
+= v
.yellow
(" super-init="+callsite
.dump_info
(v
))
2357 var mpropdef
= self.mpropdef
2358 if mpropdef
!= null then
2359 res
+= v
.yellow
(" call-next-method="+mpropdef
.to_s
)
2367 redef class ANewExpr
2368 # The constructor invoked by the new.
2369 var callsite
: nullable CallSite
2371 # The designated type
2372 var recvtype
: nullable MClassType
2374 redef fun accept_typing
(v
)
2376 var recvtype
= v
.resolve_mtype
(self.n_type
)
2377 if recvtype
== null then return
2379 if not recvtype
isa MClassType then
2380 if recvtype
isa MNullableType then
2381 v
.error
(self, "Type Error: cannot instantiate the nullable type `{recvtype}`.")
2383 else if recvtype
isa MFormalType then
2384 v
.error
(self, "Type Error: cannot instantiate the formal type `{recvtype}`.")
2387 v
.error
(self, "Type Error: cannot instantiate the type `{recvtype}`.")
2392 self.recvtype
= recvtype
2393 var kind
= recvtype
.mclass
.kind
2396 var nqid
= self.n_qid
2398 if nqid
!= null then
2399 name
= nqid
.n_id
.text
2405 if name
== "intern" then
2406 if kind
!= concrete_kind
then
2407 v
.error
(self, "Type Error: cannot instantiate {kind} {recvtype}.")
2410 if n_args
.n_exprs
.not_empty
then
2411 v
.error
(n_args
, "Type Error: the intern constructor expects no arguments.")
2415 self.mtype
= recvtype
2419 var callsite
= v
.build_callsite_by_name
(node
, recvtype
, name
, false)
2420 if callsite
== null then return
2422 if not callsite
.mproperty
.is_new
then
2423 if kind
!= concrete_kind
then
2424 v
.error
(self, "Type Error: cannot instantiate {kind} `{recvtype}`.")
2427 self.mtype
= recvtype
2429 self.mtype
= callsite
.msignature
.return_mtype
2430 assert self.mtype
!= null
2433 self.callsite
= callsite
2435 if not callsite
.mproperty
.is_init_for
(recvtype
.mclass
) then
2436 v
.error
(self, "Error: `{name}` is not a constructor.")
2440 var args
= n_args
.to_a
2441 callsite
.check_signature
(v
, node
, args
)
2444 redef fun dump_info
(v
) do
2446 var callsite
= self.callsite
2447 if callsite
!= null then
2448 res
+= v
.yellow
(" call="+callsite
.dump_info
(v
))
2456 redef class AAttrFormExpr
2457 # The attribute accessed.
2458 var mproperty
: nullable MAttribute
2460 # The static type of the attribute.
2461 var attr_type
: nullable MType
2463 # Resolve the attribute accessed.
2464 private fun resolve_property
(v
: TypeVisitor)
2466 var recvtype
= v
.visit_expr
(self.n_expr
)
2467 if recvtype
== null then return # Skip error
2468 var node
= self.n_id
2469 var name
= node
.text
2470 if recvtype
isa MNullType then
2471 v
.error
(node
, "Error: attribute `{name}` access on `null`.")
2475 var unsafe_type
= v
.anchor_to
(recvtype
)
2476 var mproperty
= v
.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
2477 if mproperty
== null then
2478 v
.modelbuilder
.error
(node
, "Error: attribute `{name}` does not exist in `{recvtype}`.")
2481 assert mproperty
isa MAttribute
2482 self.mproperty
= mproperty
2484 var mpropdefs
= mproperty
.lookup_definitions
(v
.mmodule
, unsafe_type
)
2485 assert mpropdefs
.length
== 1
2486 var mpropdef
= mpropdefs
.first
2487 var attr_type
= mpropdef
.static_mtype
2488 if attr_type
== null then return # skip error
2489 attr_type
= v
.resolve_for
(attr_type
, recvtype
, self.n_expr
isa ASelfExpr)
2490 self.attr_type
= attr_type
2493 redef fun dump_info
(v
) do
2495 var mproperty
= self.mproperty
2496 var attr_type
= self.attr_type
2497 if mproperty
!= null then
2498 res
+= v
.yellow
(" attr={mproperty}:{attr_type or else "BROKEN"}")
2504 redef class AAttrExpr
2505 redef fun accept_typing
(v
)
2507 self.resolve_property
(v
)
2508 self.mtype
= self.attr_type
2513 redef class AAttrAssignExpr
2514 redef fun accept_typing
(v
)
2516 self.resolve_property
(v
)
2517 var mtype
= self.attr_type
2519 v
.visit_expr_subtype
(self.n_value
, mtype
)
2520 self.is_typed
= mtype
!= null
2524 redef class AAttrReassignExpr
2525 redef fun accept_typing
(v
)
2527 self.resolve_property
(v
)
2528 var mtype
= self.attr_type
2529 if mtype
== null then return # Skip error
2531 var rettype
= self.resolve_reassignment
(v
, mtype
, mtype
)
2533 self.is_typed
= rettype
!= null
2537 redef class AIssetAttrExpr
2538 redef fun accept_typing
(v
)
2540 self.resolve_property
(v
)
2541 var mtype
= self.attr_type
2542 if mtype
== null then return # Skip error
2544 var recvtype
= self.n_expr
.mtype
.as(not null)
2545 var bound
= v
.resolve_for
(mtype
, recvtype
, false)
2546 if bound
isa MNullableType then
2547 v
.error
(n_id
, "Type Error: `isset` on a nullable attribute.")
2549 self.mtype
= v
.type_bool
(self)
2553 redef class ASafeExpr
2554 redef fun accept_typing
(v
)
2556 var mtype
= v
.visit_expr
(n_expr
)
2557 if mtype
== null then return # Skip error
2559 if mtype
isa MNullType then
2560 # While `null?.foo` is semantically well defined and should not execute `foo` and just return `null`,
2561 # currently `null.foo` is forbidden so it seems coherent to also forbid `null?.foo`
2562 v
.modelbuilder
.error
(self, "Error: safe operator `?` on `null`.")
2566 self.mtype
= mtype
.as_notnull
2568 if not v
.can_be_null
(mtype
) then
2569 v
.modelbuilder
.warning
(self, "useless-safe", "Warning: useless safe operator `?` on non-nullable value.")
2575 redef class AVarargExpr
2576 redef fun accept_typing
(v
)
2578 # This kind of pseudo-expression can be only processed trough a signature
2579 # See `check_signature`
2580 # Other cases are a syntax error.
2581 v
.error
(self, "Syntax Error: unexpected `...`.")
2587 redef class ADebugTypeExpr
2588 redef fun accept_typing
(v
)
2590 var expr
= v
.visit_expr
(self.n_expr
)
2591 if expr
== null then return
2592 var unsafe
= v
.anchor_to
(expr
)
2593 var ntype
= self.n_type
2594 var mtype
= v
.resolve_mtype
(ntype
)
2595 if mtype
!= null and mtype
!= expr
then
2596 var umtype
= v
.anchor_to
(mtype
)
2597 v
.modelbuilder
.warning
(self, "debug", "Found type {expr} (-> {unsafe}), expected {mtype} (-> {umtype})")
2599 self.is_typed
= true