Merge: Autocast and literal arrays
[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 modelbuilder.error(node, "Error: expected {msignature.arity} argument(s) for `{mproperty}{msignature}`; got {args.length}. See introduction at `{mproperty.full_name}`.")
411 return null
412 end
413
414 #debug("CALL {unsafe_type}.{msignature}")
415
416 # Associate each parameter to a position in the arguments
417 var map = new SignatureMap
418
419 var vararg_decl = args.length - msignature.arity
420 var j = 0
421 for i in [0..msignature.arity[ do
422 var param = msignature.mparameters[i]
423 var arg = args[j]
424 map.map[i] = j
425 j += 1
426
427 if i == vararg_rank then
428 j += vararg_decl
429 continue # skip the vararg
430 end
431
432 var paramtype = param.mtype
433 self.visit_expr_subtype(arg, paramtype)
434 end
435 if vararg_rank >= 0 then
436 var paramtype = msignature.mparameters[vararg_rank].mtype
437 var first = args[vararg_rank]
438 if vararg_decl == 0 and first isa AVarargExpr then
439 var mclass = get_mclass(node, "Array")
440 if mclass == null then return null # Forward error
441 var array_mtype = mclass.get_mtype([paramtype])
442 self.visit_expr_subtype(first.n_expr, array_mtype)
443 first.mtype = first.n_expr.mtype
444 else
445 map.vararg_decl = vararg_decl + 1
446 for i in [vararg_rank..vararg_rank+vararg_decl] do
447 self.visit_expr_subtype(args[i], paramtype)
448 end
449 end
450 end
451
452 return map
453 end
454
455 fun error(node: ANode, message: String)
456 do
457 self.modelbuilder.toolcontext.error(node.hot_location, message)
458 end
459
460 fun get_variable(node: AExpr, variable: Variable): nullable MType
461 do
462 if not variable.is_adapted then return variable.declared_type
463
464 var flow = node.after_flow_context
465 if flow == null then return null # skip error
466
467 if flow.vars.has_key(variable) then
468 return flow.vars[variable]
469 else
470 #node.debug("*** START Collected for {variable}")
471 var mtypes = flow.collect_types(variable)
472 #node.debug("**** END Collected for {variable}")
473 if mtypes.length == 0 then
474 return variable.declared_type
475 else if mtypes.length == 1 then
476 return mtypes.first
477 else
478 var res = merge_types(node,mtypes)
479 if res == null then res = variable.declared_type
480 return res
481 end
482 end
483 end
484
485 # Some variables where type-adapted during the visit
486 var dirty = false
487
488 # Some loops had been visited during the visit
489 var has_loop = false
490
491 fun set_variable(node: AExpr, variable: Variable, mtype: nullable MType)
492 do
493 var flow = node.after_flow_context
494 assert flow != null
495
496 flow.set_var(self, variable, mtype)
497 end
498
499 fun merge_types(node: ANode, col: Array[nullable MType]): nullable MType
500 do
501 if col.length == 1 then return col.first
502 for t1 in col do
503 if t1 == null then continue # return null
504 var found = true
505 for t2 in col do
506 if t2 == null then continue # return null
507 if can_be_null(t2) and not can_be_null(t1) then
508 t1 = t1.as_nullable
509 end
510 if not is_subtype(t2, t1) then found = false
511 end
512 if found then
513 #print "merge {col.join(" ")} -> {t1}"
514 return t1
515 end
516 end
517 #self.modelbuilder.warning(node, "Type Error: {col.length} conflicting types: <{col.join(", ")}>")
518 return null
519 end
520 end
521
522 # Mapping between parameters and arguments in a call.
523 #
524 # Parameters and arguments are not stored in the class but referenced by their position (starting from 0)
525 #
526 # The point of this class is to help engine and other things to map arguments in the AST to parameters of the model.
527 class SignatureMap
528 # Associate a parameter to an argument
529 var map = new ArrayMap[Int, Int]
530
531 # The length of the vararg sequence
532 # 0 if no vararg or if reverse vararg (cf `AVarargExpr`)
533 var vararg_decl: Int = 0
534 end
535
536 # A specific method call site with its associated informations.
537 class CallSite
538 # The associated node for location
539 var node: ANode
540
541 # The static type of the receiver (possibly unresolved)
542 var recv: MType
543
544 # The module where the callsite is present
545 var mmodule: MModule
546
547 # The anchor to use with `recv` or `msignature`
548 var anchor: nullable MClassType
549
550 # Is the receiver self?
551 # If "for_self", virtual types of the signature are kept
552 # If "not_for_self", virtual type are erased
553 var recv_is_self: Bool
554
555 # The designated method
556 var mproperty: MMethod
557
558 # The statically designated method definition
559 # The most specif one, it is.
560 var mpropdef: MMethodDef
561
562 # The resolved signature for the receiver
563 var msignature: MSignature
564
565 # Is a implicit cast required on erasure typing policy?
566 var erasure_cast: Bool
567
568 # The mapping used on the call to associate arguments to parameters
569 # If null then no specific association is required.
570 var signaturemap: nullable SignatureMap = null
571
572 private fun check_signature(v: TypeVisitor, args: Array[AExpr]): Bool
573 do
574 var map = v.check_signature(self.node, args, self.mproperty, self.msignature)
575 signaturemap = map
576 return map == null
577 end
578 end
579
580 redef class Variable
581 # The declared type of the variable
582 var declared_type: nullable MType
583
584 # Was the variable type-adapted?
585 # This is used to speedup type retrieval while it remains `false`
586 private var is_adapted = false
587 end
588
589 redef class FlowContext
590 # Store changes of types because of type evolution
591 private var vars = new HashMap[Variable, nullable MType]
592
593 # Adapt the variable to a static type
594 # Warning1: do not modify vars directly.
595 # Warning2: sub-flow may have cached a unadapted variable
596 private fun set_var(v: TypeVisitor, variable: Variable, mtype: nullable MType)
597 do
598 if variable.declared_type == mtype and not variable.is_adapted then return
599 if vars.has_key(variable) and vars[variable] == mtype then return
600 self.vars[variable] = mtype
601 v.dirty = true
602 variable.is_adapted = true
603 #node.debug "set {variable} to {mtype or else "X"}"
604 end
605
606 # Look in the flow and previous flow and collect all first reachable type adaptation of a local variable
607 private fun collect_types(variable: Variable): Array[nullable MType]
608 do
609 #node.debug "flow for {variable}"
610 var res = new Array[nullable MType]
611
612 var todo = [self]
613 var seen = new HashSet[FlowContext]
614 while not todo.is_empty do
615 var f = todo.pop
616 if f.is_unreachable then continue
617 if seen.has(f) then continue
618 seen.add f
619
620 if f.vars.has_key(variable) then
621 # Found something. Collect it and do not process further on this path
622 res.add f.vars[variable]
623 #f.node.debug "process {variable}: got {f.vars[variable] or else "X"}"
624 else
625 todo.add_all f.previous
626 todo.add_all f.loops
627 if f.previous.is_empty then
628 # Root flowcontext mean a parameter or something related
629 res.add variable.declared_type
630 #f.node.debug "root process {variable}: got {variable.declared_type or else "X"}"
631 end
632 end
633 end
634 #self.node.debug "##### end flow for {variable}: {res.join(" ")}"
635 return res
636 end
637 end
638
639 redef class APropdef
640 # The entry point of the whole typing analysis
641 fun do_typing(modelbuilder: ModelBuilder)
642 do
643 end
644
645 # The variable associated to the receiver (if any)
646 var selfvariable: nullable Variable
647 end
648
649 redef class AMethPropdef
650 redef fun do_typing(modelbuilder: ModelBuilder)
651 do
652 var nblock = self.n_block
653 if nblock == null then return
654
655 var mpropdef = self.mpropdef
656 if mpropdef == null then return # skip error
657
658 var v = new TypeVisitor(modelbuilder, mpropdef.mclassdef.mmodule, mpropdef)
659 self.selfvariable = v.selfvariable
660
661 var mmethoddef = self.mpropdef.as(not null)
662 var msignature = mmethoddef.msignature
663 if msignature == null then return # skip error
664 for i in [0..msignature.arity[ do
665 var mtype = msignature.mparameters[i].mtype
666 if msignature.vararg_rank == i then
667 var arrayclass = v.get_mclass(self.n_signature.n_params[i], "Array")
668 if arrayclass == null then return # Skip error
669 mtype = arrayclass.get_mtype([mtype])
670 end
671 var variable = self.n_signature.n_params[i].variable
672 assert variable != null
673 variable.declared_type = mtype
674 end
675
676 loop
677 v.dirty = false
678 v.visit_stmt(nblock)
679 if not v.has_loop or not v.dirty then break
680 end
681
682 if not nblock.after_flow_context.is_unreachable and msignature.return_mtype != null then
683 # We reach the end of the function without having a return, it is bad
684 v.error(self, "Error: reached end of function; expected `return` with a value.")
685 end
686 end
687 end
688
689 redef class AAttrPropdef
690 redef fun do_typing(modelbuilder: ModelBuilder)
691 do
692 if not has_value then return
693
694 var mpropdef = self.mpropdef
695 if mpropdef == null then return # skip error
696
697 var v = new TypeVisitor(modelbuilder, mpropdef.mclassdef.mmodule, mpropdef)
698 self.selfvariable = v.selfvariable
699
700 var nexpr = self.n_expr
701 if nexpr != null then
702 var mtype = self.mpropdef.static_mtype
703 v.visit_expr_subtype(nexpr, mtype)
704 end
705 var nblock = self.n_block
706 if nblock != null then
707 v.visit_stmt(nblock)
708 if not nblock.after_flow_context.is_unreachable then
709 # We reach the end of the init without having a return, it is bad
710 v.error(self, "Error: reached end of block; expected `return`.")
711 end
712 end
713 end
714 end
715
716 ###
717
718 redef class AExpr
719 # The static type of the expression.
720 # null if self is a statement or in case of error
721 var mtype: nullable MType = null
722
723 # Is the statement correctly typed?
724 # Used to distinguish errors and statements when `mtype == null`
725 var is_typed: Bool = false
726
727 # If required, the following implicit cast `.as(XXX)`
728 # Such a cast may by required after evaluating the expression when
729 # a unsafe operation is detected (silently accepted by the Nit language).
730 # The attribute is computed by `check_subtype`
731 var implicit_cast_to: nullable MType = null
732
733 # Return the variable read (if any)
734 # Used to perform adaptive typing
735 fun its_variable: nullable Variable do return null
736
737 private fun accept_typing(v: TypeVisitor)
738 do
739 v.error(self, "no implemented accept_typing for {self.class_name}")
740 end
741
742 # Is non-null if `self` is a leaf of a comprehension array construction.
743 # In this case, the enclosing literal array node is designated.
744 # The result of the evaluation of `self` must be
745 # stored inside the designated array (there is an implicit `push`)
746 var comprehension: nullable AArrayExpr = null
747 end
748
749 redef class ABlockExpr
750 redef fun accept_typing(v)
751 do
752 for e in self.n_expr do v.visit_stmt(e)
753 self.is_typed = true
754 end
755
756 # The type of a blockexpr is the one of the last expression (or null if empty)
757 redef fun mtype
758 do
759 if self.n_expr.is_empty then return null
760 return self.n_expr.last.mtype
761 end
762 end
763
764 redef class AVardeclExpr
765 redef fun accept_typing(v)
766 do
767 var variable = self.variable
768 if variable == null then return # Skip error
769
770 var ntype = self.n_type
771 var mtype: nullable MType
772 if ntype == null then
773 mtype = null
774 else
775 mtype = v.resolve_mtype(ntype)
776 if mtype == null then return # Skip error
777 end
778
779 var nexpr = self.n_expr
780 if nexpr != null then
781 if mtype != null then
782 var etype = v.visit_expr_subtype(nexpr, mtype)
783 if etype == mtype then
784 assert ntype != null
785 v.modelbuilder.advice(ntype, "useless-type", "Warning: useless type definition for variable `{variable.name}`")
786 end
787 else
788 mtype = v.visit_expr(nexpr)
789 if mtype == null then return # Skip error
790 end
791 end
792
793 var decltype = mtype
794 if mtype == null or mtype isa MNullType then
795 var objclass = v.get_mclass(self, "Object")
796 if objclass == null then return # skip error
797 decltype = objclass.mclass_type.as_nullable
798 if mtype == null then mtype = decltype
799 end
800
801 variable.declared_type = decltype
802 v.set_variable(self, variable, mtype)
803
804 #debug("var {variable}: {mtype}")
805
806 self.mtype = mtype
807 self.is_typed = true
808 end
809 end
810
811 redef class AVarExpr
812 redef fun its_variable do return self.variable
813 redef fun accept_typing(v)
814 do
815 var variable = self.variable
816 if variable == null then return # Skip error
817
818 var mtype = v.get_variable(self, variable)
819 if mtype != null then
820 #debug("{variable} is {mtype}")
821 else
822 #debug("{variable} is untyped")
823 end
824
825 self.mtype = mtype
826 end
827 end
828
829 redef class AVarAssignExpr
830 redef fun accept_typing(v)
831 do
832 var variable = self.variable
833 assert variable != null
834
835 var mtype = v.visit_expr_subtype(n_value, variable.declared_type)
836
837 v.set_variable(self, variable, mtype)
838
839 self.is_typed = true
840 end
841 end
842
843 redef class AReassignFormExpr
844 # The method designed by the reassign operator.
845 var reassign_callsite: nullable CallSite
846
847 var read_type: nullable MType = null
848
849 # Determine the `reassign_property`
850 # `readtype` is the type of the reading of the left value.
851 # `writetype` is the type of the writing of the left value.
852 # (Because of `ACallReassignExpr`, both can be different.
853 # Return the static type of the value to store.
854 private fun resolve_reassignment(v: TypeVisitor, readtype, writetype: MType): nullable MType
855 do
856 var reassign_name = self.n_assign_op.operator
857
858 self.read_type = readtype
859
860 var callsite = v.get_method(self.n_assign_op, readtype, reassign_name, false)
861 if callsite == null then return null # Skip error
862 self.reassign_callsite = callsite
863
864 var msignature = callsite.msignature
865 var rettype = msignature.return_mtype
866 assert msignature.arity == 1 and rettype != null
867
868 var value_type = v.visit_expr_subtype(self.n_value, msignature.mparameters.first.mtype)
869 if value_type == null then return null # Skip error
870
871 v.check_subtype(self, rettype, writetype, false)
872 return rettype
873 end
874 end
875
876 redef class AVarReassignExpr
877 redef fun accept_typing(v)
878 do
879 var variable = self.variable
880 assert variable != null
881
882 var readtype = v.get_variable(self, variable)
883 if readtype == null then return
884
885 read_type = readtype
886
887 var writetype = variable.declared_type
888 if writetype == null then return
889
890 var rettype = self.resolve_reassignment(v, readtype, writetype)
891
892 v.set_variable(self, variable, rettype)
893
894 self.is_typed = true
895 end
896 end
897
898
899 redef class AContinueExpr
900 redef fun accept_typing(v)
901 do
902 var nexpr = self.n_expr
903 if nexpr != null then
904 v.visit_expr(nexpr)
905 end
906 self.is_typed = true
907 end
908 end
909
910 redef class ABreakExpr
911 redef fun accept_typing(v)
912 do
913 var nexpr = self.n_expr
914 if nexpr != null then
915 v.visit_expr(nexpr)
916 end
917 self.is_typed = true
918 end
919 end
920
921 redef class AReturnExpr
922 redef fun accept_typing(v)
923 do
924 var nexpr = self.n_expr
925 var ret_type
926 var mpropdef = v.mpropdef
927 if mpropdef isa MMethodDef then
928 ret_type = mpropdef.msignature.return_mtype
929 else if mpropdef isa MAttributeDef then
930 ret_type = mpropdef.static_mtype
931 else
932 abort
933 end
934 if nexpr != null then
935 if ret_type != null then
936 v.visit_expr_subtype(nexpr, ret_type)
937 else
938 v.visit_expr(nexpr)
939 v.error(nexpr, "Error: `return` with value in a procedure.")
940 end
941 else if ret_type != null then
942 v.error(self, "Error: `return` without value in a function.")
943 end
944 self.is_typed = true
945 end
946 end
947
948 redef class AAbortExpr
949 redef fun accept_typing(v)
950 do
951 self.is_typed = true
952 end
953 end
954
955 redef class AIfExpr
956 redef fun accept_typing(v)
957 do
958 v.visit_expr_bool(n_expr)
959
960 v.visit_stmt(n_then)
961 v.visit_stmt(n_else)
962
963 self.is_typed = true
964
965 if n_then != null and n_else == null then
966 self.mtype = n_then.mtype
967 end
968 end
969 end
970
971 redef class AIfexprExpr
972 redef fun accept_typing(v)
973 do
974 v.visit_expr_bool(n_expr)
975
976 var t1 = v.visit_expr(n_then)
977 var t2 = v.visit_expr(n_else)
978
979 if t1 == null or t2 == null then
980 return # Skip error
981 end
982
983 var t = v.merge_types(self, [t1, t2])
984 if t == null then
985 v.error(self, "Type Error: ambiguous type `{t1}` vs `{t2}`.")
986 end
987 self.mtype = t
988 end
989 end
990
991 redef class ADoExpr
992 redef fun accept_typing(v)
993 do
994 v.visit_stmt(n_block)
995 self.is_typed = true
996 end
997 end
998
999 redef class AWhileExpr
1000 redef fun accept_typing(v)
1001 do
1002 v.has_loop = true
1003 v.visit_expr_bool(n_expr)
1004 v.visit_stmt(n_block)
1005 self.is_typed = true
1006 end
1007 end
1008
1009 redef class ALoopExpr
1010 redef fun accept_typing(v)
1011 do
1012 v.has_loop = true
1013 v.visit_stmt(n_block)
1014 self.is_typed = true
1015 end
1016 end
1017
1018 redef class AForExpr
1019 var coltype: nullable MClassType
1020
1021 var method_iterator: nullable CallSite
1022 var method_is_ok: nullable CallSite
1023 var method_item: nullable CallSite
1024 var method_next: nullable CallSite
1025 var method_key: nullable CallSite
1026 var method_finish: nullable CallSite
1027
1028 var method_lt: nullable CallSite
1029 var method_successor: nullable CallSite
1030
1031 private fun do_type_iterator(v: TypeVisitor, mtype: MType)
1032 do
1033 if mtype isa MNullType then
1034 v.error(self, "Type Error: `for` cannot iterate over `null`.")
1035 return
1036 end
1037
1038 # get obj class
1039 var objcla = v.get_mclass(self, "Object")
1040 if objcla == null then return
1041
1042 # check iterator method
1043 var itdef = v.get_method(self, mtype, "iterator", n_expr isa ASelfExpr)
1044 if itdef == null then
1045 v.error(self, "Type Error: `for` expects a type providing an `iterator` method, got `{mtype}`.")
1046 return
1047 end
1048 self.method_iterator = itdef
1049
1050 # check that iterator return something
1051 var ittype = itdef.msignature.return_mtype
1052 if ittype == null then
1053 v.error(self, "Type Error: `for` expects the method `iterator` to return an `Iterator` or `MapIterator` type.")
1054 return
1055 end
1056
1057 # get iterator type
1058 var colit_cla = v.try_get_mclass(self, "Iterator")
1059 var mapit_cla = v.try_get_mclass(self, "MapIterator")
1060 var is_col = false
1061 var is_map = false
1062
1063 if colit_cla != null and v.is_subtype(ittype, colit_cla.get_mtype([objcla.mclass_type.as_nullable])) then
1064 # Iterator
1065 var coltype = ittype.supertype_to(v.mmodule, v.anchor, colit_cla)
1066 var variables = self.variables
1067 if variables.length != 1 then
1068 v.error(self, "Type Error: `for` expects only one variable when using `Iterator`.")
1069 else
1070 variables.first.declared_type = coltype.arguments.first
1071 end
1072 is_col = true
1073 end
1074
1075 if mapit_cla != null and v.is_subtype(ittype, mapit_cla.get_mtype([objcla.mclass_type.as_nullable, objcla.mclass_type.as_nullable])) then
1076 # Map Iterator
1077 var coltype = ittype.supertype_to(v.mmodule, v.anchor, mapit_cla)
1078 var variables = self.variables
1079 if variables.length != 2 then
1080 v.error(self, "Type Error: `for` expects two variables when using `MapIterator`.")
1081 else
1082 variables[0].declared_type = coltype.arguments[0]
1083 variables[1].declared_type = coltype.arguments[1]
1084 end
1085 is_map = true
1086 end
1087
1088 if not is_col and not is_map then
1089 v.error(self, "Type Error: `for` expects the method `iterator` to return an `Iterator` or `MapIterator` type.")
1090 return
1091 end
1092
1093 # anchor formal and virtual types
1094 if mtype.need_anchor then mtype = v.anchor_to(mtype)
1095
1096 mtype = mtype.undecorate
1097 self.coltype = mtype.as(MClassType)
1098
1099 # get methods is_ok, next, item
1100 var ikdef = v.get_method(self, ittype, "is_ok", false)
1101 if ikdef == null then
1102 v.error(self, "Type Error: `for` expects a method `is_ok` in type `{ittype}`.")
1103 return
1104 end
1105 self.method_is_ok = ikdef
1106
1107 var itemdef = v.get_method(self, ittype, "item", false)
1108 if itemdef == null then
1109 v.error(self, "Type Error: `for` expects a method `item` in type `{ittype}`.")
1110 return
1111 end
1112 self.method_item = itemdef
1113
1114 var nextdef = v.get_method(self, ittype, "next", false)
1115 if nextdef == null then
1116 v.error(self, "Type Error: `for` expects a method `next` in type {ittype}.")
1117 return
1118 end
1119 self.method_next = nextdef
1120
1121 self.method_finish = v.try_get_method(self, ittype, "finish", false)
1122
1123 if is_map then
1124 var keydef = v.get_method(self, ittype, "key", false)
1125 if keydef == null then
1126 v.error(self, "Type Error: `for` expects a method `key` in type `{ittype}`.")
1127 return
1128 end
1129 self.method_key = keydef
1130 end
1131
1132 if self.variables.length == 1 and n_expr isa ARangeExpr then
1133 var variable = variables.first
1134 var vtype = variable.declared_type.as(not null)
1135
1136 if n_expr isa AOrangeExpr then
1137 self.method_lt = v.get_method(self, vtype, "<", false)
1138 else
1139 self.method_lt = v.get_method(self, vtype, "<=", false)
1140 end
1141
1142 self.method_successor = v.get_method(self, vtype, "successor", false)
1143 end
1144 end
1145
1146 redef fun accept_typing(v)
1147 do
1148 v.has_loop = true
1149 var mtype = v.visit_expr(n_expr)
1150 if mtype == null then return
1151
1152 self.do_type_iterator(v, mtype)
1153
1154 v.visit_stmt(n_block)
1155
1156 self.mtype = n_block.mtype
1157 self.is_typed = true
1158 end
1159 end
1160
1161 redef class AWithExpr
1162 var method_start: nullable CallSite
1163 var method_finish: nullable CallSite
1164
1165 redef fun accept_typing(v: TypeVisitor)
1166 do
1167 var mtype = v.visit_expr(n_expr)
1168 if mtype == null then return
1169
1170 method_start = v.get_method(self, mtype, "start", n_expr isa ASelfExpr)
1171 method_finish = v.get_method(self, mtype, "finish", n_expr isa ASelfExpr)
1172
1173 v.visit_stmt(n_block)
1174 self.mtype = n_block.mtype
1175 self.is_typed = true
1176 end
1177 end
1178
1179 redef class AAssertExpr
1180 redef fun accept_typing(v)
1181 do
1182 v.visit_expr_bool(n_expr)
1183
1184 v.visit_stmt(n_else)
1185 self.is_typed = true
1186 end
1187 end
1188
1189 redef class AOrExpr
1190 redef fun accept_typing(v)
1191 do
1192 v.visit_expr_bool(n_expr)
1193 v.visit_expr_bool(n_expr2)
1194 self.mtype = v.type_bool(self)
1195 end
1196 end
1197
1198 redef class AImpliesExpr
1199 redef fun accept_typing(v)
1200 do
1201 v.visit_expr_bool(n_expr)
1202 v.visit_expr_bool(n_expr2)
1203 self.mtype = v.type_bool(self)
1204 end
1205 end
1206
1207 redef class AAndExpr
1208 redef fun accept_typing(v)
1209 do
1210 v.visit_expr_bool(n_expr)
1211 v.visit_expr_bool(n_expr2)
1212 self.mtype = v.type_bool(self)
1213 end
1214 end
1215
1216
1217 redef class ANotExpr
1218 redef fun accept_typing(v)
1219 do
1220 v.visit_expr_bool(n_expr)
1221 self.mtype = v.type_bool(self)
1222 end
1223 end
1224
1225 redef class AOrElseExpr
1226 redef fun accept_typing(v)
1227 do
1228 var t1 = v.visit_expr(n_expr)
1229 var t2 = v.visit_expr(n_expr2)
1230
1231 if t1 == null or t2 == null then
1232 return # Skip error
1233 end
1234
1235 if t1 isa MNullType then
1236 v.error(n_expr, "Type Error: `or else` on `null`.")
1237 else if v.check_can_be_null(n_expr, t1) then
1238 t1 = t1.as_notnull
1239 end
1240
1241 var t = v.merge_types(self, [t1, t2])
1242 if t == null then
1243 var c = v.get_mclass(self, "Object")
1244 if c == null then return # forward error
1245 t = c.mclass_type
1246 if v.can_be_null(t2) then
1247 t = t.as_nullable
1248 end
1249 #v.error(self, "Type Error: ambiguous type {t1} vs {t2}")
1250 end
1251 self.mtype = t
1252 end
1253 end
1254
1255 redef class ATrueExpr
1256 redef fun accept_typing(v)
1257 do
1258 self.mtype = v.type_bool(self)
1259 end
1260 end
1261
1262 redef class AFalseExpr
1263 redef fun accept_typing(v)
1264 do
1265 self.mtype = v.type_bool(self)
1266 end
1267 end
1268
1269 redef class AIntExpr
1270 redef fun accept_typing(v)
1271 do
1272 var mclass = v.get_mclass(self, "Int")
1273 if mclass == null then return # Forward error
1274 self.mtype = mclass.mclass_type
1275 end
1276 end
1277
1278 redef class AFloatExpr
1279 redef fun accept_typing(v)
1280 do
1281 var mclass = v.get_mclass(self, "Float")
1282 if mclass == null then return # Forward error
1283 self.mtype = mclass.mclass_type
1284 end
1285 end
1286
1287 redef class ACharExpr
1288 redef fun accept_typing(v)
1289 do
1290 var mclass = v.get_mclass(self, "Char")
1291 if mclass == null then return # Forward error
1292 self.mtype = mclass.mclass_type
1293 end
1294 end
1295
1296 redef class AStringFormExpr
1297 redef fun accept_typing(v)
1298 do
1299 var mclass = v.get_mclass(self, "String")
1300 if mclass == null then return # Forward error
1301 self.mtype = mclass.mclass_type
1302 end
1303 end
1304
1305 redef class ASuperstringExpr
1306 redef fun accept_typing(v)
1307 do
1308 var mclass = v.get_mclass(self, "String")
1309 if mclass == null then return # Forward error
1310 self.mtype = mclass.mclass_type
1311 var objclass = v.get_mclass(self, "Object")
1312 if objclass == null then return # Forward error
1313 var objtype = objclass.mclass_type
1314 for nexpr in self.n_exprs do
1315 v.visit_expr_subtype(nexpr, objtype)
1316 end
1317 end
1318 end
1319
1320 redef class AArrayExpr
1321 # The `with_capacity` method on Array
1322 var with_capacity_callsite: nullable CallSite
1323
1324 # The `push` method on arrays
1325 var push_callsite: nullable CallSite
1326
1327 # The element of each type
1328 var element_mtype: nullable MType
1329
1330 # Set that `self` is a part of comprehension array `na`
1331 # If `self` is a `for`, or a `if`, then `set_comprehension` is recursively applied.
1332 private fun set_comprehension(n: nullable AExpr)
1333 do
1334 if n == null then
1335 return
1336 else if n isa AForExpr then
1337 set_comprehension(n.n_block)
1338 else if n isa AIfExpr then
1339 set_comprehension(n.n_then)
1340 set_comprehension(n.n_else)
1341 else
1342 # is a leave
1343 n.comprehension = self
1344 end
1345 end
1346 redef fun accept_typing(v)
1347 do
1348 var mtype: nullable MType = null
1349 var ntype = self.n_type
1350 if ntype != null then
1351 mtype = v.resolve_mtype(ntype)
1352 if mtype == null then return # Skip error
1353 end
1354 var mtypes = new Array[nullable MType]
1355 var useless = false
1356 for e in self.n_exprs do
1357 var t = v.visit_expr(e)
1358 if t == null then
1359 return # Skip error
1360 end
1361 set_comprehension(e)
1362 if mtype != null then
1363 if v.check_subtype(e, t, mtype, false) == null then return # Forward error
1364 if t == mtype then useless = true
1365 else
1366 mtypes.add(t)
1367 end
1368 end
1369 if mtype == null then
1370 # Ensure monotony for type adaptation on loops
1371 if self.element_mtype != null then mtypes.add self.element_mtype
1372 mtype = v.merge_types(self, mtypes)
1373 end
1374 if mtype == null or mtype isa MNullType then
1375 v.error(self, "Type Error: ambiguous array type {mtypes.join(" ")}")
1376 return
1377 end
1378 if useless then
1379 assert ntype != null
1380 v.modelbuilder.warning(ntype, "useless-type", "Warning: useless type declaration `{mtype}` in literal Array since it can be inferred from the elements type.")
1381 end
1382
1383 self.element_mtype = mtype
1384
1385 var mclass = v.get_mclass(self, "Array")
1386 if mclass == null then return # Forward error
1387 var array_mtype = mclass.get_mtype([mtype])
1388
1389 with_capacity_callsite = v.get_method(self, array_mtype, "with_capacity", false)
1390 push_callsite = v.get_method(self, array_mtype, "push", false)
1391
1392 self.mtype = array_mtype
1393 end
1394 end
1395
1396 redef class ARangeExpr
1397 var init_callsite: nullable CallSite
1398
1399 redef fun accept_typing(v)
1400 do
1401 var discrete_class = v.get_mclass(self, "Discrete")
1402 if discrete_class == null then return # Forward error
1403 var discrete_type = discrete_class.intro.bound_mtype
1404 var t1 = v.visit_expr_subtype(self.n_expr, discrete_type)
1405 var t2 = v.visit_expr_subtype(self.n_expr2, discrete_type)
1406 if t1 == null or t2 == null then return
1407 var mclass = v.get_mclass(self, "Range")
1408 if mclass == null then return # Forward error
1409 var mtype
1410 if v.is_subtype(t1, t2) then
1411 mtype = mclass.get_mtype([t2])
1412 else if v.is_subtype(t2, t1) then
1413 mtype = mclass.get_mtype([t1])
1414 else
1415 v.error(self, "Type Error: cannot create range: `{t1}` vs `{t2}`.")
1416 return
1417 end
1418
1419 self.mtype = mtype
1420
1421 # get the constructor
1422 var callsite
1423 if self isa ACrangeExpr then
1424 callsite = v.get_method(self, mtype, "init", false)
1425 else if self isa AOrangeExpr then
1426 callsite = v.get_method(self, mtype, "without_last", false)
1427 else
1428 abort
1429 end
1430 init_callsite = callsite
1431 end
1432 end
1433
1434 redef class ANullExpr
1435 redef fun accept_typing(v)
1436 do
1437 self.mtype = v.mmodule.model.null_type
1438 end
1439 end
1440
1441 redef class AIsaExpr
1442 # The static type to cast to.
1443 # (different from the static type of the expression that is `Bool`).
1444 var cast_type: nullable MType
1445 redef fun accept_typing(v)
1446 do
1447 var mtype = v.visit_expr_cast(self, self.n_expr, self.n_type)
1448 self.cast_type = mtype
1449
1450 var variable = self.n_expr.its_variable
1451 if variable != null then
1452 #var orig = self.n_expr.mtype
1453 #var from = if orig != null then orig.to_s else "invalid"
1454 #var to = if mtype != null then mtype.to_s else "invalid"
1455 #debug("adapt {variable}: {from} -> {to}")
1456 self.after_flow_context.when_true.set_var(v, variable, mtype)
1457 end
1458
1459 self.mtype = v.type_bool(self)
1460 end
1461 end
1462
1463 redef class AAsCastExpr
1464 redef fun accept_typing(v)
1465 do
1466 self.mtype = v.visit_expr_cast(self, self.n_expr, self.n_type)
1467 end
1468 end
1469
1470 redef class AAsNotnullExpr
1471 redef fun accept_typing(v)
1472 do
1473 var mtype = v.visit_expr(self.n_expr)
1474 if mtype == null then return # Forward error
1475
1476 if mtype isa MNullType then
1477 v.error(self, "Type Error: `as(not null)` on `null`.")
1478 return
1479 end
1480
1481 if v.check_can_be_null(n_expr, mtype) then
1482 mtype = mtype.as_notnull
1483 end
1484
1485 self.mtype = mtype
1486 end
1487 end
1488
1489 redef class AParExpr
1490 redef fun accept_typing(v)
1491 do
1492 self.mtype = v.visit_expr(self.n_expr)
1493 end
1494 end
1495
1496 redef class AOnceExpr
1497 redef fun accept_typing(v)
1498 do
1499 self.mtype = v.visit_expr(self.n_expr)
1500 end
1501 end
1502
1503 redef class ASelfExpr
1504 redef var its_variable: nullable Variable
1505 redef fun accept_typing(v)
1506 do
1507 if v.is_toplevel_context and not self isa AImplicitSelfExpr then
1508 v.error(self, "Error: `self` cannot be used in top-level method.")
1509 end
1510 var variable = v.selfvariable
1511 self.its_variable = variable
1512 self.mtype = v.get_variable(self, variable)
1513 end
1514 end
1515
1516 redef class AImplicitSelfExpr
1517 # Is the implicit receiver `sys`?
1518 #
1519 # By default, the implicit receiver is `self`.
1520 # But when there is not method for `self`, `sys` is used as a fall-back.
1521 # Is this case this flag is set to `true`.
1522 var is_sys = false
1523 end
1524
1525 ## MESSAGE SENDING AND PROPERTY
1526
1527 redef class ASendExpr
1528 # The property invoked by the send.
1529 var callsite: nullable CallSite
1530
1531 redef fun accept_typing(v)
1532 do
1533 var nrecv = self.n_expr
1534 var recvtype = v.visit_expr(nrecv)
1535 var name = self.property_name
1536 var node = self.property_node
1537
1538 if recvtype == null then return # Forward error
1539
1540 var callsite = null
1541 var unsafe_type = v.anchor_to(recvtype)
1542 var mproperty = v.try_get_mproperty_by_name2(node, unsafe_type, name)
1543 if mproperty == null and nrecv isa AImplicitSelfExpr then
1544 # Special fall-back search in `sys` when noting found in the implicit receiver.
1545 var sysclass = v.try_get_mclass(node, "Sys")
1546 if sysclass != null then
1547 var systype = sysclass.mclass_type
1548 mproperty = v.try_get_mproperty_by_name2(node, systype, name)
1549 if mproperty != null then
1550 callsite = v.get_method(node, systype, name, false)
1551 if callsite == null then return # Forward error
1552 # Update information, we are looking at `sys` now, not `self`
1553 nrecv.is_sys = true
1554 nrecv.its_variable = null
1555 nrecv.mtype = systype
1556 recvtype = systype
1557 end
1558 end
1559 end
1560 if callsite == null then
1561 # If still nothing, just exit
1562 callsite = v.get_method(node, recvtype, name, nrecv isa ASelfExpr)
1563 if callsite == null then return
1564 end
1565
1566 self.callsite = callsite
1567 var msignature = callsite.msignature
1568
1569 var args = compute_raw_arguments
1570
1571 callsite.check_signature(v, args)
1572
1573 if callsite.mproperty.is_init then
1574 var vmpropdef = v.mpropdef
1575 if not (vmpropdef isa MMethodDef and vmpropdef.mproperty.is_init) then
1576 v.error(node, "Error: an `init` can only be called from another `init`.")
1577 end
1578 if vmpropdef isa MMethodDef and vmpropdef.mproperty.is_root_init and not callsite.mproperty.is_root_init then
1579 v.error(node, "Error: `{vmpropdef}` cannot call a factory `{callsite.mproperty}`.")
1580 end
1581 end
1582
1583 var ret = msignature.return_mtype
1584 if ret != null then
1585 self.mtype = ret
1586 else
1587 self.is_typed = true
1588 end
1589 end
1590
1591 # The name of the property
1592 # Each subclass simply provide the correct name.
1593 private fun property_name: String is abstract
1594
1595 # The node identifying the name (id, operator, etc) for messages.
1596 #
1597 # Is `self` by default
1598 private fun property_node: ANode do return self
1599
1600 # An array of all arguments (excluding self)
1601 fun raw_arguments: Array[AExpr] do return compute_raw_arguments
1602
1603 private fun compute_raw_arguments: Array[AExpr] is abstract
1604 end
1605
1606 redef class ABinopExpr
1607 redef fun compute_raw_arguments do return [n_expr2]
1608 redef fun property_name do return operator
1609 redef fun property_node do return n_op
1610 end
1611 redef class AEqExpr
1612 redef fun accept_typing(v)
1613 do
1614 super
1615 v.null_test(self)
1616 end
1617 end
1618 redef class ANeExpr
1619 redef fun accept_typing(v)
1620 do
1621 super
1622 v.null_test(self)
1623 end
1624 end
1625
1626 redef class AUplusExpr
1627 redef fun property_name do return "unary +"
1628 redef fun compute_raw_arguments do return new Array[AExpr]
1629 end
1630
1631 redef class AUminusExpr
1632 redef fun property_name do return "unary -"
1633 redef fun compute_raw_arguments do return new Array[AExpr]
1634 end
1635
1636
1637 redef class ACallExpr
1638 redef fun property_name do return n_id.text
1639 redef fun property_node do return n_id
1640 redef fun compute_raw_arguments do return n_args.to_a
1641 end
1642
1643 redef class ACallAssignExpr
1644 redef fun property_name do return n_id.text + "="
1645 redef fun property_node do return n_id
1646 redef fun compute_raw_arguments
1647 do
1648 var res = n_args.to_a
1649 res.add(n_value)
1650 return res
1651 end
1652 end
1653
1654 redef class ABraExpr
1655 redef fun property_name do return "[]"
1656 redef fun compute_raw_arguments do return n_args.to_a
1657 end
1658
1659 redef class ABraAssignExpr
1660 redef fun property_name do return "[]="
1661 redef fun compute_raw_arguments
1662 do
1663 var res = n_args.to_a
1664 res.add(n_value)
1665 return res
1666 end
1667 end
1668
1669 redef class ASendReassignFormExpr
1670 # The property invoked for the writing
1671 var write_callsite: nullable CallSite
1672
1673 redef fun accept_typing(v)
1674 do
1675 var recvtype = v.visit_expr(self.n_expr)
1676 var name = self.property_name
1677 var node = self.property_node
1678
1679 if recvtype == null then return # Forward error
1680
1681 var for_self = self.n_expr isa ASelfExpr
1682 var callsite = v.get_method(node, recvtype, name, for_self)
1683
1684 if callsite == null then return
1685 self.callsite = callsite
1686
1687 var args = compute_raw_arguments
1688
1689 callsite.check_signature(v, args)
1690
1691 var readtype = callsite.msignature.return_mtype
1692 if readtype == null then
1693 v.error(node, "Error: `{name}` is not a function.")
1694 return
1695 end
1696
1697 var wcallsite = v.get_method(node, recvtype, name + "=", self.n_expr isa ASelfExpr)
1698 if wcallsite == null then return
1699 self.write_callsite = wcallsite
1700
1701 var wtype = self.resolve_reassignment(v, readtype, wcallsite.msignature.mparameters.last.mtype)
1702 if wtype == null then return
1703
1704 args = args.to_a # duplicate so raw_arguments keeps only the getter args
1705 args.add(self.n_value)
1706 wcallsite.check_signature(v, args)
1707
1708 self.is_typed = true
1709 end
1710 end
1711
1712 redef class ACallReassignExpr
1713 redef fun property_name do return n_id.text
1714 redef fun property_node do return n_id
1715 redef fun compute_raw_arguments do return n_args.to_a
1716 end
1717
1718 redef class ABraReassignExpr
1719 redef fun property_name do return "[]"
1720 redef fun compute_raw_arguments do return n_args.to_a
1721 end
1722
1723 redef class AInitExpr
1724 redef fun property_name do return "init"
1725 redef fun property_node do return n_kwinit
1726 redef fun compute_raw_arguments do return n_args.to_a
1727 end
1728
1729 redef class AExprs
1730 fun to_a: Array[AExpr] do return self.n_exprs.to_a
1731 end
1732
1733 ###
1734
1735 redef class ASuperExpr
1736 # The method to call if the super is in fact a 'super init call'
1737 # Note: if the super is a normal call-next-method, then this attribute is null
1738 var callsite: nullable CallSite
1739
1740 # The method to call is the super is a standard `call-next-method` super-call
1741 # Note: if the super is a special super-init-call, then this attribute is null
1742 var mpropdef: nullable MMethodDef
1743
1744 redef fun accept_typing(v)
1745 do
1746 var anchor = v.anchor
1747 assert anchor != null
1748 var recvtype = v.get_variable(self, v.selfvariable)
1749 assert recvtype != null
1750 var mproperty = v.mpropdef.mproperty
1751 if not mproperty isa MMethod then
1752 v.error(self, "Error: `super` only usable in a `method`.")
1753 return
1754 end
1755 var superprops = mproperty.lookup_super_definitions(v.mmodule, anchor)
1756 if superprops.length == 0 then
1757 if mproperty.is_init and v.mpropdef.is_intro then
1758 process_superinit(v)
1759 return
1760 end
1761 v.error(self, "Error: no super method to call for `{mproperty}`.")
1762 return
1763 end
1764 # FIXME: covariance of return type in linear extension?
1765 var superprop = superprops.first
1766
1767 var msignature = superprop.msignature.as(not null)
1768 msignature = v.resolve_for(msignature, recvtype, true).as(MSignature)
1769 var args = self.n_args.to_a
1770 if args.length > 0 then
1771 signaturemap = v.check_signature(self, args, mproperty, msignature)
1772 end
1773 self.mtype = msignature.return_mtype
1774 self.is_typed = true
1775 v.mpropdef.has_supercall = true
1776 mpropdef = v.mpropdef.as(MMethodDef)
1777 end
1778
1779 # The mapping used on the call to associate arguments to parameters.
1780 # If null then no specific association is required.
1781 var signaturemap: nullable SignatureMap
1782
1783 private fun process_superinit(v: TypeVisitor)
1784 do
1785 var anchor = v.anchor
1786 assert anchor != null
1787 var recvtype = v.get_variable(self, v.selfvariable)
1788 assert recvtype != null
1789 var mpropdef = v.mpropdef
1790 assert mpropdef isa MMethodDef
1791 var mproperty = mpropdef.mproperty
1792 var superprop: nullable MMethodDef = null
1793 for msupertype in mpropdef.mclassdef.supertypes do
1794 msupertype = msupertype.anchor_to(v.mmodule, anchor)
1795 var errcount = v.modelbuilder.toolcontext.error_count
1796 var candidate = v.try_get_mproperty_by_name2(self, msupertype, mproperty.name).as(nullable MMethod)
1797 if candidate == null then
1798 if v.modelbuilder.toolcontext.error_count > errcount then return # Forward error
1799 continue # Try next super-class
1800 end
1801 if superprop != null and candidate.is_root_init then
1802 continue
1803 end
1804 if superprop != null and superprop.mproperty != candidate and not superprop.mproperty.is_root_init then
1805 v.error(self, "Error: conflicting super constructor to call for `{mproperty}`: `{candidate.full_name}`, `{superprop.mproperty.full_name}`")
1806 return
1807 end
1808 var candidatedefs = candidate.lookup_definitions(v.mmodule, anchor)
1809 if superprop != null and superprop.mproperty == candidate then
1810 if superprop == candidatedefs.first then continue
1811 candidatedefs.add(superprop)
1812 end
1813 if candidatedefs.length > 1 then
1814 v.error(self, "Error: conflicting property definitions for property `{mproperty}` in `{recvtype}`: {candidatedefs.join(", ")}")
1815 return
1816 end
1817 superprop = candidatedefs.first
1818 end
1819 if superprop == null then
1820 v.error(self, "Error: no super method to call for `{mproperty}`.")
1821 return
1822 end
1823
1824 var msignature = superprop.new_msignature or else superprop.msignature.as(not null)
1825 msignature = v.resolve_for(msignature, recvtype, true).as(MSignature)
1826
1827 var callsite = new CallSite(self, recvtype, v.mmodule, v.anchor, true, superprop.mproperty, superprop, msignature, false)
1828 self.callsite = callsite
1829
1830 var args = self.n_args.to_a
1831 if args.length > 0 then
1832 callsite.check_signature(v, args)
1833 else
1834 # Check there is at least enough parameters
1835 if mpropdef.msignature.arity < msignature.arity then
1836 v.error(self, "Error: not enough implicit arguments to pass. Got `{mpropdef.msignature.arity}`, expected at least `{msignature.arity}`. Signature is `{msignature}`.")
1837 return
1838 end
1839 # Check that each needed parameter is conform
1840 var i = 0
1841 for sp in msignature.mparameters do
1842 var p = mpropdef.msignature.mparameters[i]
1843 if not v.is_subtype(p.mtype, sp.mtype) then
1844 v.error(self, "Type Error: expected argument #{i} of type `{sp.mtype}`, got implicit argument `{p.name}` of type `{p.mtype}`. Signature is {msignature}")
1845 return
1846 end
1847 i += 1
1848 end
1849 end
1850
1851 self.is_typed = true
1852 end
1853 end
1854
1855 ####
1856
1857 redef class ANewExpr
1858 # The constructor invoked by the new.
1859 var callsite: nullable CallSite
1860
1861 # The designated type
1862 var recvtype: nullable MClassType
1863
1864 redef fun accept_typing(v)
1865 do
1866 var recvtype = v.resolve_mtype(self.n_type)
1867 if recvtype == null then return
1868
1869 if not recvtype isa MClassType then
1870 if recvtype isa MNullableType then
1871 v.error(self, "Type Error: cannot instantiate the nullable type `{recvtype}`.")
1872 return
1873 else if recvtype isa MFormalType then
1874 v.error(self, "Type Error: cannot instantiate the formal type `{recvtype}`.")
1875 return
1876 else
1877 v.error(self, "Type Error: cannot instantiate the type `{recvtype}`.")
1878 return
1879 end
1880 end
1881
1882 self.recvtype = recvtype
1883 var kind = recvtype.mclass.kind
1884
1885 var name: String
1886 var nid = self.n_id
1887 var node: ANode
1888 if nid != null then
1889 name = nid.text
1890 node = nid
1891 else
1892 name = "new"
1893 node = self.n_kwnew
1894 end
1895 if name == "intern" then
1896 if kind != concrete_kind then
1897 v.error(self, "Type Error: cannot instantiate {kind} {recvtype}.")
1898 return
1899 end
1900 if n_args.n_exprs.not_empty then
1901 v.error(n_args, "Type Error: the intern constructor expects no arguments.")
1902 return
1903 end
1904 # Our job is done
1905 self.mtype = recvtype
1906 return
1907 end
1908
1909 var callsite = v.get_method(node, recvtype, name, false)
1910 if callsite == null then return
1911
1912 if not callsite.mproperty.is_new then
1913 if kind != concrete_kind then
1914 v.error(self, "Type Error: cannot instantiate {kind} `{recvtype}`.")
1915 return
1916 end
1917 self.mtype = recvtype
1918 else
1919 self.mtype = callsite.msignature.return_mtype
1920 assert self.mtype != null
1921 end
1922
1923 self.callsite = callsite
1924
1925 if not callsite.mproperty.is_init_for(recvtype.mclass) then
1926 v.error(self, "Error: `{name}` is not a constructor.")
1927 return
1928 end
1929
1930 var args = n_args.to_a
1931 callsite.check_signature(v, args)
1932 end
1933 end
1934
1935 ####
1936
1937 redef class AAttrFormExpr
1938 # The attribute accessed.
1939 var mproperty: nullable MAttribute
1940
1941 # The static type of the attribute.
1942 var attr_type: nullable MType
1943
1944 # Resolve the attribute accessed.
1945 private fun resolve_property(v: TypeVisitor)
1946 do
1947 var recvtype = v.visit_expr(self.n_expr)
1948 if recvtype == null then return # Skip error
1949 var node = self.n_id
1950 var name = node.text
1951 if recvtype isa MNullType then
1952 v.error(node, "Error: attribute `{name}` access on `null`.")
1953 return
1954 end
1955
1956 var unsafe_type = v.anchor_to(recvtype)
1957 var mproperty = v.try_get_mproperty_by_name2(node, unsafe_type, name)
1958 if mproperty == null then
1959 v.modelbuilder.error(node, "Error: attribute `{name}` does not exist in `{recvtype}`.")
1960 return
1961 end
1962 assert mproperty isa MAttribute
1963 self.mproperty = mproperty
1964
1965 var mpropdefs = mproperty.lookup_definitions(v.mmodule, unsafe_type)
1966 assert mpropdefs.length == 1
1967 var mpropdef = mpropdefs.first
1968 var attr_type = mpropdef.static_mtype
1969 if attr_type == null then return # skip error
1970 attr_type = v.resolve_for(attr_type, recvtype, self.n_expr isa ASelfExpr)
1971 self.attr_type = attr_type
1972 end
1973 end
1974
1975 redef class AAttrExpr
1976 redef fun accept_typing(v)
1977 do
1978 self.resolve_property(v)
1979 self.mtype = self.attr_type
1980 end
1981 end
1982
1983
1984 redef class AAttrAssignExpr
1985 redef fun accept_typing(v)
1986 do
1987 self.resolve_property(v)
1988 var mtype = self.attr_type
1989
1990 v.visit_expr_subtype(self.n_value, mtype)
1991 self.is_typed = true
1992 end
1993 end
1994
1995 redef class AAttrReassignExpr
1996 redef fun accept_typing(v)
1997 do
1998 self.resolve_property(v)
1999 var mtype = self.attr_type
2000 if mtype == null then return # Skip error
2001
2002 self.resolve_reassignment(v, mtype, mtype)
2003
2004 self.is_typed = true
2005 end
2006 end
2007
2008 redef class AIssetAttrExpr
2009 redef fun accept_typing(v)
2010 do
2011 self.resolve_property(v)
2012 var mtype = self.attr_type
2013 if mtype == null then return # Skip error
2014
2015 var recvtype = self.n_expr.mtype.as(not null)
2016 var bound = v.resolve_for(mtype, recvtype, false)
2017 if bound isa MNullableType then
2018 v.error(n_id, "Type Error: `isset` on a nullable attribute.")
2019 end
2020 self.mtype = v.type_bool(self)
2021 end
2022 end
2023
2024 redef class AVarargExpr
2025 redef fun accept_typing(v)
2026 do
2027 # This kind of pseudo-expression can be only processed trough a signature
2028 # See `check_signature`
2029 # Other cases are a syntax error.
2030 v.error(self, "Syntax Error: unexpected `...`.")
2031 end
2032 end
2033
2034 ###
2035
2036 redef class ADebugTypeExpr
2037 redef fun accept_typing(v)
2038 do
2039 var expr = v.visit_expr(self.n_expr)
2040 if expr == null then return
2041 var unsafe = v.anchor_to(expr)
2042 var ntype = self.n_type
2043 var mtype = v.resolve_mtype(ntype)
2044 if mtype != null and mtype != expr then
2045 var umtype = v.anchor_to(mtype)
2046 v.modelbuilder.warning(self, "debug", "Found type {expr} (-> {unsafe}), expected {mtype} (-> {umtype})")
2047 end
2048 self.is_typed = true
2049 end
2050 end