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