typing: process named arguments
[nit.git] / src / semantize / typing.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2012 Jean Privat <jean@pryen.org>
4 #
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
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
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.
16
17 # Intraprocedural resolution of static types and OO-services
18 # By OO-services we mean message sending, attribute access, instantiation, etc.
19 module typing
20
21 import modelize
22 import local_var_init
23
24 redef class ToolContext
25 var typing_phase: Phase = new TypingPhase(self, [flow_phase, modelize_property_phase, local_var_init_phase])
26 end
27
28 private class TypingPhase
29 super Phase
30 redef fun process_npropdef(npropdef) do npropdef.do_typing(toolcontext.modelbuilder)
31 end
32
33 private class TypeVisitor
34 var modelbuilder: ModelBuilder
35
36 # The module of the analysis
37 # Used to correctly query the model
38 var mmodule: MModule
39
40 # The static type of the receiver
41 # Mainly used for type tests and type resolutions
42 var anchor: nullable MClassType = null
43
44 # The analyzed mclassdef
45 var mclassdef: nullable MClassDef = null
46
47 # The analyzed property
48 var mpropdef: nullable MPropDef
49
50 var selfvariable = new Variable("self")
51
52 # Is `self` use restricted?
53 # * no explicit `self`
54 # * method called on the implicit self must be top-level
55 # Currently only used for `new` factory since there is no valid receiver inside
56 var is_toplevel_context = false
57
58 init
59 do
60 var mpropdef = self.mpropdef
61
62 if mpropdef != null then
63 self.mpropdef = mpropdef
64 var mclassdef = mpropdef.mclassdef
65 self.mclassdef = mclassdef
66 self.anchor = mclassdef.bound_mtype
67
68 var mclass = mclassdef.mclass
69
70 var selfvariable = new Variable("self")
71 self.selfvariable = selfvariable
72 selfvariable.declared_type = mclass.mclass_type
73
74 var mprop = mpropdef.mproperty
75 if mprop isa MMethod and mprop.is_new then
76 is_toplevel_context = true
77 end
78 end
79 end
80
81 fun anchor_to(mtype: MType): MType
82 do
83 var anchor = anchor
84 if anchor == null then
85 assert not mtype.need_anchor
86 return mtype
87 end
88 return mtype.anchor_to(mmodule, anchor)
89 end
90
91 fun is_subtype(sub, sup: MType): Bool
92 do
93 return sub.is_subtype(mmodule, anchor, sup)
94 end
95
96 fun resolve_for(mtype, subtype: MType, for_self: Bool): MType
97 do
98 #print "resolve_for {mtype} sub={subtype} forself={for_self} mmodule={mmodule} anchor={anchor}"
99 var res = mtype.resolve_for(subtype, anchor, mmodule, not for_self)
100 return res
101 end
102
103 # Check that `sub` is a subtype of `sup`.
104 # If `sub` is not a valid suptype, then display an error on `node` an return null.
105 # If `sub` is a safe subtype of `sup` then return `sub`.
106 # If `sub` is an unsafe subtype (ie an implicit cast is required), then return `sup`.
107 #
108 # The point of the return type is to determinate the usable type on an expression when `autocast` is true:
109 # If the suptype is safe, then the return type is the one on the expression typed by `sub`.
110 # Is the subtype is unsafe, then the return type is the one of an implicit cast on `sup`.
111 fun check_subtype(node: ANode, sub, sup: MType, autocast: Bool): nullable MType
112 do
113 if self.is_subtype(sub, sup) then return sub
114 if autocast and self.is_subtype(sub, self.anchor_to(sup)) then
115 # FIXME workaround to the current unsafe typing policy. To remove once fixed virtual types exists.
116 #node.debug("Unsafe typing: expected {sup}, got {sub}")
117 return sup
118 end
119 if sub.need_anchor then
120 var u = anchor_to(sub)
121 self.modelbuilder.error(node, "Type Error: expected `{sup}`, got `{sub}: {u}`.")
122 else
123 self.modelbuilder.error(node, "Type Error: expected `{sup}`, got `{sub}`.")
124 end
125 return null
126 end
127
128 # Visit an expression and do not care about the return value
129 fun visit_stmt(nexpr: nullable AExpr)
130 do
131 if nexpr == null then return
132 nexpr.accept_typing(self)
133 end
134
135 # Visit an expression and expects that it is not a statement
136 # Return the type of the expression
137 # Display an error and return null if:
138 # * the type cannot be determined or
139 # * `nexpr` is a statement
140 fun visit_expr(nexpr: AExpr): nullable MType
141 do
142 nexpr.accept_typing(self)
143 var mtype = nexpr.mtype
144 if mtype != null then return mtype
145 if not nexpr.is_typed then
146 if not self.modelbuilder.toolcontext.error_count > 0 then # check that there is really an error
147 if self.modelbuilder.toolcontext.verbose_level > 1 then
148 nexpr.debug("No return type but no error.")
149 end
150 end
151 return null # forward error
152 end
153 self.error(nexpr, "Error: expected an expression.")
154 return null
155 end
156
157 # Visit an expression and expect its static type is a least a `sup`
158 # Return the type of the expression or null if
159 # * the type cannot be determined or
160 # * `nexpr` is a statement or
161 # * `nexpr` is not a `sup`
162 fun visit_expr_subtype(nexpr: AExpr, sup: nullable MType): nullable MType
163 do
164 var sub = visit_expr(nexpr)
165 if sub == null then return null # Forward error
166
167 if sup == null then return null # Forward error
168
169 var res = check_subtype(nexpr, sub, sup, true)
170 if res != sub then
171 nexpr.implicit_cast_to = res
172 end
173 return res
174 end
175
176 # Visit an expression and expect its static type is a `Bool`
177 # Return the type of the expression or null if
178 # * the type cannot be determined or
179 # * `nexpr` is a statement or
180 # * `nexpr` is not a `Bool`
181 fun visit_expr_bool(nexpr: AExpr): nullable MType
182 do
183 return self.visit_expr_subtype(nexpr, self.type_bool(nexpr))
184 end
185
186
187 fun visit_expr_cast(node: ANode, nexpr: AExpr, ntype: AType): nullable MType
188 do
189 var sub = visit_expr(nexpr)
190 if sub == null then return null # Forward error
191
192 var sup = self.resolve_mtype(ntype)
193 if sup == null then return null # Forward error
194
195 if sup == sub then
196 self.modelbuilder.warning(node, "useless-type-test", "Warning: expression is already a `{sup}`.")
197 else if self.is_subtype(sub, sup) then
198 self.modelbuilder.warning(node, "useless-type-test", "Warning: expression is already a `{sup}` since it is a `{sub}`.")
199 end
200 return sup
201 end
202
203 # Can `mtype` be null (up to the current knowledge)?
204 fun can_be_null(mtype: MType): Bool
205 do
206 if mtype isa MNullableType or mtype isa MNullType then return true
207 if mtype isa MFormalType then
208 var x = anchor_to(mtype)
209 if x isa MNullableType or x isa MNullType then return true
210 end
211 return false
212 end
213
214 # Check that `mtype` can be null (up to the current knowledge).
215 #
216 # If not then display a `useless-null-test` warning on node and return false.
217 # Else return true.
218 fun check_can_be_null(anode: ANode, mtype: MType): Bool
219 do
220 if can_be_null(mtype) then return true
221
222 if mtype isa MFormalType then
223 var res = anchor_to(mtype)
224 modelbuilder.warning(anode, "useless-null-test", "Warning: expression is not null, since it is a `{mtype}: {res}`.")
225 else
226 modelbuilder.warning(anode, "useless-null-test", "Warning: expression is not null, since it is a `{mtype}`.")
227 end
228 return false
229 end
230
231 # Special verification on != and == for null
232 # Return true
233 fun null_test(anode: ABinopExpr)
234 do
235 var mtype = anode.n_expr.mtype
236 var mtype2 = anode.n_expr2.mtype
237
238 if mtype == null or mtype2 == null then return
239
240 if not mtype2 isa MNullType then return
241
242 # Check of useless null
243 if not check_can_be_null(anode.n_expr, mtype) then return
244
245 if mtype isa MNullType then
246 # Because of type adaptation, we cannot just stop here
247 # so return use `null` as a bottom type that will be merged easily (cf) `merge_types`
248 mtype = null
249 else
250 mtype = mtype.as_notnull
251 end
252
253 # Check for type adaptation
254 var variable = anode.n_expr.its_variable
255 if variable == null then return
256
257 # One is null (mtype2 see above) the other is not null
258 if anode isa AEqExpr then
259 anode.after_flow_context.when_true.set_var(self, variable, mtype2)
260 anode.after_flow_context.when_false.set_var(self, variable, mtype)
261 else if anode isa ANeExpr then
262 anode.after_flow_context.when_false.set_var(self, variable, mtype2)
263 anode.after_flow_context.when_true.set_var(self, variable, mtype)
264 else
265 abort
266 end
267 end
268
269 fun try_get_mproperty_by_name2(anode: ANode, mtype: MType, name: String): nullable MProperty
270 do
271 return self.modelbuilder.try_get_mproperty_by_name2(anode, mmodule, mtype, name)
272 end
273
274 fun resolve_mtype(node: AType): nullable MType
275 do
276 return self.modelbuilder.resolve_mtype(mmodule, mclassdef, node)
277 end
278
279 fun try_get_mclass(node: ANode, name: String): nullable MClass
280 do
281 var mclass = modelbuilder.try_get_mclass_by_name(node, mmodule, name)
282 return mclass
283 end
284
285 fun get_mclass(node: ANode, name: String): nullable MClass
286 do
287 var mclass = modelbuilder.get_mclass_by_name(node, mmodule, name)
288 return mclass
289 end
290
291 fun type_bool(node: ANode): nullable MType
292 do
293 var mclass = self.get_mclass(node, "Bool")
294 if mclass == null then return null
295 return mclass.mclass_type
296 end
297
298 fun get_method(node: ANode, recvtype: MType, name: String, recv_is_self: Bool): nullable CallSite
299 do
300 var unsafe_type = self.anchor_to(recvtype)
301
302 #debug("recv: {recvtype} (aka {unsafe_type})")
303 if recvtype isa MNullType then
304 # `null` only accepts some methods of object.
305 if name == "==" or name == "!=" or name == "is_same_instance" then
306 var objclass = get_mclass(node, "Object")
307 if objclass == null then return null # Forward error
308 unsafe_type = objclass.mclass_type
309 else
310 self.error(node, "Error: method `{name}` called on `null`.")
311 return null
312 end
313 end
314
315 var mproperty = self.try_get_mproperty_by_name2(node, unsafe_type, name)
316 if name == "new" and mproperty == null then
317 name = "init"
318 mproperty = self.try_get_mproperty_by_name2(node, unsafe_type, name)
319 end
320
321 if mproperty == null then
322 if recv_is_self then
323 self.modelbuilder.error(node, "Error: method or variable `{name}` unknown in `{recvtype}`.")
324 else if recvtype.need_anchor then
325 self.modelbuilder.error(node, "Error: method `{name}` does not exists in `{recvtype}: {unsafe_type}`.")
326 else
327 self.modelbuilder.error(node, "Error: method `{name}` does not exists in `{recvtype}`.")
328 end
329 return null
330 end
331
332 assert mproperty isa MMethod
333
334 if is_toplevel_context and recv_is_self and not mproperty.is_toplevel then
335 error(node, "Error: `{name}` is not a top-level method, thus need a receiver.")
336 end
337 if not recv_is_self and mproperty.is_toplevel then
338 error(node, "Error: cannot call `{name}`, a top-level method, with a receiver.")
339 end
340
341 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
342 self.modelbuilder.error(node, "Error: method `{name}` is protected and can only accessed by `self`.")
343 return null
344 end
345
346 var info = mproperty.deprecation
347 if info != null and self.mpropdef.mproperty.deprecation == null then
348 var mdoc = info.mdoc
349 if mdoc != null then
350 self.modelbuilder.warning(node, "deprecated-method", "Deprecation Warning: method `{name}` is deprecated: {mdoc.content.first}")
351 else
352 self.modelbuilder.warning(node, "deprecated-method", "Deprecation Warning: method `{name}` is deprecated.")
353 end
354 end
355
356 var propdefs = mproperty.lookup_definitions(self.mmodule, unsafe_type)
357 var mpropdef
358 if propdefs.length == 0 then
359 self.modelbuilder.error(node, "Type Error: no definition found for property `{name}` in `{unsafe_type}`.")
360 return null
361 else if propdefs.length == 1 then
362 mpropdef = propdefs.first
363 else
364 self.modelbuilder.warning(node, "property-conflict", "Warning: conflicting property definitions for property `{name}` in `{unsafe_type}`: {propdefs.join(" ")}")
365 mpropdef = mproperty.intro
366 end
367
368
369 var msignature = mpropdef.new_msignature or else mpropdef.msignature
370 if msignature == null then return null # skip error
371 msignature = resolve_for(msignature, recvtype, recv_is_self).as(MSignature)
372
373 var erasure_cast = false
374 var rettype = mpropdef.msignature.return_mtype
375 if not recv_is_self and rettype != null then
376 rettype = rettype.undecorate
377 if rettype isa MParameterType then
378 var erased_rettype = msignature.return_mtype
379 assert erased_rettype != null
380 #node.debug("Erasure cast: Really a {rettype} but unsafely a {erased_rettype}")
381 erasure_cast = true
382 end
383 end
384
385 var callsite = new CallSite(node, recvtype, mmodule, anchor, recv_is_self, mproperty, mpropdef, msignature, erasure_cast)
386 return callsite
387 end
388
389 fun try_get_method(node: ANode, recvtype: MType, name: String, recv_is_self: Bool): nullable CallSite
390 do
391 var unsafe_type = self.anchor_to(recvtype)
392 var mproperty = self.try_get_mproperty_by_name2(node, unsafe_type, name)
393 if mproperty == null then return null
394 return get_method(node, recvtype, name, recv_is_self)
395 end
396
397
398 # Visit the expressions of args and check their conformity with the corresponding type in signature
399 # The point of this method is to handle varargs correctly
400 # Note: The signature must be correctly adapted
401 fun check_signature(node: ANode, args: Array[AExpr], mproperty: MProperty, msignature: MSignature): nullable SignatureMap
402 do
403 var vararg_rank = msignature.vararg_rank
404 if vararg_rank >= 0 then
405 if args.length < msignature.arity then
406 modelbuilder.error(node, "Error: expected at least {msignature.arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
407 return null
408 end
409 else if args.length != msignature.arity then
410 if msignature.arity == msignature.min_arity then
411 modelbuilder.error(node, "Error: expected {msignature.arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
412 return null
413 end
414 if args.length > msignature.arity then
415 modelbuilder.error(node, "Error: expected at most {msignature.arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
416 return null
417 end
418 if args.length < msignature.min_arity then
419 modelbuilder.error(node, "Error: expected at least {msignature.min_arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
420 return null
421 end
422 end
423
424 #debug("CALL {unsafe_type}.{msignature}")
425
426 # Associate each parameter to a position in the arguments
427 var map = new SignatureMap
428
429 var setted = args.length - msignature.min_arity
430
431 # First, handle named arguments
432 for i in [0..args.length[ do
433 var e = args[i]
434 if not e isa ANamedargExpr then continue
435 var name = e.n_id.text
436 var param = msignature.mparameter_by_name(name)
437 if param == null then
438 modelbuilder.error(e.n_id, "Error: no parameter `{name}` for `{mproperty}{msignature}`.")
439 return null
440 end
441 if not param.is_default then
442 modelbuilder.error(e, "Error: parameter `{name}` is not optional for `{mproperty}{msignature}`.")
443 return null
444 end
445 var idx = msignature.mparameters.index_of(param)
446 var prev = map.map.get_or_null(idx)
447 if prev != null then
448 modelbuilder.error(e, "Error: parameter `{name}` already associated with argument #{prev} for `{mproperty}{msignature}`.")
449 return null
450 end
451 map.map[idx] = i
452 setted -= 1
453 e.mtype = self.visit_expr_subtype(e.n_expr, param.mtype)
454 end
455
456 # Second, associate remaining parameters
457 var vararg_decl = args.length - msignature.arity
458 var j = 0
459 for i in [0..msignature.arity[ do
460 # Skip parameters associated by name
461 if map.map.has_key(i) then continue
462
463 var param = msignature.mparameters[i]
464 if param.is_default then
465 if setted > 0 then
466 setted -= 1
467 else
468 continue
469 end
470 end
471
472 # Search the next free argument: skip named arguments since they are already associated
473 while args[j] isa ANamedargExpr do j += 1
474 var arg = args[j]
475 map.map[i] = j
476 j += 1
477
478 if i == vararg_rank then
479 j += vararg_decl
480 continue # skip the vararg
481 end
482
483 var paramtype = param.mtype
484 self.visit_expr_subtype(arg, paramtype)
485 end
486
487 # Third, check varargs
488 if vararg_rank >= 0 then
489 var paramtype = msignature.mparameters[vararg_rank].mtype
490 var first = args[vararg_rank]
491 if vararg_decl == 0 then
492 var mclass = get_mclass(node, "Array")
493 if mclass == null then return null # Forward error
494 var array_mtype = mclass.get_mtype([paramtype])
495 if first isa AVarargExpr then
496 self.visit_expr_subtype(first.n_expr, array_mtype)
497 first.mtype = first.n_expr.mtype
498 else
499 # only one vararg, maybe `...` was forgot, so be gentle!
500 var t = visit_expr(first)
501 if t == null then return null # Forward error
502 if not is_subtype(t, paramtype) and is_subtype(t, array_mtype) then
503 # Not acceptable but could be a `...`
504 error(first, "Type Error: expected `{paramtype}`, got `{t}`. Is an ellipsis `...` missing on the argument?")
505 return null
506 end
507 # Standard valid vararg, finish the job
508 map.vararg_decl = 1
509 self.visit_expr_subtype(first, paramtype)
510 end
511 else
512 map.vararg_decl = vararg_decl + 1
513 for i in [vararg_rank..vararg_rank+vararg_decl] do
514 self.visit_expr_subtype(args[i], paramtype)
515 end
516 end
517 end
518
519 return map
520 end
521
522 fun error(node: ANode, message: String)
523 do
524 self.modelbuilder.toolcontext.error(node.hot_location, message)
525 end
526
527 fun get_variable(node: AExpr, variable: Variable): nullable MType
528 do
529 if not variable.is_adapted then return variable.declared_type
530
531 var flow = node.after_flow_context
532 if flow == null then return null # skip error
533
534 if flow.vars.has_key(variable) then
535 return flow.vars[variable]
536 else
537 #node.debug("*** START Collected for {variable}")
538 var mtypes = flow.collect_types(variable)
539 #node.debug("**** END Collected for {variable}")
540 if mtypes.length == 0 then
541 return variable.declared_type
542 else if mtypes.length == 1 then
543 return mtypes.first
544 else
545 var res = merge_types(node,mtypes)
546 if res == null then res = variable.declared_type
547 return res
548 end
549 end
550 end
551
552 # Some variables where type-adapted during the visit
553 var dirty = false
554
555 # Some loops had been visited during the visit
556 var has_loop = false
557
558 fun set_variable(node: AExpr, variable: Variable, mtype: nullable MType)
559 do
560 var flow = node.after_flow_context
561 assert flow != null
562
563 flow.set_var(self, variable, mtype)
564 end
565
566 fun merge_types(node: ANode, col: Array[nullable MType]): nullable MType
567 do
568 if col.length == 1 then return col.first
569 for t1 in col do
570 if t1 == null then continue # return null
571 var found = true
572 for t2 in col do
573 if t2 == null then continue # return null
574 if can_be_null(t2) and not can_be_null(t1) then
575 t1 = t1.as_nullable
576 end
577 if not is_subtype(t2, t1) then found = false
578 end
579 if found then
580 #print "merge {col.join(" ")} -> {t1}"
581 return t1
582 end
583 end
584 #self.modelbuilder.warning(node, "Type Error: {col.length} conflicting types: <{col.join(", ")}>")
585 return null
586 end
587 end
588
589 # Mapping between parameters and arguments in a call.
590 #
591 # Parameters and arguments are not stored in the class but referenced by their position (starting from 0)
592 #
593 # The point of this class is to help engine and other things to map arguments in the AST to parameters of the model.
594 class SignatureMap
595 # Associate a parameter to an argument
596 var map = new ArrayMap[Int, Int]
597
598 # The length of the vararg sequence
599 # 0 if no vararg or if reverse vararg (cf `AVarargExpr`)
600 var vararg_decl: Int = 0
601 end
602
603 # A specific method call site with its associated informations.
604 class CallSite
605 # The associated node for location
606 var node: ANode
607
608 # The static type of the receiver (possibly unresolved)
609 var recv: MType
610
611 # The module where the callsite is present
612 var mmodule: MModule
613
614 # The anchor to use with `recv` or `msignature`
615 var anchor: nullable MClassType
616
617 # Is the receiver self?
618 # If "for_self", virtual types of the signature are kept
619 # If "not_for_self", virtual type are erased
620 var recv_is_self: Bool
621
622 # The designated method
623 var mproperty: MMethod
624
625 # The statically designated method definition
626 # The most specif one, it is.
627 var mpropdef: MMethodDef
628
629 # The resolved signature for the receiver
630 var msignature: MSignature
631
632 # Is a implicit cast required on erasure typing policy?
633 var erasure_cast: Bool
634
635 # The mapping used on the call to associate arguments to parameters
636 # If null then no specific association is required.
637 var signaturemap: nullable SignatureMap = null
638
639 private fun check_signature(v: TypeVisitor, args: Array[AExpr]): Bool
640 do
641 var map = v.check_signature(self.node, args, self.mproperty, self.msignature)
642 signaturemap = map
643 return map == null
644 end
645 end
646
647 redef class Variable
648 # The declared type of the variable
649 var declared_type: nullable MType
650
651 # Was the variable type-adapted?
652 # This is used to speedup type retrieval while it remains `false`
653 private var is_adapted = false
654 end
655
656 redef class FlowContext
657 # Store changes of types because of type evolution
658 private var vars = new HashMap[Variable, nullable MType]
659
660 # Adapt the variable to a static type
661 # Warning1: do not modify vars directly.
662 # Warning2: sub-flow may have cached a unadapted variable
663 private fun set_var(v: TypeVisitor, variable: Variable, mtype: nullable MType)
664 do
665 if variable.declared_type == mtype and not variable.is_adapted then return
666 if vars.has_key(variable) and vars[variable] == mtype then return
667 self.vars[variable] = mtype
668 v.dirty = true
669 variable.is_adapted = true
670 #node.debug "set {variable} to {mtype or else "X"}"
671 end
672
673 # Look in the flow and previous flow and collect all first reachable type adaptation of a local variable
674 private fun collect_types(variable: Variable): Array[nullable MType]
675 do
676 #node.debug "flow for {variable}"
677 var res = new Array[nullable MType]
678
679 var todo = [self]
680 var seen = new HashSet[FlowContext]
681 while not todo.is_empty do
682 var f = todo.pop
683 if f.is_unreachable then continue
684 if seen.has(f) then continue
685 seen.add f
686
687 if f.vars.has_key(variable) then
688 # Found something. Collect it and do not process further on this path
689 res.add f.vars[variable]
690 #f.node.debug "process {variable}: got {f.vars[variable] or else "X"}"
691 else
692 todo.add_all f.previous
693 todo.add_all f.loops
694 if f.previous.is_empty then
695 # Root flowcontext mean a parameter or something related
696 res.add variable.declared_type
697 #f.node.debug "root process {variable}: got {variable.declared_type or else "X"}"
698 end
699 end
700 end
701 #self.node.debug "##### end flow for {variable}: {res.join(" ")}"
702 return res
703 end
704 end
705
706 redef class APropdef
707 # The entry point of the whole typing analysis
708 fun do_typing(modelbuilder: ModelBuilder)
709 do
710 end
711
712 # The variable associated to the receiver (if any)
713 var selfvariable: nullable Variable
714 end
715
716 redef class AMethPropdef
717 redef fun do_typing(modelbuilder: ModelBuilder)
718 do
719 var nblock = self.n_block
720 if nblock == null then return
721
722 var mpropdef = self.mpropdef
723 if mpropdef == null then return # skip error
724
725 var v = new TypeVisitor(modelbuilder, mpropdef.mclassdef.mmodule, mpropdef)
726 self.selfvariable = v.selfvariable
727
728 var mmethoddef = self.mpropdef.as(not null)
729 var msignature = mmethoddef.msignature
730 if msignature == null then return # skip error
731 for i in [0..msignature.arity[ do
732 var mtype = msignature.mparameters[i].mtype
733 if msignature.vararg_rank == i then
734 var arrayclass = v.get_mclass(self.n_signature.n_params[i], "Array")
735 if arrayclass == null then return # Skip error
736 mtype = arrayclass.get_mtype([mtype])
737 end
738 var variable = self.n_signature.n_params[i].variable
739 assert variable != null
740 variable.declared_type = mtype
741 end
742
743 loop
744 v.dirty = false
745 v.visit_stmt(nblock)
746 if not v.has_loop or not v.dirty then break
747 end
748
749 if not nblock.after_flow_context.is_unreachable and msignature.return_mtype != null then
750 # We reach the end of the function without having a return, it is bad
751 v.error(self, "Error: reached end of function; expected `return` with a value.")
752 end
753 end
754 end
755
756 redef class AAttrPropdef
757 redef fun do_typing(modelbuilder: ModelBuilder)
758 do
759 if not has_value then return
760
761 var mpropdef = self.mpropdef
762 if mpropdef == null then return # skip error
763
764 var v = new TypeVisitor(modelbuilder, mpropdef.mclassdef.mmodule, mpropdef)
765 self.selfvariable = v.selfvariable
766
767 var nexpr = self.n_expr
768 if nexpr != null then
769 var mtype = self.mpropdef.static_mtype
770 v.visit_expr_subtype(nexpr, mtype)
771 end
772 var nblock = self.n_block
773 if nblock != null then
774 v.visit_stmt(nblock)
775 if not nblock.after_flow_context.is_unreachable then
776 # We reach the end of the init without having a return, it is bad
777 v.error(self, "Error: reached end of block; expected `return`.")
778 end
779 end
780 end
781 end
782
783 ###
784
785 redef class AExpr
786 # The static type of the expression.
787 # null if self is a statement or in case of error
788 var mtype: nullable MType = null
789
790 # Is the statement correctly typed?
791 # Used to distinguish errors and statements when `mtype == null`
792 var is_typed: Bool = false
793
794 # If required, the following implicit cast `.as(XXX)`
795 # Such a cast may by required after evaluating the expression when
796 # a unsafe operation is detected (silently accepted by the Nit language).
797 # The attribute is computed by `check_subtype`
798 var implicit_cast_to: nullable MType = null
799
800 # Return the variable read (if any)
801 # Used to perform adaptive typing
802 fun its_variable: nullable Variable do return null
803
804 private fun accept_typing(v: TypeVisitor)
805 do
806 v.error(self, "no implemented accept_typing for {self.class_name}")
807 end
808
809 # Is non-null if `self` is a leaf of a comprehension array construction.
810 # In this case, the enclosing literal array node is designated.
811 # The result of the evaluation of `self` must be
812 # stored inside the designated array (there is an implicit `push`)
813 var comprehension: nullable AArrayExpr = null
814 end
815
816 redef class ABlockExpr
817 redef fun accept_typing(v)
818 do
819 for e in self.n_expr do v.visit_stmt(e)
820 self.is_typed = true
821 end
822
823 # The type of a blockexpr is the one of the last expression (or null if empty)
824 redef fun mtype
825 do
826 if self.n_expr.is_empty then return null
827 return self.n_expr.last.mtype
828 end
829 end
830
831 redef class AVardeclExpr
832 redef fun accept_typing(v)
833 do
834 var variable = self.variable
835 if variable == null then return # Skip error
836
837 var ntype = self.n_type
838 var mtype: nullable MType
839 if ntype == null then
840 mtype = null
841 else
842 mtype = v.resolve_mtype(ntype)
843 if mtype == null then return # Skip error
844 end
845
846 var nexpr = self.n_expr
847 if nexpr != null then
848 if mtype != null then
849 var etype = v.visit_expr_subtype(nexpr, mtype)
850 if etype == mtype then
851 assert ntype != null
852 v.modelbuilder.advice(ntype, "useless-type", "Warning: useless type definition for variable `{variable.name}`")
853 end
854 else
855 mtype = v.visit_expr(nexpr)
856 if mtype == null then return # Skip error
857 end
858 end
859
860 var decltype = mtype
861 if mtype == null or mtype isa MNullType then
862 var objclass = v.get_mclass(self, "Object")
863 if objclass == null then return # skip error
864 decltype = objclass.mclass_type.as_nullable
865 if mtype == null then mtype = decltype
866 end
867
868 variable.declared_type = decltype
869 v.set_variable(self, variable, mtype)
870
871 #debug("var {variable}: {mtype}")
872
873 self.mtype = mtype
874 self.is_typed = true
875 end
876 end
877
878 redef class AVarExpr
879 redef fun its_variable do return self.variable
880 redef fun accept_typing(v)
881 do
882 var variable = self.variable
883 if variable == null then return # Skip error
884
885 var mtype = v.get_variable(self, variable)
886 if mtype != null then
887 #debug("{variable} is {mtype}")
888 else
889 #debug("{variable} is untyped")
890 end
891
892 self.mtype = mtype
893 end
894 end
895
896 redef class AVarAssignExpr
897 redef fun accept_typing(v)
898 do
899 var variable = self.variable
900 assert variable != null
901
902 var mtype = v.visit_expr_subtype(n_value, variable.declared_type)
903
904 v.set_variable(self, variable, mtype)
905
906 self.is_typed = true
907 end
908 end
909
910 redef class AReassignFormExpr
911 # The method designed by the reassign operator.
912 var reassign_callsite: nullable CallSite
913
914 var read_type: nullable MType = null
915
916 # Determine the `reassign_property`
917 # `readtype` is the type of the reading of the left value.
918 # `writetype` is the type of the writing of the left value.
919 # (Because of `ACallReassignExpr`, both can be different.
920 # Return the static type of the value to store.
921 private fun resolve_reassignment(v: TypeVisitor, readtype, writetype: MType): nullable MType
922 do
923 var reassign_name = self.n_assign_op.operator
924
925 self.read_type = readtype
926
927 var callsite = v.get_method(self.n_assign_op, readtype, reassign_name, false)
928 if callsite == null then return null # Skip error
929 self.reassign_callsite = callsite
930
931 var msignature = callsite.msignature
932 var rettype = msignature.return_mtype
933 assert msignature.arity == 1 and rettype != null
934
935 var value_type = v.visit_expr_subtype(self.n_value, msignature.mparameters.first.mtype)
936 if value_type == null then return null # Skip error
937
938 v.check_subtype(self, rettype, writetype, false)
939 return rettype
940 end
941 end
942
943 redef class AVarReassignExpr
944 redef fun accept_typing(v)
945 do
946 var variable = self.variable
947 assert variable != null
948
949 var readtype = v.get_variable(self, variable)
950 if readtype == null then return
951
952 read_type = readtype
953
954 var writetype = variable.declared_type
955 if writetype == null then return
956
957 var rettype = self.resolve_reassignment(v, readtype, writetype)
958
959 v.set_variable(self, variable, rettype)
960
961 self.is_typed = true
962 end
963 end
964
965
966 redef class AContinueExpr
967 redef fun accept_typing(v)
968 do
969 var nexpr = self.n_expr
970 if nexpr != null then
971 v.visit_expr(nexpr)
972 end
973 self.is_typed = true
974 end
975 end
976
977 redef class ABreakExpr
978 redef fun accept_typing(v)
979 do
980 var nexpr = self.n_expr
981 if nexpr != null then
982 v.visit_expr(nexpr)
983 end
984 self.is_typed = true
985 end
986 end
987
988 redef class AReturnExpr
989 redef fun accept_typing(v)
990 do
991 var nexpr = self.n_expr
992 var ret_type
993 var mpropdef = v.mpropdef
994 if mpropdef isa MMethodDef then
995 ret_type = mpropdef.msignature.return_mtype
996 else if mpropdef isa MAttributeDef then
997 ret_type = mpropdef.static_mtype
998 else
999 abort
1000 end
1001 if nexpr != null then
1002 if ret_type != null then
1003 v.visit_expr_subtype(nexpr, ret_type)
1004 else
1005 v.visit_expr(nexpr)
1006 v.error(nexpr, "Error: `return` with value in a procedure.")
1007 end
1008 else if ret_type != null then
1009 v.error(self, "Error: `return` without value in a function.")
1010 end
1011 self.is_typed = true
1012 end
1013 end
1014
1015 redef class AAbortExpr
1016 redef fun accept_typing(v)
1017 do
1018 self.is_typed = true
1019 end
1020 end
1021
1022 redef class AIfExpr
1023 redef fun accept_typing(v)
1024 do
1025 v.visit_expr_bool(n_expr)
1026
1027 v.visit_stmt(n_then)
1028 v.visit_stmt(n_else)
1029
1030 self.is_typed = true
1031
1032 if n_then != null and n_else == null then
1033 self.mtype = n_then.mtype
1034 end
1035 end
1036 end
1037
1038 redef class AIfexprExpr
1039 redef fun accept_typing(v)
1040 do
1041 v.visit_expr_bool(n_expr)
1042
1043 var t1 = v.visit_expr(n_then)
1044 var t2 = v.visit_expr(n_else)
1045
1046 if t1 == null or t2 == null then
1047 return # Skip error
1048 end
1049
1050 var t = v.merge_types(self, [t1, t2])
1051 if t == null then
1052 v.error(self, "Type Error: ambiguous type `{t1}` vs `{t2}`.")
1053 end
1054 self.mtype = t
1055 end
1056 end
1057
1058 redef class ADoExpr
1059 redef fun accept_typing(v)
1060 do
1061 v.visit_stmt(n_block)
1062 self.is_typed = true
1063 end
1064 end
1065
1066 redef class AWhileExpr
1067 redef fun accept_typing(v)
1068 do
1069 v.has_loop = true
1070 v.visit_expr_bool(n_expr)
1071 v.visit_stmt(n_block)
1072 self.is_typed = true
1073 end
1074 end
1075
1076 redef class ALoopExpr
1077 redef fun accept_typing(v)
1078 do
1079 v.has_loop = true
1080 v.visit_stmt(n_block)
1081 self.is_typed = true
1082 end
1083 end
1084
1085 redef class AForExpr
1086 var coltype: nullable MClassType
1087
1088 var method_iterator: nullable CallSite
1089 var method_is_ok: nullable CallSite
1090 var method_item: nullable CallSite
1091 var method_next: nullable CallSite
1092 var method_key: nullable CallSite
1093 var method_finish: nullable CallSite
1094
1095 var method_lt: nullable CallSite
1096 var method_successor: nullable CallSite
1097
1098 private fun do_type_iterator(v: TypeVisitor, mtype: MType)
1099 do
1100 if mtype isa MNullType then
1101 v.error(self, "Type Error: `for` cannot iterate over `null`.")
1102 return
1103 end
1104
1105 # get obj class
1106 var objcla = v.get_mclass(self, "Object")
1107 if objcla == null then return
1108
1109 # check iterator method
1110 var itdef = v.get_method(self, mtype, "iterator", n_expr isa ASelfExpr)
1111 if itdef == null then
1112 v.error(self, "Type Error: `for` expects a type providing an `iterator` method, got `{mtype}`.")
1113 return
1114 end
1115 self.method_iterator = itdef
1116
1117 # check that iterator return something
1118 var ittype = itdef.msignature.return_mtype
1119 if ittype == null then
1120 v.error(self, "Type Error: `for` expects the method `iterator` to return an `Iterator` or `MapIterator` type.")
1121 return
1122 end
1123
1124 # get iterator type
1125 var colit_cla = v.try_get_mclass(self, "Iterator")
1126 var mapit_cla = v.try_get_mclass(self, "MapIterator")
1127 var is_col = false
1128 var is_map = false
1129
1130 if colit_cla != null and v.is_subtype(ittype, colit_cla.get_mtype([objcla.mclass_type.as_nullable])) then
1131 # Iterator
1132 var coltype = ittype.supertype_to(v.mmodule, v.anchor, colit_cla)
1133 var variables = self.variables
1134 if variables.length != 1 then
1135 v.error(self, "Type Error: `for` expects only one variable when using `Iterator`.")
1136 else
1137 variables.first.declared_type = coltype.arguments.first
1138 end
1139 is_col = true
1140 end
1141
1142 if mapit_cla != null and v.is_subtype(ittype, mapit_cla.get_mtype([objcla.mclass_type.as_nullable, objcla.mclass_type.as_nullable])) then
1143 # Map Iterator
1144 var coltype = ittype.supertype_to(v.mmodule, v.anchor, mapit_cla)
1145 var variables = self.variables
1146 if variables.length != 2 then
1147 v.error(self, "Type Error: `for` expects two variables when using `MapIterator`.")
1148 else
1149 variables[0].declared_type = coltype.arguments[0]
1150 variables[1].declared_type = coltype.arguments[1]
1151 end
1152 is_map = true
1153 end
1154
1155 if not is_col and not is_map then
1156 v.error(self, "Type Error: `for` expects the method `iterator` to return an `Iterator` or `MapIterator` type.")
1157 return
1158 end
1159
1160 # anchor formal and virtual types
1161 if mtype.need_anchor then mtype = v.anchor_to(mtype)
1162
1163 mtype = mtype.undecorate
1164 self.coltype = mtype.as(MClassType)
1165
1166 # get methods is_ok, next, item
1167 var ikdef = v.get_method(self, ittype, "is_ok", false)
1168 if ikdef == null then
1169 v.error(self, "Type Error: `for` expects a method `is_ok` in type `{ittype}`.")
1170 return
1171 end
1172 self.method_is_ok = ikdef
1173
1174 var itemdef = v.get_method(self, ittype, "item", false)
1175 if itemdef == null then
1176 v.error(self, "Type Error: `for` expects a method `item` in type `{ittype}`.")
1177 return
1178 end
1179 self.method_item = itemdef
1180
1181 var nextdef = v.get_method(self, ittype, "next", false)
1182 if nextdef == null then
1183 v.error(self, "Type Error: `for` expects a method `next` in type {ittype}.")
1184 return
1185 end
1186 self.method_next = nextdef
1187
1188 self.method_finish = v.try_get_method(self, ittype, "finish", false)
1189
1190 if is_map then
1191 var keydef = v.get_method(self, ittype, "key", false)
1192 if keydef == null then
1193 v.error(self, "Type Error: `for` expects a method `key` in type `{ittype}`.")
1194 return
1195 end
1196 self.method_key = keydef
1197 end
1198
1199 if self.variables.length == 1 and n_expr isa ARangeExpr then
1200 var variable = variables.first
1201 var vtype = variable.declared_type.as(not null)
1202
1203 if n_expr isa AOrangeExpr then
1204 self.method_lt = v.get_method(self, vtype, "<", false)
1205 else
1206 self.method_lt = v.get_method(self, vtype, "<=", false)
1207 end
1208
1209 self.method_successor = v.get_method(self, vtype, "successor", false)
1210 end
1211 end
1212
1213 redef fun accept_typing(v)
1214 do
1215 v.has_loop = true
1216 var mtype = v.visit_expr(n_expr)
1217 if mtype == null then return
1218
1219 self.do_type_iterator(v, mtype)
1220
1221 v.visit_stmt(n_block)
1222
1223 self.mtype = n_block.mtype
1224 self.is_typed = true
1225 end
1226 end
1227
1228 redef class AWithExpr
1229 var method_start: nullable CallSite
1230 var method_finish: nullable CallSite
1231
1232 redef fun accept_typing(v: TypeVisitor)
1233 do
1234 var mtype = v.visit_expr(n_expr)
1235 if mtype == null then return
1236
1237 method_start = v.get_method(self, mtype, "start", n_expr isa ASelfExpr)
1238 method_finish = v.get_method(self, mtype, "finish", n_expr isa ASelfExpr)
1239
1240 v.visit_stmt(n_block)
1241 self.mtype = n_block.mtype
1242 self.is_typed = true
1243 end
1244 end
1245
1246 redef class AAssertExpr
1247 redef fun accept_typing(v)
1248 do
1249 v.visit_expr_bool(n_expr)
1250
1251 v.visit_stmt(n_else)
1252 self.is_typed = true
1253 end
1254 end
1255
1256 redef class AOrExpr
1257 redef fun accept_typing(v)
1258 do
1259 v.visit_expr_bool(n_expr)
1260 v.visit_expr_bool(n_expr2)
1261 self.mtype = v.type_bool(self)
1262 end
1263 end
1264
1265 redef class AImpliesExpr
1266 redef fun accept_typing(v)
1267 do
1268 v.visit_expr_bool(n_expr)
1269 v.visit_expr_bool(n_expr2)
1270 self.mtype = v.type_bool(self)
1271 end
1272 end
1273
1274 redef class AAndExpr
1275 redef fun accept_typing(v)
1276 do
1277 v.visit_expr_bool(n_expr)
1278 v.visit_expr_bool(n_expr2)
1279 self.mtype = v.type_bool(self)
1280 end
1281 end
1282
1283
1284 redef class ANotExpr
1285 redef fun accept_typing(v)
1286 do
1287 v.visit_expr_bool(n_expr)
1288 self.mtype = v.type_bool(self)
1289 end
1290 end
1291
1292 redef class AOrElseExpr
1293 redef fun accept_typing(v)
1294 do
1295 var t1 = v.visit_expr(n_expr)
1296 var t2 = v.visit_expr(n_expr2)
1297
1298 if t1 == null or t2 == null then
1299 return # Skip error
1300 end
1301
1302 if t1 isa MNullType then
1303 v.error(n_expr, "Type Error: `or else` on `null`.")
1304 else if v.check_can_be_null(n_expr, t1) then
1305 t1 = t1.as_notnull
1306 end
1307
1308 var t = v.merge_types(self, [t1, t2])
1309 if t == null then
1310 var c = v.get_mclass(self, "Object")
1311 if c == null then return # forward error
1312 t = c.mclass_type
1313 if v.can_be_null(t2) then
1314 t = t.as_nullable
1315 end
1316 #v.error(self, "Type Error: ambiguous type {t1} vs {t2}")
1317 end
1318 self.mtype = t
1319 end
1320 end
1321
1322 redef class ATrueExpr
1323 redef fun accept_typing(v)
1324 do
1325 self.mtype = v.type_bool(self)
1326 end
1327 end
1328
1329 redef class AFalseExpr
1330 redef fun accept_typing(v)
1331 do
1332 self.mtype = v.type_bool(self)
1333 end
1334 end
1335
1336 redef class AIntExpr
1337 redef fun accept_typing(v)
1338 do
1339 var mclass = v.get_mclass(self, "Int")
1340 if mclass == null then return # Forward error
1341 self.mtype = mclass.mclass_type
1342 end
1343 end
1344
1345 redef class AFloatExpr
1346 redef fun accept_typing(v)
1347 do
1348 var mclass = v.get_mclass(self, "Float")
1349 if mclass == null then return # Forward error
1350 self.mtype = mclass.mclass_type
1351 end
1352 end
1353
1354 redef class ACharExpr
1355 redef fun accept_typing(v)
1356 do
1357 var mclass = v.get_mclass(self, "Char")
1358 if mclass == null then return # Forward error
1359 self.mtype = mclass.mclass_type
1360 end
1361 end
1362
1363 redef class AStringFormExpr
1364 redef fun accept_typing(v)
1365 do
1366 var mclass = v.get_mclass(self, "String")
1367 if mclass == null then return # Forward error
1368 self.mtype = mclass.mclass_type
1369 end
1370 end
1371
1372 redef class ASuperstringExpr
1373 redef fun accept_typing(v)
1374 do
1375 var mclass = v.get_mclass(self, "String")
1376 if mclass == null then return # Forward error
1377 self.mtype = mclass.mclass_type
1378 var objclass = v.get_mclass(self, "Object")
1379 if objclass == null then return # Forward error
1380 var objtype = objclass.mclass_type
1381 for nexpr in self.n_exprs do
1382 v.visit_expr_subtype(nexpr, objtype)
1383 end
1384 end
1385 end
1386
1387 redef class AArrayExpr
1388 # The `with_capacity` method on Array
1389 var with_capacity_callsite: nullable CallSite
1390
1391 # The `push` method on arrays
1392 var push_callsite: nullable CallSite
1393
1394 # The element of each type
1395 var element_mtype: nullable MType
1396
1397 # Set that `self` is a part of comprehension array `na`
1398 # If `self` is a `for`, or a `if`, then `set_comprehension` is recursively applied.
1399 private fun set_comprehension(n: nullable AExpr)
1400 do
1401 if n == null then
1402 return
1403 else if n isa AForExpr then
1404 set_comprehension(n.n_block)
1405 else if n isa AIfExpr then
1406 set_comprehension(n.n_then)
1407 set_comprehension(n.n_else)
1408 else
1409 # is a leave
1410 n.comprehension = self
1411 end
1412 end
1413 redef fun accept_typing(v)
1414 do
1415 var mtype: nullable MType = null
1416 var ntype = self.n_type
1417 if ntype != null then
1418 mtype = v.resolve_mtype(ntype)
1419 if mtype == null then return # Skip error
1420 end
1421 var mtypes = new Array[nullable MType]
1422 var useless = false
1423 for e in self.n_exprs do
1424 var t = v.visit_expr(e)
1425 if t == null then
1426 return # Skip error
1427 end
1428 set_comprehension(e)
1429 if mtype != null then
1430 if v.check_subtype(e, t, mtype, false) == null then return # Forward error
1431 if t == mtype then useless = true
1432 else
1433 mtypes.add(t)
1434 end
1435 end
1436 if mtype == null then
1437 # Ensure monotony for type adaptation on loops
1438 if self.element_mtype != null then mtypes.add self.element_mtype
1439 mtype = v.merge_types(self, mtypes)
1440 end
1441 if mtype == null or mtype isa MNullType then
1442 v.error(self, "Type Error: ambiguous array type {mtypes.join(" ")}")
1443 return
1444 end
1445 if useless then
1446 assert ntype != null
1447 v.modelbuilder.warning(ntype, "useless-type", "Warning: useless type declaration `{mtype}` in literal Array since it can be inferred from the elements type.")
1448 end
1449
1450 self.element_mtype = mtype
1451
1452 var mclass = v.get_mclass(self, "Array")
1453 if mclass == null then return # Forward error
1454 var array_mtype = mclass.get_mtype([mtype])
1455
1456 with_capacity_callsite = v.get_method(self, array_mtype, "with_capacity", false)
1457 push_callsite = v.get_method(self, array_mtype, "push", false)
1458
1459 self.mtype = array_mtype
1460 end
1461 end
1462
1463 redef class ARangeExpr
1464 var init_callsite: nullable CallSite
1465
1466 redef fun accept_typing(v)
1467 do
1468 var discrete_class = v.get_mclass(self, "Discrete")
1469 if discrete_class == null then return # Forward error
1470 var discrete_type = discrete_class.intro.bound_mtype
1471 var t1 = v.visit_expr_subtype(self.n_expr, discrete_type)
1472 var t2 = v.visit_expr_subtype(self.n_expr2, discrete_type)
1473 if t1 == null or t2 == null then return
1474 var mclass = v.get_mclass(self, "Range")
1475 if mclass == null then return # Forward error
1476 var mtype
1477 if v.is_subtype(t1, t2) then
1478 mtype = mclass.get_mtype([t2])
1479 else if v.is_subtype(t2, t1) then
1480 mtype = mclass.get_mtype([t1])
1481 else
1482 v.error(self, "Type Error: cannot create range: `{t1}` vs `{t2}`.")
1483 return
1484 end
1485
1486 self.mtype = mtype
1487
1488 # get the constructor
1489 var callsite
1490 if self isa ACrangeExpr then
1491 callsite = v.get_method(self, mtype, "init", false)
1492 else if self isa AOrangeExpr then
1493 callsite = v.get_method(self, mtype, "without_last", false)
1494 else
1495 abort
1496 end
1497 init_callsite = callsite
1498 end
1499 end
1500
1501 redef class ANullExpr
1502 redef fun accept_typing(v)
1503 do
1504 self.mtype = v.mmodule.model.null_type
1505 end
1506 end
1507
1508 redef class AIsaExpr
1509 # The static type to cast to.
1510 # (different from the static type of the expression that is `Bool`).
1511 var cast_type: nullable MType
1512 redef fun accept_typing(v)
1513 do
1514 var mtype = v.visit_expr_cast(self, self.n_expr, self.n_type)
1515 self.cast_type = mtype
1516
1517 var variable = self.n_expr.its_variable
1518 if variable != null then
1519 #var orig = self.n_expr.mtype
1520 #var from = if orig != null then orig.to_s else "invalid"
1521 #var to = if mtype != null then mtype.to_s else "invalid"
1522 #debug("adapt {variable}: {from} -> {to}")
1523 self.after_flow_context.when_true.set_var(v, variable, mtype)
1524 end
1525
1526 self.mtype = v.type_bool(self)
1527 end
1528 end
1529
1530 redef class AAsCastExpr
1531 redef fun accept_typing(v)
1532 do
1533 self.mtype = v.visit_expr_cast(self, self.n_expr, self.n_type)
1534 end
1535 end
1536
1537 redef class AAsNotnullExpr
1538 redef fun accept_typing(v)
1539 do
1540 var mtype = v.visit_expr(self.n_expr)
1541 if mtype == null then return # Forward error
1542
1543 if mtype isa MNullType then
1544 v.error(self, "Type Error: `as(not null)` on `null`.")
1545 return
1546 end
1547
1548 if v.check_can_be_null(n_expr, mtype) then
1549 mtype = mtype.as_notnull
1550 end
1551
1552 self.mtype = mtype
1553 end
1554 end
1555
1556 redef class AParExpr
1557 redef fun accept_typing(v)
1558 do
1559 self.mtype = v.visit_expr(self.n_expr)
1560 end
1561 end
1562
1563 redef class AOnceExpr
1564 redef fun accept_typing(v)
1565 do
1566 self.mtype = v.visit_expr(self.n_expr)
1567 end
1568 end
1569
1570 redef class ASelfExpr
1571 redef var its_variable: nullable Variable
1572 redef fun accept_typing(v)
1573 do
1574 if v.is_toplevel_context and not self isa AImplicitSelfExpr then
1575 v.error(self, "Error: `self` cannot be used in top-level method.")
1576 end
1577 var variable = v.selfvariable
1578 self.its_variable = variable
1579 self.mtype = v.get_variable(self, variable)
1580 end
1581 end
1582
1583 redef class AImplicitSelfExpr
1584 # Is the implicit receiver `sys`?
1585 #
1586 # By default, the implicit receiver is `self`.
1587 # But when there is not method for `self`, `sys` is used as a fall-back.
1588 # Is this case this flag is set to `true`.
1589 var is_sys = false
1590 end
1591
1592 ## MESSAGE SENDING AND PROPERTY
1593
1594 redef class ASendExpr
1595 # The property invoked by the send.
1596 var callsite: nullable CallSite
1597
1598 redef fun accept_typing(v)
1599 do
1600 var nrecv = self.n_expr
1601 var recvtype = v.visit_expr(nrecv)
1602 var name = self.property_name
1603 var node = self.property_node
1604
1605 if recvtype == null then return # Forward error
1606
1607 var callsite = null
1608 var unsafe_type = v.anchor_to(recvtype)
1609 var mproperty = v.try_get_mproperty_by_name2(node, unsafe_type, name)
1610 if mproperty == null and nrecv isa AImplicitSelfExpr then
1611 # Special fall-back search in `sys` when noting found in the implicit receiver.
1612 var sysclass = v.try_get_mclass(node, "Sys")
1613 if sysclass != null then
1614 var systype = sysclass.mclass_type
1615 mproperty = v.try_get_mproperty_by_name2(node, systype, name)
1616 if mproperty != null then
1617 callsite = v.get_method(node, systype, name, false)
1618 if callsite == null then return # Forward error
1619 # Update information, we are looking at `sys` now, not `self`
1620 nrecv.is_sys = true
1621 nrecv.its_variable = null
1622 nrecv.mtype = systype
1623 recvtype = systype
1624 end
1625 end
1626 end
1627 if callsite == null then
1628 # If still nothing, just exit
1629 callsite = v.get_method(node, recvtype, name, nrecv isa ASelfExpr)
1630 if callsite == null then return
1631 end
1632
1633 self.callsite = callsite
1634 var msignature = callsite.msignature
1635
1636 var args = compute_raw_arguments
1637
1638 callsite.check_signature(v, args)
1639
1640 if callsite.mproperty.is_init then
1641 var vmpropdef = v.mpropdef
1642 if not (vmpropdef isa MMethodDef and vmpropdef.mproperty.is_init) then
1643 v.error(node, "Error: an `init` can only be called from another `init`.")
1644 end
1645 if vmpropdef isa MMethodDef and vmpropdef.mproperty.is_root_init and not callsite.mproperty.is_root_init then
1646 v.error(node, "Error: `{vmpropdef}` cannot call a factory `{callsite.mproperty}`.")
1647 end
1648 end
1649
1650 var ret = msignature.return_mtype
1651 if ret != null then
1652 self.mtype = ret
1653 else
1654 self.is_typed = true
1655 end
1656 end
1657
1658 # The name of the property
1659 # Each subclass simply provide the correct name.
1660 private fun property_name: String is abstract
1661
1662 # The node identifying the name (id, operator, etc) for messages.
1663 #
1664 # Is `self` by default
1665 private fun property_node: ANode do return self
1666
1667 # An array of all arguments (excluding self)
1668 fun raw_arguments: Array[AExpr] do return compute_raw_arguments
1669
1670 private fun compute_raw_arguments: Array[AExpr] is abstract
1671 end
1672
1673 redef class ABinopExpr
1674 redef fun compute_raw_arguments do return [n_expr2]
1675 redef fun property_name do return operator
1676 redef fun property_node do return n_op
1677 end
1678 redef class AEqExpr
1679 redef fun accept_typing(v)
1680 do
1681 super
1682 v.null_test(self)
1683 end
1684 end
1685 redef class ANeExpr
1686 redef fun accept_typing(v)
1687 do
1688 super
1689 v.null_test(self)
1690 end
1691 end
1692
1693 redef class AUnaryopExpr
1694 redef fun property_name do return "unary {operator}"
1695 redef fun compute_raw_arguments do return new Array[AExpr]
1696 end
1697
1698
1699 redef class ACallExpr
1700 redef fun property_name do return n_id.text
1701 redef fun property_node do return n_id
1702 redef fun compute_raw_arguments do return n_args.to_a
1703 end
1704
1705 redef class ACallAssignExpr
1706 redef fun property_name do return n_id.text + "="
1707 redef fun property_node do return n_id
1708 redef fun compute_raw_arguments
1709 do
1710 var res = n_args.to_a
1711 res.add(n_value)
1712 return res
1713 end
1714 end
1715
1716 redef class ABraExpr
1717 redef fun property_name do return "[]"
1718 redef fun compute_raw_arguments do return n_args.to_a
1719 end
1720
1721 redef class ABraAssignExpr
1722 redef fun property_name do return "[]="
1723 redef fun compute_raw_arguments
1724 do
1725 var res = n_args.to_a
1726 res.add(n_value)
1727 return res
1728 end
1729 end
1730
1731 redef class ASendReassignFormExpr
1732 # The property invoked for the writing
1733 var write_callsite: nullable CallSite
1734
1735 redef fun accept_typing(v)
1736 do
1737 var recvtype = v.visit_expr(self.n_expr)
1738 var name = self.property_name
1739 var node = self.property_node
1740
1741 if recvtype == null then return # Forward error
1742
1743 var for_self = self.n_expr isa ASelfExpr
1744 var callsite = v.get_method(node, recvtype, name, for_self)
1745
1746 if callsite == null then return
1747 self.callsite = callsite
1748
1749 var args = compute_raw_arguments
1750
1751 callsite.check_signature(v, args)
1752
1753 var readtype = callsite.msignature.return_mtype
1754 if readtype == null then
1755 v.error(node, "Error: `{name}` is not a function.")
1756 return
1757 end
1758
1759 var wcallsite = v.get_method(node, recvtype, name + "=", self.n_expr isa ASelfExpr)
1760 if wcallsite == null then return
1761 self.write_callsite = wcallsite
1762
1763 var wtype = self.resolve_reassignment(v, readtype, wcallsite.msignature.mparameters.last.mtype)
1764 if wtype == null then return
1765
1766 args = args.to_a # duplicate so raw_arguments keeps only the getter args
1767 args.add(self.n_value)
1768 wcallsite.check_signature(v, args)
1769
1770 self.is_typed = true
1771 end
1772 end
1773
1774 redef class ACallReassignExpr
1775 redef fun property_name do return n_id.text
1776 redef fun property_node do return n_id
1777 redef fun compute_raw_arguments do return n_args.to_a
1778 end
1779
1780 redef class ABraReassignExpr
1781 redef fun property_name do return "[]"
1782 redef fun compute_raw_arguments do return n_args.to_a
1783 end
1784
1785 redef class AInitExpr
1786 redef fun property_name do return "init"
1787 redef fun property_node do return n_kwinit
1788 redef fun compute_raw_arguments do return n_args.to_a
1789 end
1790
1791 redef class AExprs
1792 fun to_a: Array[AExpr] do return self.n_exprs.to_a
1793 end
1794
1795 ###
1796
1797 redef class ASuperExpr
1798 # The method to call if the super is in fact a 'super init call'
1799 # Note: if the super is a normal call-next-method, then this attribute is null
1800 var callsite: nullable CallSite
1801
1802 # The method to call is the super is a standard `call-next-method` super-call
1803 # Note: if the super is a special super-init-call, then this attribute is null
1804 var mpropdef: nullable MMethodDef
1805
1806 redef fun accept_typing(v)
1807 do
1808 var anchor = v.anchor
1809 assert anchor != null
1810 var recvtype = v.get_variable(self, v.selfvariable)
1811 assert recvtype != null
1812 var mproperty = v.mpropdef.mproperty
1813 if not mproperty isa MMethod then
1814 v.error(self, "Error: `super` only usable in a `method`.")
1815 return
1816 end
1817 var superprops = mproperty.lookup_super_definitions(v.mmodule, anchor)
1818 if superprops.length == 0 then
1819 if mproperty.is_init and v.mpropdef.is_intro then
1820 process_superinit(v)
1821 return
1822 end
1823 v.error(self, "Error: no super method to call for `{mproperty}`.")
1824 return
1825 end
1826 # FIXME: covariance of return type in linear extension?
1827 var superprop = superprops.first
1828
1829 var msignature = superprop.msignature.as(not null)
1830 msignature = v.resolve_for(msignature, recvtype, true).as(MSignature)
1831 var args = self.n_args.to_a
1832 if args.length > 0 then
1833 signaturemap = v.check_signature(self, args, mproperty, msignature)
1834 end
1835 self.mtype = msignature.return_mtype
1836 self.is_typed = true
1837 v.mpropdef.has_supercall = true
1838 mpropdef = v.mpropdef.as(MMethodDef)
1839 end
1840
1841 # The mapping used on the call to associate arguments to parameters.
1842 # If null then no specific association is required.
1843 var signaturemap: nullable SignatureMap
1844
1845 private fun process_superinit(v: TypeVisitor)
1846 do
1847 var anchor = v.anchor
1848 assert anchor != null
1849 var recvtype = v.get_variable(self, v.selfvariable)
1850 assert recvtype != null
1851 var mpropdef = v.mpropdef
1852 assert mpropdef isa MMethodDef
1853 var mproperty = mpropdef.mproperty
1854 var superprop: nullable MMethodDef = null
1855 for msupertype in mpropdef.mclassdef.supertypes do
1856 msupertype = msupertype.anchor_to(v.mmodule, anchor)
1857 var errcount = v.modelbuilder.toolcontext.error_count
1858 var candidate = v.try_get_mproperty_by_name2(self, msupertype, mproperty.name).as(nullable MMethod)
1859 if candidate == null then
1860 if v.modelbuilder.toolcontext.error_count > errcount then return # Forward error
1861 continue # Try next super-class
1862 end
1863 if superprop != null and candidate.is_root_init then
1864 continue
1865 end
1866 if superprop != null and superprop.mproperty != candidate and not superprop.mproperty.is_root_init then
1867 v.error(self, "Error: conflicting super constructor to call for `{mproperty}`: `{candidate.full_name}`, `{superprop.mproperty.full_name}`")
1868 return
1869 end
1870 var candidatedefs = candidate.lookup_definitions(v.mmodule, anchor)
1871 if superprop != null and superprop.mproperty == candidate then
1872 if superprop == candidatedefs.first then continue
1873 candidatedefs.add(superprop)
1874 end
1875 if candidatedefs.length > 1 then
1876 v.error(self, "Error: conflicting property definitions for property `{mproperty}` in `{recvtype}`: {candidatedefs.join(", ")}")
1877 return
1878 end
1879 superprop = candidatedefs.first
1880 end
1881 if superprop == null then
1882 v.error(self, "Error: no super method to call for `{mproperty}`.")
1883 return
1884 end
1885
1886 var msignature = superprop.new_msignature or else superprop.msignature.as(not null)
1887 msignature = v.resolve_for(msignature, recvtype, true).as(MSignature)
1888
1889 var callsite = new CallSite(self, recvtype, v.mmodule, v.anchor, true, superprop.mproperty, superprop, msignature, false)
1890 self.callsite = callsite
1891
1892 var args = self.n_args.to_a
1893 if args.length > 0 then
1894 callsite.check_signature(v, args)
1895 else
1896 # Check there is at least enough parameters
1897 if mpropdef.msignature.arity < msignature.arity then
1898 v.error(self, "Error: not enough implicit arguments to pass. Got `{mpropdef.msignature.arity}`, expected at least `{msignature.arity}`. Signature is `{msignature}`.")
1899 return
1900 end
1901 # Check that each needed parameter is conform
1902 var i = 0
1903 for sp in msignature.mparameters do
1904 var p = mpropdef.msignature.mparameters[i]
1905 if not v.is_subtype(p.mtype, sp.mtype) then
1906 v.error(self, "Type Error: expected argument #{i} of type `{sp.mtype}`, got implicit argument `{p.name}` of type `{p.mtype}`. Signature is {msignature}")
1907 return
1908 end
1909 i += 1
1910 end
1911 end
1912
1913 self.is_typed = true
1914 end
1915 end
1916
1917 ####
1918
1919 redef class ANewExpr
1920 # The constructor invoked by the new.
1921 var callsite: nullable CallSite
1922
1923 # The designated type
1924 var recvtype: nullable MClassType
1925
1926 redef fun accept_typing(v)
1927 do
1928 var recvtype = v.resolve_mtype(self.n_type)
1929 if recvtype == null then return
1930
1931 if not recvtype isa MClassType then
1932 if recvtype isa MNullableType then
1933 v.error(self, "Type Error: cannot instantiate the nullable type `{recvtype}`.")
1934 return
1935 else if recvtype isa MFormalType then
1936 v.error(self, "Type Error: cannot instantiate the formal type `{recvtype}`.")
1937 return
1938 else
1939 v.error(self, "Type Error: cannot instantiate the type `{recvtype}`.")
1940 return
1941 end
1942 end
1943
1944 self.recvtype = recvtype
1945 var kind = recvtype.mclass.kind
1946
1947 var name: String
1948 var nid = self.n_id
1949 var node: ANode
1950 if nid != null then
1951 name = nid.text
1952 node = nid
1953 else
1954 name = "new"
1955 node = self.n_kwnew
1956 end
1957 if name == "intern" then
1958 if kind != concrete_kind then
1959 v.error(self, "Type Error: cannot instantiate {kind} {recvtype}.")
1960 return
1961 end
1962 if n_args.n_exprs.not_empty then
1963 v.error(n_args, "Type Error: the intern constructor expects no arguments.")
1964 return
1965 end
1966 # Our job is done
1967 self.mtype = recvtype
1968 return
1969 end
1970
1971 var callsite = v.get_method(node, recvtype, name, false)
1972 if callsite == null then return
1973
1974 if not callsite.mproperty.is_new then
1975 if kind != concrete_kind then
1976 v.error(self, "Type Error: cannot instantiate {kind} `{recvtype}`.")
1977 return
1978 end
1979 self.mtype = recvtype
1980 else
1981 self.mtype = callsite.msignature.return_mtype
1982 assert self.mtype != null
1983 end
1984
1985 self.callsite = callsite
1986
1987 if not callsite.mproperty.is_init_for(recvtype.mclass) then
1988 v.error(self, "Error: `{name}` is not a constructor.")
1989 return
1990 end
1991
1992 var args = n_args.to_a
1993 callsite.check_signature(v, args)
1994 end
1995 end
1996
1997 ####
1998
1999 redef class AAttrFormExpr
2000 # The attribute accessed.
2001 var mproperty: nullable MAttribute
2002
2003 # The static type of the attribute.
2004 var attr_type: nullable MType
2005
2006 # Resolve the attribute accessed.
2007 private fun resolve_property(v: TypeVisitor)
2008 do
2009 var recvtype = v.visit_expr(self.n_expr)
2010 if recvtype == null then return # Skip error
2011 var node = self.n_id
2012 var name = node.text
2013 if recvtype isa MNullType then
2014 v.error(node, "Error: attribute `{name}` access on `null`.")
2015 return
2016 end
2017
2018 var unsafe_type = v.anchor_to(recvtype)
2019 var mproperty = v.try_get_mproperty_by_name2(node, unsafe_type, name)
2020 if mproperty == null then
2021 v.modelbuilder.error(node, "Error: attribute `{name}` does not exist in `{recvtype}`.")
2022 return
2023 end
2024 assert mproperty isa MAttribute
2025 self.mproperty = mproperty
2026
2027 var mpropdefs = mproperty.lookup_definitions(v.mmodule, unsafe_type)
2028 assert mpropdefs.length == 1
2029 var mpropdef = mpropdefs.first
2030 var attr_type = mpropdef.static_mtype
2031 if attr_type == null then return # skip error
2032 attr_type = v.resolve_for(attr_type, recvtype, self.n_expr isa ASelfExpr)
2033 self.attr_type = attr_type
2034 end
2035 end
2036
2037 redef class AAttrExpr
2038 redef fun accept_typing(v)
2039 do
2040 self.resolve_property(v)
2041 self.mtype = self.attr_type
2042 end
2043 end
2044
2045
2046 redef class AAttrAssignExpr
2047 redef fun accept_typing(v)
2048 do
2049 self.resolve_property(v)
2050 var mtype = self.attr_type
2051
2052 v.visit_expr_subtype(self.n_value, mtype)
2053 self.is_typed = true
2054 end
2055 end
2056
2057 redef class AAttrReassignExpr
2058 redef fun accept_typing(v)
2059 do
2060 self.resolve_property(v)
2061 var mtype = self.attr_type
2062 if mtype == null then return # Skip error
2063
2064 self.resolve_reassignment(v, mtype, mtype)
2065
2066 self.is_typed = true
2067 end
2068 end
2069
2070 redef class AIssetAttrExpr
2071 redef fun accept_typing(v)
2072 do
2073 self.resolve_property(v)
2074 var mtype = self.attr_type
2075 if mtype == null then return # Skip error
2076
2077 var recvtype = self.n_expr.mtype.as(not null)
2078 var bound = v.resolve_for(mtype, recvtype, false)
2079 if bound isa MNullableType then
2080 v.error(n_id, "Type Error: `isset` on a nullable attribute.")
2081 end
2082 self.mtype = v.type_bool(self)
2083 end
2084 end
2085
2086 redef class AVarargExpr
2087 redef fun accept_typing(v)
2088 do
2089 # This kind of pseudo-expression can be only processed trough a signature
2090 # See `check_signature`
2091 # Other cases are a syntax error.
2092 v.error(self, "Syntax Error: unexpected `...`.")
2093 end
2094 end
2095
2096 ###
2097
2098 redef class ADebugTypeExpr
2099 redef fun accept_typing(v)
2100 do
2101 var expr = v.visit_expr(self.n_expr)
2102 if expr == null then return
2103 var unsafe = v.anchor_to(expr)
2104 var ntype = self.n_type
2105 var mtype = v.resolve_mtype(ntype)
2106 if mtype != null and mtype != expr then
2107 var umtype = v.anchor_to(mtype)
2108 v.modelbuilder.warning(self, "debug", "Found type {expr} (-> {unsafe}), expected {mtype} (-> {umtype})")
2109 end
2110 self.is_typed = true
2111 end
2112 end