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
41 # The static type of the receiver
42 # Mainly used for type tests and type resolutions
43 var anchor
: nullable MClassType = null
45 # The analyzed mclassdef
46 var mclassdef
: nullable MClassDef = null
48 # The analyzed property
49 var mpropdef
: nullable 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
63 if mpropdef
!= null then
64 self.mpropdef
= mpropdef
65 var mclassdef
= mpropdef
.mclassdef
66 self.mclassdef
= mclassdef
67 self.anchor
= mclassdef
.bound_mtype
69 var mclass
= mclassdef
.mclass
71 var selfvariable
= new Variable("self")
72 self.selfvariable
= selfvariable
73 selfvariable
.declared_type
= mclass
.mclass_type
75 var mprop
= mpropdef
.mproperty
76 if mprop
isa MMethod and mprop
.is_new
then
77 is_toplevel_context
= true
82 fun anchor_to
(mtype
: MType): MType
85 if anchor
== null then
86 assert not mtype
.need_anchor
89 return mtype
.anchor_to
(mmodule
, anchor
)
92 fun is_subtype
(sub
, sup
: MType): Bool
94 return sub
.is_subtype
(mmodule
, anchor
, sup
)
97 fun resolve_for
(mtype
, subtype
: MType, for_self
: Bool): MType
99 #print "resolve_for {mtype} sub={subtype} forself={for_self} mmodule={mmodule} anchor={anchor}"
100 var res
= mtype
.resolve_for
(subtype
, anchor
, mmodule
, not for_self
)
104 # Check that `sub` is a subtype of `sup`.
105 # If `sub` is not a valid suptype, then display an error on `node` and return `null`.
106 # If `sub` is a safe subtype of `sup`, then return `sub`.
107 # If `sub` is an unsafe subtype (i.e., an implicit cast is required), then return `sup`.
109 # The point of the return type is to determinate the usable type on an expression when `autocast` is true:
110 # If the suptype is safe, then the return type is the one on the expression typed by `sub`.
111 # Is the subtype is unsafe, then the return type is the one of an implicit cast on `sup`.
112 fun check_subtype
(node
: ANode, sub
, sup
: MType, autocast
: Bool): nullable MType
114 if self.is_subtype
(sub
, sup
) then return sub
115 if autocast
and self.is_subtype
(sub
, self.anchor_to
(sup
)) then
116 # FIXME workaround to the current unsafe typing policy. To remove once fixed virtual types exists.
117 #node.debug("Unsafe typing: expected {sup}, got {sub}")
120 if sup
isa MErrorType then return null # Skip error
121 if sub
.need_anchor
then
122 var u
= anchor_to
(sub
)
123 self.modelbuilder
.error
(node
, "Type Error: expected `{sup}`, got `{sub}: {u}`.")
125 self.modelbuilder
.error
(node
, "Type Error: expected `{sup}`, got `{sub}`.")
130 # Visit an expression and do not care about the return value
131 fun visit_stmt
(nexpr
: nullable AExpr)
133 if nexpr
== null then return
134 nexpr
.accept_typing
(self)
137 # Visit an expression and expects that it is not a statement
138 # Return the type of the expression
139 # Display an error and return null if:
140 # * the type cannot be determined or
141 # * `nexpr` is a statement
142 fun visit_expr
(nexpr
: AExpr): nullable MType
144 nexpr
.accept_typing
(self)
145 var mtype
= nexpr
.mtype
146 if mtype
!= null then return mtype
147 if not nexpr
.is_typed
then
148 if not self.modelbuilder
.toolcontext
.error_count
> 0 then # check that there is really an error
149 if self.modelbuilder
.toolcontext
.verbose_level
> 1 then
150 nexpr
.debug
("No return type but no error.")
153 return null # forward error
155 var more_message
= null
157 if p
!= null then more_message
= p
.bad_expr_message
(nexpr
)
158 if more_message
== null then more_message
= "" else more_message
= " " + more_message
159 self.error
(nexpr
, "Error: expected an expression{more_message}.")
163 # Visit an expression and expect its static type is a least a `sup`
164 # Return the type of the expression or null if
165 # * the type cannot be determined or
166 # * `nexpr` is a statement or
167 # * `nexpr` is not a `sup`
168 fun visit_expr_subtype
(nexpr
: AExpr, sup
: nullable MType): nullable MType
170 var sub
= visit_expr
(nexpr
)
171 if sub
== null then return null # Forward error
173 if sup
== null then return null # Forward error
175 var res
= check_subtype
(nexpr
, sub
, sup
, true)
177 nexpr
.implicit_cast_to
= res
182 # Visit an expression and expect its static type is a `Bool`
183 # Return the type of the expression or null if
184 # * the type cannot be determined or
185 # * `nexpr` is a statement or
186 # * `nexpr` is not a `Bool`
187 fun visit_expr_bool
(nexpr
: AExpr): nullable MType
189 return self.visit_expr_subtype
(nexpr
, self.type_bool
(nexpr
))
193 fun check_expr_cast
(node
: ANode, nexpr
: AExpr, ntype
: AType): nullable MType
195 var sub
= nexpr
.mtype
196 if sub
== null then return null # Forward error
198 var sup
= ntype
.mtype
199 if sup
== null then return null # Forward error
202 self.modelbuilder
.warning
(node
, "useless-type-test", "Warning: expression is already a `{sup}`.")
203 else if self.is_subtype
(sub
, sup
) then
204 self.modelbuilder
.warning
(node
, "useless-type-test", "Warning: expression is already a `{sup}` since it is a `{sub}`.")
209 # Can `mtype` be null (up to the current knowledge)?
210 fun can_be_null
(mtype
: MType): Bool
212 if mtype
isa MNullableType or mtype
isa MNullType then return true
213 if mtype
isa MFormalType then
214 var x
= anchor_to
(mtype
)
215 if x
isa MNullableType or x
isa MNullType then return true
220 # Check that `mtype` can be null (up to the current knowledge).
222 # If not then display a `useless-null-test` warning on node and return false.
224 fun check_can_be_null
(anode
: ANode, mtype
: MType): Bool
226 if mtype
isa MNullType then
227 modelbuilder
.warning
(anode
, "useless-null-test", "Warning: expression is always `null`.")
230 if can_be_null
(mtype
) then return true
232 if mtype
isa MFormalType then
233 var res
= anchor_to
(mtype
)
234 modelbuilder
.warning
(anode
, "useless-null-test", "Warning: expression is not null, since it is a `{mtype}: {res}`.")
236 modelbuilder
.warning
(anode
, "useless-null-test", "Warning: expression is not null, since it is a `{mtype}`.")
241 # Special verification on != and == for null
243 fun null_test
(anode
: ABinopExpr)
245 var mtype
= anode
.n_expr
.mtype
246 var mtype2
= anode
.n_expr2
.mtype
248 if mtype
== null or mtype2
== null then return
250 if not mtype2
isa MNullType then return
252 # Check of useless null
253 if not can_be_null
(mtype
) then return
255 if mtype
isa MNullType then
256 # Because of type adaptation, we cannot just stop here
257 # so return use `null` as a bottom type that will be merged easily (cf) `merge_types`
260 mtype
= mtype
.as_notnull
263 # Check for type adaptation
264 var variable
= anode
.n_expr
.its_variable
265 if variable
== null then return
267 # One is null (mtype2 see above) the other is not null
268 if anode
isa AEqExpr then
269 anode
.after_flow_context
.when_true
.set_var
(self, variable
, mtype2
)
270 anode
.after_flow_context
.when_false
.set_var
(self, variable
, mtype
)
271 else if anode
isa ANeExpr then
272 anode
.after_flow_context
.when_false
.set_var
(self, variable
, mtype2
)
273 anode
.after_flow_context
.when_true
.set_var
(self, variable
, mtype
)
279 fun try_get_mproperty_by_name2
(anode
: ANode, mtype
: MType, name
: String): nullable MProperty
281 return self.modelbuilder
.try_get_mproperty_by_name2
(anode
, mmodule
, mtype
, name
)
284 fun resolve_mtype
(node
: AType): nullable MType
286 return self.modelbuilder
.resolve_mtype
(mmodule
, mclassdef
, node
)
289 fun try_get_mclass
(node
: ANode, name
: String): nullable MClass
291 var mclass
= modelbuilder
.try_get_mclass_by_name
(node
, mmodule
, name
)
295 fun get_mclass
(node
: ANode, name
: String): nullable MClass
297 var mclass
= modelbuilder
.get_mclass_by_name
(node
, mmodule
, name
)
301 fun type_bool
(node
: ANode): nullable MType
303 var mclass
= self.get_mclass
(node
, "Bool")
304 if mclass
== null then return null
305 return mclass
.mclass_type
308 fun get_method
(node
: ANode, recvtype
: MType, name
: String, recv_is_self
: Bool): nullable CallSite
310 var unsafe_type
= self.anchor_to
(recvtype
)
312 #debug("recv: {recvtype} (aka {unsafe_type})")
313 if recvtype
isa MNullType then
314 var objclass
= get_mclass
(node
, "Object")
315 if objclass
== null then return null # Forward error
316 unsafe_type
= objclass
.mclass_type
319 var mproperty
= self.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
320 if name
== "new" and mproperty
== null then
322 mproperty
= self.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
325 if mproperty
== null then
327 self.modelbuilder
.error
(node
, "Error: method or variable `{name}` unknown in `{recvtype}`.")
328 else if recvtype
.need_anchor
then
329 self.modelbuilder
.error
(node
, "Error: method `{name}` does not exists in `{recvtype}: {unsafe_type}`.")
331 self.modelbuilder
.error
(node
, "Error: method `{name}` does not exists in `{recvtype}`.")
336 assert mproperty
isa MMethod
338 # `null` only accepts some methods of object.
339 if recvtype
isa MNullType and not mproperty
.is_null_safe
then
340 self.error
(node
, "Error: method `{name}` called on `null`.")
342 else if unsafe_type
isa MNullableType and not mproperty
.is_null_safe
then
343 modelbuilder
.advice
(node
, "call-on-nullable", "Warning: method call on a nullable receiver `{recvtype}`.")
346 if is_toplevel_context
and recv_is_self
and not mproperty
.is_toplevel
then
347 error
(node
, "Error: `{name}` is not a top-level method, thus need a receiver.")
349 if not recv_is_self
and mproperty
.is_toplevel
then
350 error
(node
, "Error: cannot call `{name}`, a top-level method, with a receiver.")
353 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
354 self.modelbuilder
.error
(node
, "Error: method `{name}` is protected and can only accessed by `self`.")
358 var info
= mproperty
.deprecation
359 if info
!= null and self.mpropdef
.mproperty
.deprecation
== null then
362 self.modelbuilder
.warning
(node
, "deprecated-method", "Deprecation Warning: method `{name}` is deprecated: {mdoc.content.first}")
364 self.modelbuilder
.warning
(node
, "deprecated-method", "Deprecation Warning: method `{name}` is deprecated.")
368 var propdefs
= mproperty
.lookup_definitions
(self.mmodule
, unsafe_type
)
370 if propdefs
.length
== 0 then
371 self.modelbuilder
.error
(node
, "Type Error: no definition found for property `{name}` in `{unsafe_type}`.")
373 else if propdefs
.length
== 1 then
374 mpropdef
= propdefs
.first
376 self.modelbuilder
.warning
(node
, "property-conflict", "Warning: conflicting property definitions for property `{name}` in `{unsafe_type}`: {propdefs.join(" ")}")
377 mpropdef
= mproperty
.intro
381 var msignature
= mpropdef
.new_msignature
or else mpropdef
.msignature
382 if msignature
== null then return null # skip error
383 msignature
= resolve_for
(msignature
, recvtype
, recv_is_self
).as(MSignature)
385 var erasure_cast
= false
386 var rettype
= mpropdef
.msignature
.return_mtype
387 if not recv_is_self
and rettype
!= null then
388 rettype
= rettype
.undecorate
389 if rettype
isa MParameterType then
390 var erased_rettype
= msignature
.return_mtype
391 assert erased_rettype
!= null
392 #node.debug("Erasure cast: Really a {rettype} but unsafely a {erased_rettype}")
397 var callsite
= new CallSite(node
.hot_location
, recvtype
, mmodule
, anchor
, recv_is_self
, mproperty
, mpropdef
, msignature
, erasure_cast
)
401 fun try_get_method
(node
: ANode, recvtype
: MType, name
: String, recv_is_self
: Bool): nullable CallSite
403 var unsafe_type
= self.anchor_to
(recvtype
)
404 var mproperty
= self.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
405 if mproperty
== null then return null
406 return get_method
(node
, recvtype
, name
, recv_is_self
)
410 # Visit the expressions of args and check their conformity with the corresponding type in signature
411 # The point of this method is to handle varargs correctly
412 # Note: The signature must be correctly adapted
413 fun check_signature
(node
: ANode, args
: Array[AExpr], mproperty
: MProperty, msignature
: MSignature): nullable SignatureMap
415 var vararg_rank
= msignature
.vararg_rank
416 if vararg_rank
>= 0 then
417 if args
.length
< msignature
.arity
then
418 modelbuilder
.error
(node
, "Error: expected at least {msignature.arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
421 else if args
.length
!= msignature
.arity
then
423 if args
.length
> msignature
.arity
then
424 modelbuilder
.error
(node
, "Error: expected {msignature.arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
427 # Other cases are managed later
431 #debug("CALL {unsafe_type}.{msignature}")
433 # Associate each parameter to a position in the arguments
434 var map
= new SignatureMap
436 # Special case for the isolated last argument
437 # TODO: reify this method characteristics (where? the param, the signature, the method?)
438 var last_is_padded
= mproperty
.name
.chars
.last
== '='
439 var nbargs
= args
.length
440 if last_is_padded
then
442 assert not args
.last
isa ANamedargExpr
443 map
.map
[msignature
.arity
- 1] = args
.length
- 1
444 self.visit_expr_subtype
(args
.last
, msignature
.mparameters
.last
.mtype
)
447 # First, handle named arguments
448 for i
in [0..args
.length
[ do
450 if not e
isa ANamedargExpr then continue
451 var name
= e
.n_id
.text
452 var param
= msignature
.mparameter_by_name
(name
)
453 if param
== null then
454 modelbuilder
.error
(e
.n_id
, "Error: no parameter `{name}` for `{mproperty}{msignature}`.")
457 var idx
= msignature
.mparameters
.index_of
(param
)
458 var prev
= map
.map
.get_or_null
(idx
)
460 modelbuilder
.error
(e
, "Error: parameter `{name}` already associated with argument #{prev} for `{mproperty}{msignature}`.")
464 e
.mtype
= self.visit_expr_subtype
(e
.n_expr
, param
.mtype
)
467 # Number of minimum mandatory remaining parameters
470 # Second, associate remaining parameters
471 var vararg_decl
= args
.length
- msignature
.arity
473 for i
in [0..msignature
.arity
[ do
474 # Skip parameters associated by name
475 if map
.map
.has_key
(i
) then continue
477 var param
= msignature
.mparameters
[i
]
479 # Search the next free argument: skip named arguments since they are already associated
480 while j
< nbargs
and args
[j
] isa ANamedargExpr do j
+= 1
482 if not param
.mtype
isa MNullableType then
492 if i
== vararg_rank
then
494 continue # skip the vararg
497 if not param
.is_vararg
then
498 var paramtype
= param
.mtype
499 self.visit_expr_subtype
(arg
, paramtype
)
501 check_one_vararg
(arg
, param
)
505 if min_arity
> 0 then
506 if last_is_padded
then min_arity
+= 1
507 if min_arity
< msignature
.arity
then
508 modelbuilder
.error
(node
, "Error: expected at least {min_arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
510 modelbuilder
.error
(node
, "Error: expected {min_arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
515 # Third, check varargs
516 if vararg_rank
>= 0 then
517 var paramtype
= msignature
.mparameters
[vararg_rank
].mtype
518 var first
= args
[vararg_rank
]
519 if vararg_decl
== 0 then
520 if not check_one_vararg
(first
, msignature
.mparameters
[vararg_rank
]) then return null
522 first
.vararg_decl
= vararg_decl
+ 1
523 for i
in [vararg_rank
..vararg_rank
+vararg_decl
] do
524 self.visit_expr_subtype
(args
[i
], paramtype
)
532 # Check an expression as a single vararg.
533 # The main point of the method if to handle the case of reversed vararg (see `AVarargExpr`)
534 fun check_one_vararg
(arg
: AExpr, param
: MParameter): Bool
536 var paramtype
= param
.mtype
537 var mclass
= get_mclass
(arg
, "Array")
538 if mclass
== null then return false # Forward error
539 var array_mtype
= mclass
.get_mtype
([paramtype
])
540 if arg
isa AVarargExpr then
541 self.visit_expr_subtype
(arg
.n_expr
, array_mtype
)
542 arg
.mtype
= arg
.n_expr
.mtype
544 # only one vararg, maybe `...` was forgot, so be gentle!
545 var t
= visit_expr
(arg
)
546 if t
== null then return false # Forward error
547 if not is_subtype
(t
, paramtype
) and is_subtype
(t
, array_mtype
) then
548 # Not acceptable but could be a `...`
549 error
(arg
, "Type Error: expected `{paramtype}`, got `{t}`. Is an ellipsis `...` missing on the argument?")
552 # Standard valid vararg, finish the job
554 self.visit_expr_subtype
(arg
, paramtype
)
559 fun error
(node
: ANode, message
: String)
561 self.modelbuilder
.error
(node
, message
)
564 fun get_variable
(node
: AExpr, variable
: Variable): nullable MType
566 if not variable
.is_adapted
then return variable
.declared_type
568 var flow
= node
.after_flow_context
569 if flow
== null then return null # skip error
571 if flow
.vars
.has_key
(variable
) then
572 return flow
.vars
[variable
]
574 #node.debug("*** START Collected for {variable}")
575 var mtypes
= flow
.collect_types
(variable
)
576 #node.debug("**** END Collected for {variable}")
577 if mtypes
.length
== 0 then
578 return variable
.declared_type
579 else if mtypes
.length
== 1 then
582 var res
= merge_types
(node
,mtypes
)
583 if res
== null then res
= variable
.declared_type
589 # Some variables where type-adapted during the visit
592 # Some loops had been visited during the visit
595 fun set_variable
(node
: AExpr, variable
: Variable, mtype
: nullable MType)
597 var flow
= node
.after_flow_context
600 flow
.set_var
(self, variable
, mtype
)
603 fun merge_types
(node
: ANode, col
: Array[nullable MType]): nullable MType
605 if col
.length
== 1 then return col
.first
607 if t1
== null then continue # return null
610 if t2
== null then continue # return null
611 if can_be_null
(t2
) and not can_be_null
(t1
) then
614 if not is_subtype
(t2
, t1
) then found
= false
617 #print "merge {col.join(" ")} -> {t1}"
621 #self.modelbuilder.warning(node, "Type Error: {col.length} conflicting types: <{col.join(", ")}>")
626 # Mapping between parameters and arguments in a call.
628 # Parameters and arguments are not stored in the class but referenced by their position (starting from 0)
630 # The point of this class is to help engine and other things to map arguments in the AST to parameters of the model.
632 # Associate a parameter to an argument
633 var map
= new ArrayMap[Int, Int]
636 # A specific method call site with its associated informations.
640 redef var location
: Location
642 # The static type of the receiver (possibly unresolved)
645 # The module where the callsite is present
648 # The anchor to use with `recv` or `msignature`
649 var anchor
: nullable MClassType
651 # Is the receiver self?
652 # If "for_self", virtual types of the signature are kept
653 # If "not_for_self", virtual type are erased
654 var recv_is_self
: Bool
656 # The designated method
657 var mproperty
: MMethod
659 # The statically designated method definition
660 # The most specif one, it is.
661 var mpropdef
: MMethodDef
663 # The resolved signature for the receiver
664 var msignature
: MSignature
666 # Is a implicit cast required on erasure typing policy?
667 var erasure_cast
: Bool
669 # The mapping used on the call to associate arguments to parameters
670 # If null then no specific association is required.
671 var signaturemap
: nullable SignatureMap = null
673 private fun check_signature
(v
: TypeVisitor, node
: ANode, args
: Array[AExpr]): Bool
675 var map
= v
.check_signature
(node
, args
, self.mproperty
, self.msignature
)
677 if map
== null then is_broken
= true
681 # Information about the callsite to display on a node
682 fun dump_info
(v
: ASTDump): String do
683 return "{recv}.{mpropdef}{msignature}"
688 # The declared type of the variable
689 var declared_type
: nullable MType is writable
691 # Was the variable type-adapted?
692 # This is used to speedup type retrieval while it remains `false`
693 private var is_adapted
= false
696 redef class FlowContext
697 # Store changes of types because of type evolution
698 private var vars
= new HashMap[Variable, nullable MType]
700 # Adapt the variable to a static type
701 # Warning1: do not modify vars directly.
702 # Warning2: sub-flow may have cached a unadapted variable
703 private fun set_var
(v
: TypeVisitor, variable
: Variable, mtype
: nullable MType)
705 if variable
.declared_type
== mtype
and not variable
.is_adapted
then return
706 if vars
.has_key
(variable
) and vars
[variable
] == mtype
then return
707 self.vars
[variable
] = mtype
709 variable
.is_adapted
= true
710 #node.debug "set {variable} to {mtype or else "X"}"
713 # Look in the flow and previous flow and collect all first reachable type adaptation of a local variable
714 private fun collect_types
(variable
: Variable): Array[nullable MType]
716 #node.debug "flow for {variable}"
717 var res
= new Array[nullable MType]
720 var seen
= new HashSet[FlowContext]
721 while not todo
.is_empty
do
723 if f
.is_unreachable
then continue
724 if seen
.has
(f
) then continue
727 if f
.vars
.has_key
(variable
) then
728 # Found something. Collect it and do not process further on this path
729 res
.add f
.vars
[variable
]
730 #f.node.debug "process {variable}: got {f.vars[variable] or else "X"}"
732 todo
.add_all f
.previous
734 if f
.previous
.is_empty
then
735 # Root flowcontext mean a parameter or something related
736 res
.add variable
.declared_type
737 #f.node.debug "root process {variable}: got {variable.declared_type or else "X"}"
741 #self.node.debug "##### end flow for {variable}: {res.join(" ")}"
747 # The entry point of the whole typing analysis
748 fun do_typing
(modelbuilder
: ModelBuilder)
752 # The variable associated to the receiver (if any)
753 var selfvariable
: nullable Variable
756 redef class AMethPropdef
757 redef fun do_typing
(modelbuilder
: ModelBuilder)
759 var mpropdef
= self.mpropdef
760 if mpropdef
== null then return # skip error
762 var v
= new TypeVisitor(modelbuilder
, mpropdef
.mclassdef
.mmodule
, mpropdef
)
763 self.selfvariable
= v
.selfvariable
765 var mmethoddef
= self.mpropdef
.as(not null)
766 var msignature
= mmethoddef
.msignature
767 if msignature
== null then return # skip error
768 for i
in [0..msignature
.arity
[ do
769 var mtype
= msignature
.mparameters
[i
].mtype
770 if msignature
.vararg_rank
== i
then
771 var arrayclass
= v
.get_mclass
(self.n_signature
.n_params
[i
], "Array")
772 if arrayclass
== null then return # Skip error
773 mtype
= arrayclass
.get_mtype
([mtype
])
775 var variable
= self.n_signature
.n_params
[i
].variable
776 assert variable
!= null
777 variable
.declared_type
= mtype
780 var nblock
= self.n_block
781 if nblock
== null then return
786 if not v
.has_loop
or not v
.dirty
then break
789 var post_visitor
= new PostTypingVisitor(v
)
790 post_visitor
.enter_visit
(self)
792 if not nblock
.after_flow_context
.is_unreachable
and msignature
.return_mtype
!= null then
793 # We reach the end of the function without having a return, it is bad
794 v
.error
(self, "Error: reached end of function; expected `return` with a value.")
799 private class PostTypingVisitor
801 var type_visitor
: TypeVisitor
802 redef fun visit
(n
) do
804 n
.accept_post_typing
(type_visitor
)
805 if n
isa AExpr and n
.mtype
== null and not n
.is_typed
then
812 private fun accept_post_typing
(v
: TypeVisitor) do end
814 # An additional information message to explain the role of a child expression.
816 # The point of the method is to allow some kind of double dispatch so the parent
817 # choose how to describe its children.
818 private fun bad_expr_message
(child
: AExpr): nullable String do return null
821 redef class AAttrPropdef
822 redef fun do_typing
(modelbuilder
: ModelBuilder)
824 if not has_value
then return
826 var mpropdef
= self.mreadpropdef
827 if mpropdef
== null or mpropdef
.msignature
== null then return # skip error
829 var v
= new TypeVisitor(modelbuilder
, mpropdef
.mclassdef
.mmodule
, mpropdef
)
830 self.selfvariable
= v
.selfvariable
832 var nexpr
= self.n_expr
833 if nexpr
!= null then
834 var mtype
= self.mtype
835 v
.visit_expr_subtype
(nexpr
, mtype
)
837 var nblock
= self.n_block
838 if nblock
!= null then
840 if not nblock
.after_flow_context
.is_unreachable
then
841 # We reach the end of the init without having a return, it is bad
842 v
.error
(self, "Error: reached end of block; expected `return`.")
851 # The static type of the expression.
852 # null if self is a statement or in case of error
853 var mtype
: nullable MType = null
855 # Is the statement correctly typed?
856 # Used to distinguish errors and statements when `mtype == null`
857 var is_typed
: Bool = false
859 # If required, the following implicit cast `.as(XXX)`
860 # Such a cast may by required after evaluating the expression when
861 # a unsafe operation is detected (silently accepted by the Nit language).
862 # The attribute is computed by `check_subtype`
863 var implicit_cast_to
: nullable MType = null
865 # Return the variable read (if any)
866 # Used to perform adaptive typing
867 fun its_variable
: nullable Variable do return null
869 private fun accept_typing
(v
: TypeVisitor)
871 v
.error
(self, "no implemented accept_typing for {self.class_name}")
874 # Is non-null if `self` is a leaf of a comprehension array construction.
875 # In this case, the enclosing literal array node is designated.
876 # The result of the evaluation of `self` must be
877 # stored inside the designated array (there is an implicit `push`)
878 var comprehension
: nullable AArrayExpr = null
880 # It indicates the number of arguments collected as a vararg.
882 # When 0, the argument is used as is, without transformation.
883 # When 1, the argument is transformed into an singleton array.
884 # Above 1, the arguments and the next ones are transformed into a common array.
886 # This attribute is meaning less on expressions not used as attributes.
887 var vararg_decl
: Int = 0
889 redef fun dump_info
(v
) do
891 var mtype
= self.mtype
892 if mtype
!= null then
893 res
+= v
.yellow
(":{mtype}")
895 var ict
= self.implicit_cast_to
897 res
+= v
.yellow
("(.as({ict}))")
903 redef class ABlockExpr
904 redef fun accept_typing
(v
)
906 for e
in self.n_expr
do v
.visit_stmt
(e
)
910 # The type of a blockexpr is the one of the last expression (or null if empty)
913 if self.n_expr
.is_empty
then return null
914 return self.n_expr
.last
.mtype
918 redef class AVardeclExpr
919 redef fun accept_typing
(v
)
921 var variable
= self.variable
922 if variable
== null then return # Skip error
924 var ntype
= self.n_type
925 var mtype
: nullable MType
926 if ntype
== null then
929 mtype
= v
.resolve_mtype
(ntype
)
930 if mtype
== null then return # Skip error
933 var nexpr
= self.n_expr
934 if nexpr
!= null then
935 if mtype
!= null then
936 var etype
= v
.visit_expr_subtype
(nexpr
, mtype
)
937 if etype
== mtype
then
939 v
.modelbuilder
.advice
(ntype
, "useless-type", "Warning: useless type definition for variable `{variable.name}`")
942 mtype
= v
.visit_expr
(nexpr
)
943 if mtype
== null then return # Skip error
948 if mtype
== null or mtype
isa MNullType then
949 var objclass
= v
.get_mclass
(self, "Object")
950 if objclass
== null then return # skip error
951 decltype
= objclass
.mclass_type
.as_nullable
952 if mtype
== null then mtype
= decltype
955 variable
.declared_type
= decltype
956 v
.set_variable
(self, variable
, mtype
)
958 #debug("var {variable}: {mtype}")
966 redef fun its_variable
do return self.variable
967 redef fun accept_typing
(v
)
969 var variable
= self.variable
970 if variable
== null then return # Skip error
972 var mtype
= v
.get_variable
(self, variable
)
973 if mtype
!= null then
974 #debug("{variable} is {mtype}")
976 #debug("{variable} is untyped")
983 redef class AVarAssignExpr
984 redef fun accept_typing
(v
)
986 var variable
= self.variable
987 assert variable
!= null
989 var mtype
= v
.visit_expr_subtype
(n_value
, variable
.declared_type
)
991 v
.set_variable
(self, variable
, mtype
)
997 redef class AReassignFormExpr
998 # The method designed by the reassign operator.
999 var reassign_callsite
: nullable CallSite
1001 var read_type
: nullable MType = null
1003 # Determine the `reassign_property`
1004 # `readtype` is the type of the reading of the left value.
1005 # `writetype` is the type of the writing of the left value.
1006 # (Because of `ACallReassignExpr`, both can be different.
1007 # Return the static type of the value to store.
1008 private fun resolve_reassignment
(v
: TypeVisitor, readtype
, writetype
: MType): nullable MType
1010 var reassign_name
= self.n_assign_op
.operator
1012 self.read_type
= readtype
1014 var callsite
= v
.get_method
(self.n_assign_op
, readtype
, reassign_name
, false)
1015 if callsite
== null then return null # Skip error
1016 self.reassign_callsite
= callsite
1018 var msignature
= callsite
.msignature
1019 var rettype
= msignature
.return_mtype
1020 assert msignature
.arity
== 1 and rettype
!= null
1022 var value_type
= v
.visit_expr_subtype
(self.n_value
, msignature
.mparameters
.first
.mtype
)
1023 if value_type
== null then return null # Skip error
1025 v
.check_subtype
(self, rettype
, writetype
, false)
1030 redef class AVarReassignExpr
1031 redef fun accept_typing
(v
)
1033 var variable
= self.variable
1034 assert variable
!= null
1036 var readtype
= v
.get_variable
(self, variable
)
1037 if readtype
== null then return
1039 read_type
= readtype
1041 var writetype
= variable
.declared_type
1042 if writetype
== null then return
1044 var rettype
= self.resolve_reassignment
(v
, readtype
, writetype
)
1046 v
.set_variable
(self, variable
, rettype
)
1048 self.is_typed
= rettype
!= null
1053 redef class AContinueExpr
1054 redef fun accept_typing
(v
)
1056 var nexpr
= self.n_expr
1057 if nexpr
!= null then
1060 self.is_typed
= true
1064 redef class ABreakExpr
1065 redef fun accept_typing
(v
)
1067 var nexpr
= self.n_expr
1068 if nexpr
!= null then
1071 self.is_typed
= true
1075 redef class AReturnExpr
1076 redef fun accept_typing
(v
)
1078 var nexpr
= self.n_expr
1080 var mpropdef
= v
.mpropdef
1081 if mpropdef
isa MMethodDef then
1082 ret_type
= mpropdef
.msignature
.return_mtype
1083 else if mpropdef
isa MAttributeDef then
1084 ret_type
= mpropdef
.static_mtype
1088 if nexpr
!= null then
1089 if ret_type
!= null then
1090 v
.visit_expr_subtype
(nexpr
, ret_type
)
1093 v
.error
(nexpr
, "Error: `return` with value in a procedure.")
1096 else if ret_type
!= null then
1097 v
.error
(self, "Error: `return` without value in a function.")
1100 self.is_typed
= true
1104 redef class AAbortExpr
1105 redef fun accept_typing
(v
)
1107 self.is_typed
= true
1112 redef fun accept_typing
(v
)
1114 v
.visit_expr_bool
(n_expr
)
1116 v
.visit_stmt
(n_then
)
1117 v
.visit_stmt
(n_else
)
1119 self.is_typed
= true
1121 if n_then
!= null and n_else
== null then
1122 self.mtype
= n_then
.mtype
1127 redef class AIfexprExpr
1128 redef fun accept_typing
(v
)
1130 v
.visit_expr_bool
(n_expr
)
1132 var t1
= v
.visit_expr
(n_then
)
1133 var t2
= v
.visit_expr
(n_else
)
1135 if t1
== null or t2
== null then
1139 var t
= v
.merge_types
(self, [t1
, t2
])
1141 v
.error
(self, "Type Error: ambiguous type `{t1}` vs `{t2}`.")
1148 redef fun accept_typing
(v
)
1150 v
.visit_stmt
(n_block
)
1151 v
.visit_stmt
(n_catch
)
1152 self.is_typed
= true
1156 redef class AWhileExpr
1157 redef fun accept_typing
(v
)
1160 v
.visit_expr_bool
(n_expr
)
1161 v
.visit_stmt
(n_block
)
1162 self.is_typed
= true
1166 redef class ALoopExpr
1167 redef fun accept_typing
(v
)
1170 v
.visit_stmt
(n_block
)
1171 self.is_typed
= true
1175 redef class AForExpr
1176 redef fun accept_typing
(v
)
1180 for g
in n_groups
do
1181 var mtype
= v
.visit_expr
(g
.n_expr
)
1182 if mtype
== null then return
1183 g
.do_type_iterator
(v
, mtype
)
1184 if g
.is_broken
then is_broken
= true
1187 v
.visit_stmt
(n_block
)
1189 self.mtype
= n_block
.mtype
1190 self.is_typed
= true
1194 redef class AForGroup
1195 var coltype
: nullable MClassType
1197 var method_iterator
: nullable CallSite
1198 var method_is_ok
: nullable CallSite
1199 var method_item
: nullable CallSite
1200 var method_next
: nullable CallSite
1201 var method_key
: nullable CallSite
1202 var method_finish
: nullable CallSite
1204 var method_lt
: nullable CallSite
1205 var method_successor
: nullable CallSite
1207 private fun do_type_iterator
(v
: TypeVisitor, mtype
: MType)
1209 if mtype
isa MNullType then
1210 v
.error
(self, "Type Error: `for` cannot iterate over `null`.")
1215 var objcla
= v
.get_mclass
(self, "Object")
1216 if objcla
== null then return
1218 # check iterator method
1219 var itdef
= v
.get_method
(self, mtype
, "iterator", n_expr
isa ASelfExpr)
1220 if itdef
== null then
1221 v
.error
(self, "Type Error: `for` expects a type providing an `iterator` method, got `{mtype}`.")
1224 self.method_iterator
= itdef
1226 # check that iterator return something
1227 var ittype
= itdef
.msignature
.return_mtype
1228 if ittype
== null then
1229 v
.error
(self, "Type Error: `for` expects the method `iterator` to return an `Iterator` or `MapIterator` type.")
1234 var colit_cla
= v
.try_get_mclass
(self, "Iterator")
1235 var mapit_cla
= v
.try_get_mclass
(self, "MapIterator")
1239 if colit_cla
!= null and v
.is_subtype
(ittype
, colit_cla
.get_mtype
([objcla
.mclass_type
.as_nullable
])) then
1241 var coltype
= ittype
.supertype_to
(v
.mmodule
, v
.anchor
, colit_cla
)
1242 var variables
= self.variables
1243 if variables
.length
!= 1 then
1244 v
.error
(self, "Type Error: `for` expects only one variable when using `Iterator`.")
1246 variables
.first
.declared_type
= coltype
.arguments
.first
1251 if mapit_cla
!= null and v
.is_subtype
(ittype
, mapit_cla
.get_mtype
([objcla
.mclass_type
.as_nullable
, objcla
.mclass_type
.as_nullable
])) then
1253 var coltype
= ittype
.supertype_to
(v
.mmodule
, v
.anchor
, mapit_cla
)
1254 var variables
= self.variables
1255 if variables
.length
!= 2 then
1256 v
.error
(self, "Type Error: `for` expects two variables when using `MapIterator`.")
1258 variables
[0].declared_type
= coltype
.arguments
[0]
1259 variables
[1].declared_type
= coltype
.arguments
[1]
1264 if not is_col
and not is_map
then
1265 v
.error
(self, "Type Error: `for` expects the method `iterator` to return an `Iterator` or `MapIterator` type.")
1269 # anchor formal and virtual types
1270 if mtype
.need_anchor
then mtype
= v
.anchor_to
(mtype
)
1272 mtype
= mtype
.undecorate
1273 self.coltype
= mtype
.as(MClassType)
1275 # get methods is_ok, next, item
1276 var ikdef
= v
.get_method
(self, ittype
, "is_ok", false)
1277 if ikdef
== null then
1278 v
.error
(self, "Type Error: `for` expects a method `is_ok` in type `{ittype}`.")
1281 self.method_is_ok
= ikdef
1283 var itemdef
= v
.get_method
(self, ittype
, "item", false)
1284 if itemdef
== null then
1285 v
.error
(self, "Type Error: `for` expects a method `item` in type `{ittype}`.")
1288 self.method_item
= itemdef
1290 var nextdef
= v
.get_method
(self, ittype
, "next", false)
1291 if nextdef
== null then
1292 v
.error
(self, "Type Error: `for` expects a method `next` in type {ittype}.")
1295 self.method_next
= nextdef
1297 self.method_finish
= v
.try_get_method
(self, ittype
, "finish", false)
1300 var keydef
= v
.get_method
(self, ittype
, "key", false)
1301 if keydef
== null then
1302 v
.error
(self, "Type Error: `for` expects a method `key` in type `{ittype}`.")
1305 self.method_key
= keydef
1308 if self.variables
.length
== 1 and n_expr
isa ARangeExpr then
1309 var variable
= variables
.first
1310 var vtype
= variable
.declared_type
.as(not null)
1312 if n_expr
isa AOrangeExpr then
1313 self.method_lt
= v
.get_method
(self, vtype
, "<", false)
1315 self.method_lt
= v
.get_method
(self, vtype
, "<=", false)
1318 self.method_successor
= v
.get_method
(self, vtype
, "successor", false)
1323 redef class AWithExpr
1324 var method_start
: nullable CallSite
1325 var method_finish
: nullable CallSite
1327 redef fun accept_typing
(v
: TypeVisitor)
1329 var mtype
= v
.visit_expr
(n_expr
)
1330 if mtype
== null then return
1332 method_start
= v
.get_method
(self, mtype
, "start", n_expr
isa ASelfExpr)
1333 method_finish
= v
.get_method
(self, mtype
, "finish", n_expr
isa ASelfExpr)
1335 v
.visit_stmt
(n_block
)
1336 self.mtype
= n_block
.mtype
1337 self.is_typed
= true
1341 redef class AAssertExpr
1342 redef fun accept_typing
(v
)
1344 v
.visit_expr_bool
(n_expr
)
1346 v
.visit_stmt
(n_else
)
1347 self.is_typed
= true
1352 redef fun accept_typing
(v
)
1354 v
.visit_expr_bool
(n_expr
)
1355 v
.visit_expr_bool
(n_expr2
)
1356 self.mtype
= v
.type_bool
(self)
1360 redef class AImpliesExpr
1361 redef fun accept_typing
(v
)
1363 v
.visit_expr_bool
(n_expr
)
1364 v
.visit_expr_bool
(n_expr2
)
1365 self.mtype
= v
.type_bool
(self)
1369 redef class AAndExpr
1370 redef fun accept_typing
(v
)
1372 v
.visit_expr_bool
(n_expr
)
1373 v
.visit_expr_bool
(n_expr2
)
1374 self.mtype
= v
.type_bool
(self)
1379 redef class ANotExpr
1380 redef fun accept_typing
(v
)
1382 v
.visit_expr_bool
(n_expr
)
1383 self.mtype
= v
.type_bool
(self)
1387 redef class AOrElseExpr
1388 redef fun accept_typing
(v
)
1390 var t1
= v
.visit_expr
(n_expr
)
1391 var t2
= v
.visit_expr
(n_expr2
)
1393 if t1
== null or t2
== null then
1397 if t1
isa MNullType then
1400 else if v
.can_be_null
(t1
) then
1404 var t
= v
.merge_types
(self, [t1
, t2
])
1406 var c
= v
.get_mclass
(self, "Object")
1407 if c
== null then return # forward error
1409 if v
.can_be_null
(t2
) then
1412 #v.error(self, "Type Error: ambiguous type {t1} vs {t2}")
1417 redef fun accept_post_typing
(v
)
1419 var t1
= n_expr
.mtype
1423 v
.check_can_be_null
(n_expr
, t1
)
1428 redef class ATrueExpr
1429 redef fun accept_typing
(v
)
1431 self.mtype
= v
.type_bool
(self)
1435 redef class AFalseExpr
1436 redef fun accept_typing
(v
)
1438 self.mtype
= v
.type_bool
(self)
1442 redef class AIntegerExpr
1443 redef fun accept_typing
(v
)
1445 var mclass
: nullable MClass = null
1446 if value
isa Byte then
1447 mclass
= v
.get_mclass
(self, "Byte")
1448 else if value
isa Int then
1449 mclass
= v
.get_mclass
(self, "Int")
1450 else if value
isa Int8 then
1451 mclass
= v
.get_mclass
(self, "Int8")
1452 else if value
isa Int16 then
1453 mclass
= v
.get_mclass
(self, "Int16")
1454 else if value
isa UInt16 then
1455 mclass
= v
.get_mclass
(self, "UInt16")
1456 else if value
isa Int32 then
1457 mclass
= v
.get_mclass
(self, "Int32")
1458 else if value
isa UInt32 then
1459 mclass
= v
.get_mclass
(self, "UInt32")
1461 if mclass
== null then return # Forward error
1462 self.mtype
= mclass
.mclass_type
1466 redef class AFloatExpr
1467 redef fun accept_typing
(v
)
1469 var mclass
= v
.get_mclass
(self, "Float")
1470 if mclass
== null then return # Forward error
1471 self.mtype
= mclass
.mclass_type
1475 redef class ACharExpr
1476 redef fun accept_typing
(v
) do
1477 var mclass
: nullable MClass = null
1479 mclass
= v
.get_mclass
(self, "Byte")
1480 else if is_code_point
then
1481 mclass
= v
.get_mclass
(self, "Int")
1483 mclass
= v
.get_mclass
(self, "Char")
1485 if mclass
== null then return # Forward error
1486 self.mtype
= mclass
.mclass_type
1490 redef class AugmentedStringFormExpr
1493 # Text::to_re, used for prefix `re`
1494 var to_re
: nullable CallSite = null
1495 # Regex::ignore_case, used for suffix `i` on `re`
1496 var ignore_case
: nullable CallSite = null
1497 # Regex::newline, used for suffix `m` on `re`
1498 var newline
: nullable CallSite = null
1499 # Regex::extended, used for suffix `b` on `re`
1500 var extended
: nullable CallSite = null
1501 # CString::to_bytes_with_copy, used for prefix `b`
1502 var to_bytes_with_copy
: nullable CallSite = null
1504 redef fun accept_typing
(v
) do
1505 var mclass
= v
.get_mclass
(self, "String")
1506 if mclass
== null then return # Forward error
1507 if is_bytestring
then
1508 to_bytes_with_copy
= v
.get_method
(self, v
.mmodule
.c_string_type
, "to_bytes_with_copy", false)
1509 mclass
= v
.get_mclass
(self, "Bytes")
1511 to_re
= v
.get_method
(self, mclass
.mclass_type
, "to_re", false)
1512 for i
in suffix
.chars
do
1513 mclass
= v
.get_mclass
(self, "Regex")
1514 if mclass
== null then
1515 v
.error
(self, "Error: `Regex` class unknown")
1520 service
= "ignore_case="
1521 ignore_case
= v
.get_method
(self, mclass
.mclass_type
, service
, false)
1522 else if i
== 'm' then
1523 service
= "newline="
1524 newline
= v
.get_method
(self, mclass
.mclass_type
, service
, false)
1525 else if i
== 'b' then
1526 service
= "extended="
1527 extended
= v
.get_method
(self, mclass
.mclass_type
, service
, false)
1529 v
.error
(self, "Type Error: Unrecognized suffix {i} in prefixed Regex")
1534 if mclass
== null then return # Forward error
1535 mtype
= mclass
.mclass_type
1539 redef class ASuperstringExpr
1540 redef fun accept_typing
(v
)
1543 var objclass
= v
.get_mclass
(self, "Object")
1544 if objclass
== null then return # Forward error
1545 var objtype
= objclass
.mclass_type
1546 for nexpr
in self.n_exprs
do
1547 v
.visit_expr_subtype
(nexpr
, objtype
)
1552 redef class AArrayExpr
1553 # The `with_capacity` method on Array
1554 var with_capacity_callsite
: nullable CallSite
1556 # The `push` method on arrays
1557 var push_callsite
: nullable CallSite
1559 # The element of each type
1560 var element_mtype
: nullable MType
1562 # Set that `self` is a part of comprehension array `na`
1563 # If `self` is a `for`, or a `if`, then `set_comprehension` is recursively applied.
1564 private fun set_comprehension
(n
: nullable AExpr)
1568 else if n
isa AForExpr then
1569 set_comprehension
(n
.n_block
)
1570 else if n
isa AIfExpr then
1571 set_comprehension
(n
.n_then
)
1572 set_comprehension
(n
.n_else
)
1575 n
.comprehension
= self
1578 redef fun accept_typing
(v
)
1580 var mtype
: nullable MType = null
1581 var ntype
= self.n_type
1582 if ntype
!= null then
1583 mtype
= v
.resolve_mtype
(ntype
)
1584 if mtype
== null then return # Skip error
1586 var mtypes
= new Array[nullable MType]
1588 for e
in self.n_exprs
do
1589 var t
= v
.visit_expr
(e
)
1593 set_comprehension
(e
)
1594 if mtype
!= null then
1595 if v
.check_subtype
(e
, t
, mtype
, false) == null then return # Forward error
1596 if t
== mtype
then useless
= true
1601 if mtype
== null then
1602 # Ensure monotony for type adaptation on loops
1603 if self.element_mtype
!= null then mtypes
.add
self.element_mtype
1604 mtype
= v
.merge_types
(self, mtypes
)
1606 if mtype
== null or mtype
isa MNullType then
1607 v
.error
(self, "Type Error: ambiguous array type {mtypes.join(" ")}")
1611 assert ntype
!= null
1612 v
.modelbuilder
.warning
(ntype
, "useless-type", "Warning: useless type declaration `{mtype}` in literal Array since it can be inferred from the elements type.")
1615 self.element_mtype
= mtype
1617 var mclass
= v
.get_mclass
(self, "Array")
1618 if mclass
== null then return # Forward error
1619 var array_mtype
= mclass
.get_mtype
([mtype
])
1621 with_capacity_callsite
= v
.get_method
(self, array_mtype
, "with_capacity", false)
1622 push_callsite
= v
.get_method
(self, array_mtype
, "push", false)
1624 self.mtype
= array_mtype
1628 redef class ARangeExpr
1629 var init_callsite
: nullable CallSite
1631 redef fun accept_typing
(v
)
1633 var discrete_class
= v
.get_mclass
(self, "Discrete")
1634 if discrete_class
== null then return # Forward error
1635 var discrete_type
= discrete_class
.intro
.bound_mtype
1636 var t1
= v
.visit_expr_subtype
(self.n_expr
, discrete_type
)
1637 var t2
= v
.visit_expr_subtype
(self.n_expr2
, discrete_type
)
1638 if t1
== null or t2
== null then return
1639 var mclass
= v
.get_mclass
(self, "Range")
1640 if mclass
== null then return # Forward error
1642 if v
.is_subtype
(t1
, t2
) then
1643 mtype
= mclass
.get_mtype
([t2
])
1644 else if v
.is_subtype
(t2
, t1
) then
1645 mtype
= mclass
.get_mtype
([t1
])
1647 v
.error
(self, "Type Error: cannot create range: `{t1}` vs `{t2}`.")
1653 # get the constructor
1655 if self isa ACrangeExpr then
1656 callsite
= v
.get_method
(self, mtype
, "init", false)
1657 else if self isa AOrangeExpr then
1658 callsite
= v
.get_method
(self, mtype
, "without_last", false)
1662 init_callsite
= callsite
1666 redef class ANullExpr
1667 redef fun accept_typing
(v
)
1669 self.mtype
= v
.mmodule
.model
.null_type
1673 redef class AIsaExpr
1674 # The static type to cast to.
1675 # (different from the static type of the expression that is `Bool`).
1676 var cast_type
: nullable MType
1677 redef fun accept_typing
(v
)
1679 v
.visit_expr
(n_expr
)
1681 var mtype
= v
.resolve_mtype
(n_type
)
1683 self.cast_type
= mtype
1685 var variable
= self.n_expr
.its_variable
1686 if variable
!= null then
1687 var orig
= self.n_expr
.mtype
1688 #var from = if orig != null then orig.to_s else "invalid"
1689 #var to = if mtype != null then mtype.to_s else "invalid"
1690 #debug("adapt {variable}: {from} -> {to}")
1692 # Do not adapt if there is no information gain (i.e. adapt to a supertype)
1693 if mtype
== null or orig
== null or not v
.is_subtype
(orig
, mtype
) then
1694 self.after_flow_context
.when_true
.set_var
(v
, variable
, mtype
)
1698 self.mtype
= v
.type_bool
(self)
1701 redef fun accept_post_typing
(v
)
1703 v
.check_expr_cast
(self, self.n_expr
, self.n_type
)
1706 redef fun dump_info
(v
) do
1708 var mtype
= self.cast_type
1709 if mtype
!= null then
1710 res
+= v
.yellow
(".as({mtype})")
1717 redef class AAsCastExpr
1718 redef fun accept_typing
(v
)
1720 v
.visit_expr
(n_expr
)
1722 self.mtype
= v
.resolve_mtype
(n_type
)
1725 redef fun accept_post_typing
(v
)
1727 v
.check_expr_cast
(self, self.n_expr
, self.n_type
)
1731 redef class AAsNotnullExpr
1732 redef fun accept_typing
(v
)
1734 var mtype
= v
.visit_expr
(self.n_expr
)
1735 if mtype
== null then return # Forward error
1737 if mtype
isa MNullType then
1738 v
.error
(self, "Type Error: `as(not null)` on `null`.")
1742 if v
.can_be_null
(mtype
) then
1743 mtype
= mtype
.as_notnull
1749 redef fun accept_post_typing
(v
)
1751 var mtype
= n_expr
.mtype
1752 if mtype
== null then return
1753 v
.check_can_be_null
(n_expr
, mtype
)
1757 redef class AParExpr
1758 redef fun accept_typing
(v
)
1760 self.mtype
= v
.visit_expr
(self.n_expr
)
1764 redef class AOnceExpr
1765 redef fun accept_typing
(v
)
1767 self.mtype
= v
.visit_expr
(self.n_expr
)
1771 redef class ASelfExpr
1772 redef var its_variable
: nullable Variable
1773 redef fun accept_typing
(v
)
1775 if v
.is_toplevel_context
and not self isa AImplicitSelfExpr then
1776 v
.error
(self, "Error: `self` cannot be used in top-level method.")
1778 var variable
= v
.selfvariable
1779 self.its_variable
= variable
1780 self.mtype
= v
.get_variable
(self, variable
)
1784 redef class AImplicitSelfExpr
1785 # Is the implicit receiver `sys`?
1787 # By default, the implicit receiver is `self`.
1788 # But when there is not method for `self`, `sys` is used as a fall-back.
1789 # Is this case this flag is set to `true`.
1793 ## MESSAGE SENDING AND PROPERTY
1795 redef class ASendExpr
1796 # The property invoked by the send.
1797 var callsite
: nullable CallSite
1799 redef fun bad_expr_message
(child
)
1801 if child
== self.n_expr
then
1802 return "to be the receiver of `{self.property_name}`"
1807 redef fun accept_typing
(v
)
1809 var nrecv
= self.n_expr
1810 var recvtype
= v
.visit_expr
(nrecv
)
1811 var name
= self.property_name
1812 var node
= self.property_node
1814 if recvtype
== null then return # Forward error
1817 var unsafe_type
= v
.anchor_to
(recvtype
)
1818 var mproperty
= v
.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
1819 if mproperty
== null and nrecv
isa AImplicitSelfExpr then
1820 # Special fall-back search in `sys` when noting found in the implicit receiver.
1821 var sysclass
= v
.try_get_mclass
(node
, "Sys")
1822 if sysclass
!= null then
1823 var systype
= sysclass
.mclass_type
1824 mproperty
= v
.try_get_mproperty_by_name2
(node
, systype
, name
)
1825 if mproperty
!= null then
1826 callsite
= v
.get_method
(node
, systype
, name
, false)
1827 if callsite
== null then return # Forward error
1828 # Update information, we are looking at `sys` now, not `self`
1830 nrecv
.its_variable
= null
1831 nrecv
.mtype
= systype
1836 if callsite
== null then
1837 # If still nothing, just exit
1838 callsite
= v
.get_method
(node
, recvtype
, name
, nrecv
isa ASelfExpr)
1839 if callsite
== null then return
1842 self.callsite
= callsite
1843 var msignature
= callsite
.msignature
1845 var args
= compute_raw_arguments
1847 callsite
.check_signature
(v
, node
, args
)
1849 if callsite
.mproperty
.is_init
then
1850 var vmpropdef
= v
.mpropdef
1851 if not (vmpropdef
isa MMethodDef and vmpropdef
.mproperty
.is_init
) then
1852 v
.error
(node
, "Error: an `init` can only be called from another `init`.")
1854 if vmpropdef
isa MMethodDef and vmpropdef
.mproperty
.is_root_init
and not callsite
.mproperty
.is_root_init
then
1855 v
.error
(node
, "Error: `{vmpropdef}` cannot call a factory `{callsite.mproperty}`.")
1859 var ret
= msignature
.return_mtype
1863 self.is_typed
= true
1867 # The name of the property
1868 # Each subclass simply provide the correct name.
1869 private fun property_name
: String is abstract
1871 # The node identifying the name (id, operator, etc) for messages.
1873 # Is `self` by default
1874 private fun property_node
: ANode do return self
1876 # An array of all arguments (excluding self)
1877 fun raw_arguments
: Array[AExpr] do return compute_raw_arguments
1879 private fun compute_raw_arguments
: Array[AExpr] is abstract
1881 redef fun dump_info
(v
) do
1883 var callsite
= self.callsite
1884 if callsite
!= null then
1885 res
+= v
.yellow
(" call="+callsite
.dump_info
(v
))
1891 redef class ABinopExpr
1892 redef fun compute_raw_arguments
do return [n_expr2
]
1893 redef fun property_name
do return operator
1894 redef fun property_node
do return n_op
1897 redef class AEqFormExpr
1898 redef fun accept_typing
(v
)
1904 redef fun accept_post_typing
(v
)
1906 var mtype
= n_expr
.mtype
1907 var mtype2
= n_expr2
.mtype
1909 if mtype
== null or mtype2
== null then return
1911 if not mtype2
isa MNullType then return
1913 v
.check_can_be_null
(n_expr
, mtype
)
1917 redef class AUnaryopExpr
1918 redef fun property_name
do return "unary {operator}"
1919 redef fun compute_raw_arguments
do return new Array[AExpr]
1923 redef class ACallExpr
1924 redef fun property_name
do return n_qid
.n_id
.text
1925 redef fun property_node
do return n_qid
1926 redef fun compute_raw_arguments
do return n_args
.to_a
1929 redef class ACallAssignExpr
1930 redef fun property_name
do return n_qid
.n_id
.text
+ "="
1931 redef fun property_node
do return n_qid
1932 redef fun compute_raw_arguments
1934 var res
= n_args
.to_a
1940 redef class ABraExpr
1941 redef fun property_name
do return "[]"
1942 redef fun compute_raw_arguments
do return n_args
.to_a
1945 redef class ABraAssignExpr
1946 redef fun property_name
do return "[]="
1947 redef fun compute_raw_arguments
1949 var res
= n_args
.to_a
1955 redef class ASendReassignFormExpr
1956 # The property invoked for the writing
1957 var write_callsite
: nullable CallSite
1959 redef fun accept_typing
(v
)
1961 var recvtype
= v
.visit_expr
(self.n_expr
)
1962 var name
= self.property_name
1963 var node
= self.property_node
1965 if recvtype
== null then return # Forward error
1967 var for_self
= self.n_expr
isa ASelfExpr
1968 var callsite
= v
.get_method
(node
, recvtype
, name
, for_self
)
1970 if callsite
== null then return
1971 self.callsite
= callsite
1973 var args
= compute_raw_arguments
1975 callsite
.check_signature
(v
, node
, args
)
1977 var readtype
= callsite
.msignature
.return_mtype
1978 if readtype
== null then
1979 v
.error
(node
, "Error: `{name}` is not a function.")
1983 var wcallsite
= v
.get_method
(node
, recvtype
, name
+ "=", self.n_expr
isa ASelfExpr)
1984 if wcallsite
== null then return
1985 self.write_callsite
= wcallsite
1987 var wtype
= self.resolve_reassignment
(v
, readtype
, wcallsite
.msignature
.mparameters
.last
.mtype
)
1988 if wtype
== null then return
1990 args
= args
.to_a
# duplicate so raw_arguments keeps only the getter args
1991 args
.add
(self.n_value
)
1992 wcallsite
.check_signature
(v
, node
, args
)
1994 self.is_typed
= true
1998 redef class ACallReassignExpr
1999 redef fun property_name
do return n_qid
.n_id
.text
2000 redef fun property_node
do return n_qid
.n_id
2001 redef fun compute_raw_arguments
do return n_args
.to_a
2004 redef class ABraReassignExpr
2005 redef fun property_name
do return "[]"
2006 redef fun compute_raw_arguments
do return n_args
.to_a
2009 redef class AInitExpr
2010 redef fun property_name
do return "init"
2011 redef fun property_node
do return n_kwinit
2012 redef fun compute_raw_arguments
do return n_args
.to_a
2016 fun to_a
: Array[AExpr] do return self.n_exprs
.to_a
2021 redef class ASuperExpr
2022 # The method to call if the super is in fact a 'super init call'
2023 # Note: if the super is a normal call-next-method, then this attribute is null
2024 var callsite
: nullable CallSite
2026 # The method to call is the super is a standard `call-next-method` super-call
2027 # Note: if the super is a special super-init-call, then this attribute is null
2028 var mpropdef
: nullable MMethodDef
2030 redef fun accept_typing
(v
)
2032 var anchor
= v
.anchor
2033 assert anchor
!= null
2034 var recvtype
= v
.get_variable
(self, v
.selfvariable
)
2035 assert recvtype
!= null
2036 var mproperty
= v
.mpropdef
.mproperty
2037 if not mproperty
isa MMethod then
2038 v
.error
(self, "Error: `super` only usable in a `method`.")
2041 var superprops
= mproperty
.lookup_super_definitions
(v
.mmodule
, anchor
)
2042 if superprops
.length
== 0 then
2043 if mproperty
.is_init
and v
.mpropdef
.is_intro
then
2044 process_superinit
(v
)
2047 v
.error
(self, "Error: no super method to call for `{mproperty}`.")
2050 # FIXME: covariance of return type in linear extension?
2051 var superprop
= superprops
.first
2053 var msignature
= superprop
.msignature
.as(not null)
2054 msignature
= v
.resolve_for
(msignature
, recvtype
, true).as(MSignature)
2055 var args
= self.n_args
.to_a
2056 if args
.length
> 0 then
2057 signaturemap
= v
.check_signature
(self, args
, mproperty
, msignature
)
2059 self.mtype
= msignature
.return_mtype
2060 self.is_typed
= true
2061 v
.mpropdef
.has_supercall
= true
2062 mpropdef
= v
.mpropdef
.as(MMethodDef)
2065 # The mapping used on the call to associate arguments to parameters.
2066 # If null then no specific association is required.
2067 var signaturemap
: nullable SignatureMap
2069 private fun process_superinit
(v
: TypeVisitor)
2071 var anchor
= v
.anchor
2072 assert anchor
!= null
2073 var recvtype
= v
.get_variable
(self, v
.selfvariable
)
2074 assert recvtype
!= null
2075 var mpropdef
= v
.mpropdef
2076 assert mpropdef
isa MMethodDef
2077 var mproperty
= mpropdef
.mproperty
2078 var superprop
: nullable MMethodDef = null
2079 for msupertype
in mpropdef
.mclassdef
.supertypes
do
2080 msupertype
= msupertype
.anchor_to
(v
.mmodule
, anchor
)
2081 var errcount
= v
.modelbuilder
.toolcontext
.error_count
2082 var candidate
= v
.try_get_mproperty_by_name2
(self, msupertype
, mproperty
.name
).as(nullable MMethod)
2083 if candidate
== null then
2084 if v
.modelbuilder
.toolcontext
.error_count
> errcount
then return # Forward error
2085 continue # Try next super-class
2087 if superprop
!= null and candidate
.is_root_init
then
2090 if superprop
!= null and superprop
.mproperty
!= candidate
and not superprop
.mproperty
.is_root_init
then
2091 v
.error
(self, "Error: conflicting super constructor to call for `{mproperty}`: `{candidate.full_name}`, `{superprop.mproperty.full_name}`")
2094 var candidatedefs
= candidate
.lookup_definitions
(v
.mmodule
, anchor
)
2095 if superprop
!= null and superprop
.mproperty
== candidate
then
2096 if superprop
== candidatedefs
.first
then continue
2097 candidatedefs
.add
(superprop
)
2099 if candidatedefs
.length
> 1 then
2100 v
.error
(self, "Error: conflicting property definitions for property `{mproperty}` in `{recvtype}`: {candidatedefs.join(", ")}")
2103 superprop
= candidatedefs
.first
2105 if superprop
== null then
2106 v
.error
(self, "Error: no super method to call for `{mproperty}`.")
2110 var msignature
= superprop
.new_msignature
or else superprop
.msignature
.as(not null)
2111 msignature
= v
.resolve_for
(msignature
, recvtype
, true).as(MSignature)
2113 var callsite
= new CallSite(hot_location
, recvtype
, v
.mmodule
, v
.anchor
, true, superprop
.mproperty
, superprop
, msignature
, false)
2114 self.callsite
= callsite
2116 var args
= self.n_args
.to_a
2117 if args
.length
> 0 then
2118 callsite
.check_signature
(v
, self, args
)
2120 # Check there is at least enough parameters
2121 if mpropdef
.msignature
.arity
< msignature
.arity
then
2122 v
.error
(self, "Error: not enough implicit arguments to pass. Got `{mpropdef.msignature.arity}`, expected at least `{msignature.arity}`. Signature is `{msignature}`.")
2125 # Check that each needed parameter is conform
2127 for sp
in msignature
.mparameters
do
2128 var p
= mpropdef
.msignature
.mparameters
[i
]
2129 if not v
.is_subtype
(p
.mtype
, sp
.mtype
) then
2130 v
.error
(self, "Type Error: expected argument #{i} of type `{sp.mtype}`, got implicit argument `{p.name}` of type `{p.mtype}`. Signature is {msignature}")
2137 self.is_typed
= true
2140 redef fun dump_info
(v
) do
2142 var callsite
= self.callsite
2143 if callsite
!= null then
2144 res
+= v
.yellow
(" super-init="+callsite
.dump_info
(v
))
2146 var mpropdef
= self.mpropdef
2147 if mpropdef
!= null then
2148 res
+= v
.yellow
(" call-next-method="+mpropdef
.to_s
)
2156 redef class ANewExpr
2157 # The constructor invoked by the new.
2158 var callsite
: nullable CallSite
2160 # The designated type
2161 var recvtype
: nullable MClassType
2163 redef fun accept_typing
(v
)
2165 var recvtype
= v
.resolve_mtype
(self.n_type
)
2166 if recvtype
== null then return
2168 if not recvtype
isa MClassType then
2169 if recvtype
isa MNullableType then
2170 v
.error
(self, "Type Error: cannot instantiate the nullable type `{recvtype}`.")
2172 else if recvtype
isa MFormalType then
2173 v
.error
(self, "Type Error: cannot instantiate the formal type `{recvtype}`.")
2176 v
.error
(self, "Type Error: cannot instantiate the type `{recvtype}`.")
2181 self.recvtype
= recvtype
2182 var kind
= recvtype
.mclass
.kind
2185 var nqid
= self.n_qid
2187 if nqid
!= null then
2188 name
= nqid
.n_id
.text
2194 if name
== "intern" then
2195 if kind
!= concrete_kind
then
2196 v
.error
(self, "Type Error: cannot instantiate {kind} {recvtype}.")
2199 if n_args
.n_exprs
.not_empty
then
2200 v
.error
(n_args
, "Type Error: the intern constructor expects no arguments.")
2204 self.mtype
= recvtype
2208 var callsite
= v
.get_method
(node
, recvtype
, name
, false)
2209 if callsite
== null then return
2211 if not callsite
.mproperty
.is_new
then
2212 if kind
!= concrete_kind
then
2213 v
.error
(self, "Type Error: cannot instantiate {kind} `{recvtype}`.")
2216 self.mtype
= recvtype
2218 self.mtype
= callsite
.msignature
.return_mtype
2219 assert self.mtype
!= null
2222 self.callsite
= callsite
2224 if not callsite
.mproperty
.is_init_for
(recvtype
.mclass
) then
2225 v
.error
(self, "Error: `{name}` is not a constructor.")
2229 var args
= n_args
.to_a
2230 callsite
.check_signature
(v
, node
, args
)
2233 redef fun dump_info
(v
) do
2235 var callsite
= self.callsite
2236 if callsite
!= null then
2237 res
+= v
.yellow
(" call="+callsite
.dump_info
(v
))
2245 redef class AAttrFormExpr
2246 # The attribute accessed.
2247 var mproperty
: nullable MAttribute
2249 # The static type of the attribute.
2250 var attr_type
: nullable MType
2252 # Resolve the attribute accessed.
2253 private fun resolve_property
(v
: TypeVisitor)
2255 var recvtype
= v
.visit_expr
(self.n_expr
)
2256 if recvtype
== null then return # Skip error
2257 var node
= self.n_id
2258 var name
= node
.text
2259 if recvtype
isa MNullType then
2260 v
.error
(node
, "Error: attribute `{name}` access on `null`.")
2264 var unsafe_type
= v
.anchor_to
(recvtype
)
2265 var mproperty
= v
.try_get_mproperty_by_name2
(node
, unsafe_type
, name
)
2266 if mproperty
== null then
2267 v
.modelbuilder
.error
(node
, "Error: attribute `{name}` does not exist in `{recvtype}`.")
2270 assert mproperty
isa MAttribute
2271 self.mproperty
= mproperty
2273 var mpropdefs
= mproperty
.lookup_definitions
(v
.mmodule
, unsafe_type
)
2274 assert mpropdefs
.length
== 1
2275 var mpropdef
= mpropdefs
.first
2276 var attr_type
= mpropdef
.static_mtype
2277 if attr_type
== null then return # skip error
2278 attr_type
= v
.resolve_for
(attr_type
, recvtype
, self.n_expr
isa ASelfExpr)
2279 self.attr_type
= attr_type
2282 redef fun dump_info
(v
) do
2284 var mproperty
= self.mproperty
2285 var attr_type
= self.attr_type
2286 if mproperty
!= null then
2287 res
+= v
.yellow
(" attr={mproperty}:{attr_type or else "BROKEN"}")
2293 redef class AAttrExpr
2294 redef fun accept_typing
(v
)
2296 self.resolve_property
(v
)
2297 self.mtype
= self.attr_type
2302 redef class AAttrAssignExpr
2303 redef fun accept_typing
(v
)
2305 self.resolve_property
(v
)
2306 var mtype
= self.attr_type
2308 v
.visit_expr_subtype
(self.n_value
, mtype
)
2309 self.is_typed
= mtype
!= null
2313 redef class AAttrReassignExpr
2314 redef fun accept_typing
(v
)
2316 self.resolve_property
(v
)
2317 var mtype
= self.attr_type
2318 if mtype
== null then return # Skip error
2320 var rettype
= self.resolve_reassignment
(v
, mtype
, mtype
)
2322 self.is_typed
= rettype
!= null
2326 redef class AIssetAttrExpr
2327 redef fun accept_typing
(v
)
2329 self.resolve_property
(v
)
2330 var mtype
= self.attr_type
2331 if mtype
== null then return # Skip error
2333 var recvtype
= self.n_expr
.mtype
.as(not null)
2334 var bound
= v
.resolve_for
(mtype
, recvtype
, false)
2335 if bound
isa MNullableType then
2336 v
.error
(n_id
, "Type Error: `isset` on a nullable attribute.")
2338 self.mtype
= v
.type_bool
(self)
2342 redef class AVarargExpr
2343 redef fun accept_typing
(v
)
2345 # This kind of pseudo-expression can be only processed trough a signature
2346 # See `check_signature`
2347 # Other cases are a syntax error.
2348 v
.error
(self, "Syntax Error: unexpected `...`.")
2354 redef class ADebugTypeExpr
2355 redef fun accept_typing
(v
)
2357 var expr
= v
.visit_expr
(self.n_expr
)
2358 if expr
== null then return
2359 var unsafe
= v
.anchor_to
(expr
)
2360 var ntype
= self.n_type
2361 var mtype
= v
.resolve_mtype
(ntype
)
2362 if mtype
!= null and mtype
!= expr
then
2363 var umtype
= v
.anchor_to
(mtype
)
2364 v
.modelbuilder
.warning
(self, "debug", "Found type {expr} (-> {unsafe}), expected {mtype} (-> {umtype})")
2366 self.is_typed
= true