doc: use operator `implies` in documentation
[nit.git] / src / model / model.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 # Object model of the Nit language
18 #
19 # This module define the entities of the Nit meta-model like modules,
20 # classes, types and properties
21 #
22 # It also provide an API to build and query models.
23 #
24 # All model classes starts with the M letter (`MModule`, `MClass`, etc.)
25 #
26 # TODO: better doc
27 #
28 # TODO: liearization, closures, extern stuff
29 # FIXME: better handling of the types
30 module model
31
32 import poset
33 import location
34 import model_base
35 private import more_collections
36
37 redef class Model
38 # All known classes
39 var mclasses: Array[MClass] = new Array[MClass]
40
41 # All known properties
42 var mproperties: Array[MProperty] = new Array[MProperty]
43
44 # Hierarchy of class definition.
45 #
46 # Each classdef is associated with its super-classdefs in regard to
47 # its module of definition.
48 var mclassdef_hierarchy: POSet[MClassDef] = new POSet[MClassDef]
49
50 # Class-type hierarchy restricted to the introduction.
51 #
52 # The idea is that what is true on introduction is always true whatever
53 # the module considered.
54 # Therefore, this hierarchy is used for a fast positive subtype check.
55 #
56 # This poset will evolve in a monotonous way:
57 # * Two non connected nodes will remain unconnected
58 # * New nodes can appear with new edges
59 private var intro_mtype_specialization_hierarchy: POSet[MClassType] = new POSet[MClassType]
60
61 # Global overlapped class-type hierarchy.
62 # The hierarchy when all modules are combined.
63 # Therefore, this hierarchy is used for a fast negative subtype check.
64 #
65 # This poset will evolve in an anarchic way. Loops can even be created.
66 #
67 # FIXME decide what to do on loops
68 private var full_mtype_specialization_hierarchy: POSet[MClassType] = new POSet[MClassType]
69
70 # Collections of classes grouped by their short name
71 private var mclasses_by_name: MultiHashMap[String, MClass] = new MultiHashMap[String, MClass]
72
73 # Return all class named `name`.
74 #
75 # If such a class does not exist, null is returned
76 # (instead of an empty array)
77 #
78 # Visibility or modules are not considered
79 fun get_mclasses_by_name(name: String): nullable Array[MClass]
80 do
81 if mclasses_by_name.has_key(name) then
82 return mclasses_by_name[name]
83 else
84 return null
85 end
86 end
87
88 # Collections of properties grouped by their short name
89 private var mproperties_by_name: MultiHashMap[String, MProperty] = new MultiHashMap[String, MProperty]
90
91 # Return all properties named `name`.
92 #
93 # If such a property does not exist, null is returned
94 # (instead of an empty array)
95 #
96 # Visibility or modules are not considered
97 fun get_mproperties_by_name(name: String): nullable Array[MProperty]
98 do
99 if not mproperties_by_name.has_key(name) then
100 return null
101 else
102 return mproperties_by_name[name]
103 end
104 end
105
106 # The only null type
107 var null_type: MNullType = new MNullType(self)
108 end
109
110 redef class MModule
111 # All the classes introduced in the module
112 var intro_mclasses: Array[MClass] = new Array[MClass]
113
114 # All the class definitions of the module
115 # (introduction and refinement)
116 var mclassdefs: Array[MClassDef] = new Array[MClassDef]
117
118 # Does the current module has a given class `mclass`?
119 # Return true if the mmodule introduces, refines or imports a class.
120 # Visibility is not considered.
121 fun has_mclass(mclass: MClass): Bool
122 do
123 return self.in_importation <= mclass.intro_mmodule
124 end
125
126 # Full hierarchy of introduced ans imported classes.
127 #
128 # Create a new hierarchy got by flattening the classes for the module
129 # and its imported modules.
130 # Visibility is not considered.
131 #
132 # Note: this function is expensive and is usually used for the main
133 # module of a program only. Do not use it to do you own subtype
134 # functions.
135 fun flatten_mclass_hierarchy: POSet[MClass]
136 do
137 var res = self.flatten_mclass_hierarchy_cache
138 if res != null then return res
139 res = new POSet[MClass]
140 for m in self.in_importation.greaters do
141 for cd in m.mclassdefs do
142 var c = cd.mclass
143 res.add_node(c)
144 for s in cd.supertypes do
145 res.add_edge(c, s.mclass)
146 end
147 end
148 end
149 self.flatten_mclass_hierarchy_cache = res
150 return res
151 end
152
153 # Sort a given array of classes using the linerarization order of the module
154 # The most general is first, the most specific is last
155 fun linearize_mclasses(mclasses: Array[MClass])
156 do
157 self.flatten_mclass_hierarchy.sort(mclasses)
158 end
159
160 # Sort a given array of class definitions using the linerarization order of the module
161 # the refinement link is stronger than the specialisation link
162 # The most general is first, the most specific is last
163 fun linearize_mclassdefs(mclassdefs: Array[MClassDef])
164 do
165 var sorter = new MClassDefSorter(self)
166 sorter.sort(mclassdefs)
167 end
168
169 # Sort a given array of property definitions using the linerarization order of the module
170 # the refinement link is stronger than the specialisation link
171 # The most general is first, the most specific is last
172 fun linearize_mpropdefs(mpropdefs: Array[MPropDef])
173 do
174 var sorter = new MPropDefSorter(self)
175 sorter.sort(mpropdefs)
176 end
177
178 private var flatten_mclass_hierarchy_cache: nullable POSet[MClass] = null
179
180 # The primitive type `Object`, the root of the class hierarchy
181 fun object_type: MClassType
182 do
183 var res = self.object_type_cache
184 if res != null then return res
185 res = self.get_primitive_class("Object").mclass_type
186 self.object_type_cache = res
187 return res
188 end
189
190 private var object_type_cache: nullable MClassType
191
192 # The primitive type `Bool`
193 fun bool_type: MClassType
194 do
195 var res = self.bool_type_cache
196 if res != null then return res
197 res = self.get_primitive_class("Bool").mclass_type
198 self.bool_type_cache = res
199 return res
200 end
201
202 private var bool_type_cache: nullable MClassType
203
204 # The primitive type `Sys`, the main type of the program, if any
205 fun sys_type: nullable MClassType
206 do
207 var clas = self.model.get_mclasses_by_name("Sys")
208 if clas == null then return null
209 return get_primitive_class("Sys").mclass_type
210 end
211
212 # Force to get the primitive class named `name` or abort
213 fun get_primitive_class(name: String): MClass
214 do
215 var cla = self.model.get_mclasses_by_name(name)
216 if cla == null then
217 if name == "Bool" then
218 var c = new MClass(self, name, 0, enum_kind, public_visibility)
219 var cladef = new MClassDef(self, c.mclass_type, new Location(null, 0,0,0,0), new Array[String])
220 return c
221 end
222 print("Fatal Error: no primitive class {name}")
223 exit(1)
224 end
225 assert cla.length == 1 else print cla.join(", ")
226 return cla.first
227 end
228
229 # Try to get the primitive method named `name` on the type `recv`
230 fun try_get_primitive_method(name: String, recv: MClass): nullable MMethod
231 do
232 var props = self.model.get_mproperties_by_name(name)
233 if props == null then return null
234 var res: nullable MMethod = null
235 for mprop in props do
236 assert mprop isa MMethod
237 var intro = mprop.intro_mclassdef
238 for mclassdef in recv.mclassdefs do
239 if not self.in_importation.greaters.has(mclassdef.mmodule) then continue
240 if not mclassdef.in_hierarchy.greaters.has(intro) then continue
241 if res == null then
242 res = mprop
243 else if res != mprop then
244 print("Fatal Error: ambigous property name '{name}'; conflict between {mprop.full_name} and {res.full_name}")
245 abort
246 end
247 end
248 end
249 return res
250 end
251 end
252
253 private class MClassDefSorter
254 super AbstractSorter[MClassDef]
255 var mmodule: MModule
256 redef fun compare(a, b)
257 do
258 var ca = a.mclass
259 var cb = b.mclass
260 if ca != cb then return mmodule.flatten_mclass_hierarchy.compare(ca, cb)
261 return mmodule.model.mclassdef_hierarchy.compare(a, b)
262 end
263 end
264
265 private class MPropDefSorter
266 super AbstractSorter[MPropDef]
267 var mmodule: MModule
268 redef fun compare(pa, pb)
269 do
270 var a = pa.mclassdef
271 var b = pb.mclassdef
272 var ca = a.mclass
273 var cb = b.mclass
274 if ca != cb then return mmodule.flatten_mclass_hierarchy.compare(ca, cb)
275 return mmodule.model.mclassdef_hierarchy.compare(a, b)
276 end
277 end
278
279 # A named class
280 #
281 # `MClass` are global to the model; it means that a `MClass` is not bound to a
282 # specific `MModule`.
283 #
284 # This characteristic helps the reasoning about classes in a program since a
285 # single `MClass` object always denote the same class.
286 # However, because a `MClass` is global, it does not really have properties nor
287 # belong to a hierarchy since the property and the
288 # hierarchy of a class depends of a module.
289 class MClass
290 # The module that introduce the class
291 # While classes are not bound to a specific module,
292 # the introducing module is used for naming an visibility
293 var intro_mmodule: MModule
294
295 # The short name of the class
296 # In Nit, the name of a class cannot evolve in refinements
297 var name: String
298
299 # The canonical name of the class
300 # Example: `"owner::module::MyClass"`
301 fun full_name: String
302 do
303 return "{self.intro_mmodule.full_name}::{name}"
304 end
305
306 # The number of generic formal parameters
307 # 0 if the class is not generic
308 var arity: Int
309
310 # The kind of the class (interface, abstract class, etc.)
311 # In Nit, the kind of a class cannot evolve in refinements
312 var kind: MClassKind
313
314 # The visibility of the class
315 # In Nit, the visibility of a class cannot evolve in refinements
316 var visibility: MVisibility
317
318 init(intro_mmodule: MModule, name: String, arity: Int, kind: MClassKind, visibility: MVisibility)
319 do
320 self.intro_mmodule = intro_mmodule
321 self.name = name
322 self.arity = arity
323 self.kind = kind
324 self.visibility = visibility
325 intro_mmodule.intro_mclasses.add(self)
326 var model = intro_mmodule.model
327 model.mclasses_by_name.add_one(name, self)
328 model.mclasses.add(self)
329
330 # Create the formal parameter types
331 if arity > 0 then
332 var mparametertypes = new Array[MParameterType]
333 for i in [0..arity[ do
334 var mparametertype = new MParameterType(self, i)
335 mparametertypes.add(mparametertype)
336 end
337 var mclass_type = new MGenericType(self, mparametertypes)
338 self.mclass_type = mclass_type
339 self.get_mtype_cache.add(mclass_type)
340 else
341 self.mclass_type = new MClassType(self)
342 end
343 end
344
345 # All class definitions (introduction and refinements)
346 var mclassdefs: Array[MClassDef] = new Array[MClassDef]
347
348 # Alias for `name`
349 redef fun to_s do return self.name
350
351 # The definition that introduced the class
352 # Warning: the introduction is the first `MClassDef` object associated
353 # to self. If self is just created without having any associated
354 # definition, this method will abort
355 fun intro: MClassDef
356 do
357 assert has_a_first_definition: not mclassdefs.is_empty
358 return mclassdefs.first
359 end
360
361 # Return the class `self` in the class hierarchy of the module `mmodule`.
362 #
363 # SEE: `MModule::flatten_mclass_hierarchy`
364 # REQUIRE: `mmodule.has_mclass(self)`
365 fun in_hierarchy(mmodule: MModule): POSetElement[MClass]
366 do
367 return mmodule.flatten_mclass_hierarchy[self]
368 end
369
370 # The principal static type of the class.
371 #
372 # For non-generic class, mclass_type is the only `MClassType` based
373 # on self.
374 #
375 # For a generic class, the arguments are the formal parameters.
376 # i.e.: for the class Array[E:Object], the `mclass_type` is Array[E].
377 # If you want Array[Object] the see `MClassDef::bound_mtype`
378 #
379 # For generic classes, the mclass_type is also the way to get a formal
380 # generic parameter type.
381 #
382 # To get other types based on a generic class, see `get_mtype`.
383 #
384 # ENSURE: `mclass_type.mclass == self`
385 var mclass_type: MClassType
386
387 # Return a generic type based on the class
388 # Is the class is not generic, then the result is `mclass_type`
389 #
390 # REQUIRE: `mtype_arguments.length == self.arity`
391 fun get_mtype(mtype_arguments: Array[MType]): MClassType
392 do
393 assert mtype_arguments.length == self.arity
394 if self.arity == 0 then return self.mclass_type
395 for t in self.get_mtype_cache do
396 if t.arguments == mtype_arguments then
397 return t
398 end
399 end
400 var res = new MGenericType(self, mtype_arguments)
401 self.get_mtype_cache.add res
402 return res
403 end
404
405 private var get_mtype_cache: Array[MGenericType] = new Array[MGenericType]
406 end
407
408
409 # A definition (an introduction or a refinement) of a class in a module
410 #
411 # A `MClassDef` is associated with an explicit (or almost) definition of a
412 # class. Unlike `MClass`, a `MClassDef` is a local definition that belong to
413 # a specific module
414 class MClassDef
415 # The module where the definition is
416 var mmodule: MModule
417
418 # The associated `MClass`
419 var mclass: MClass
420
421 # The bounded type associated to the mclassdef
422 #
423 # For a non-generic class, `bound_mtype` and `mclass.mclass_type`
424 # are the same type.
425 #
426 # Example:
427 # For the classdef Array[E: Object], the bound_mtype is Array[Object].
428 # If you want Array[E], then see `mclass.mclass_type`
429 #
430 # ENSURE: `bound_mtype.mclass == self.mclass`
431 var bound_mtype: MClassType
432
433 # Name of each formal generic parameter (in order of declaration)
434 var parameter_names: Array[String]
435
436 # The origin of the definition
437 var location: Location
438
439 # Internal name combining the module and the class
440 # Example: "mymodule#MyClass"
441 redef var to_s: String
442
443 init(mmodule: MModule, bound_mtype: MClassType, location: Location, parameter_names: Array[String])
444 do
445 assert bound_mtype.mclass.arity == parameter_names.length
446 self.bound_mtype = bound_mtype
447 self.mmodule = mmodule
448 self.mclass = bound_mtype.mclass
449 self.location = location
450 mmodule.mclassdefs.add(self)
451 mclass.mclassdefs.add(self)
452 self.parameter_names = parameter_names
453 self.to_s = "{mmodule}#{mclass}"
454 end
455
456 # All declared super-types
457 # FIXME: quite ugly but not better idea yet
458 var supertypes: Array[MClassType] = new Array[MClassType]
459
460 # Register some super-types for the class (ie "super SomeType")
461 #
462 # The hierarchy must not already be set
463 # REQUIRE: `self.in_hierarchy == null`
464 fun set_supertypes(supertypes: Array[MClassType])
465 do
466 assert unique_invocation: self.in_hierarchy == null
467 var mmodule = self.mmodule
468 var model = mmodule.model
469 var mtype = self.bound_mtype
470
471 for supertype in supertypes do
472 self.supertypes.add(supertype)
473
474 # Register in full_type_specialization_hierarchy
475 model.full_mtype_specialization_hierarchy.add_edge(mtype, supertype)
476 # Register in intro_type_specialization_hierarchy
477 if mclass.intro_mmodule == mmodule and supertype.mclass.intro_mmodule == mmodule then
478 model.intro_mtype_specialization_hierarchy.add_edge(mtype, supertype)
479 end
480 end
481
482 end
483
484 # Collect the super-types (set by set_supertypes) to build the hierarchy
485 #
486 # This function can only invoked once by class
487 # REQUIRE: `self.in_hierarchy == null`
488 # ENSURE: `self.in_hierarchy != null`
489 fun add_in_hierarchy
490 do
491 assert unique_invocation: self.in_hierarchy == null
492 var model = mmodule.model
493 var res = model.mclassdef_hierarchy.add_node(self)
494 self.in_hierarchy = res
495 var mtype = self.bound_mtype
496
497 # Here we need to connect the mclassdef to its pairs in the mclassdef_hierarchy
498 # The simpliest way is to attach it to collect_mclassdefs
499 for mclassdef in mtype.collect_mclassdefs(mmodule) do
500 res.poset.add_edge(self, mclassdef)
501 end
502 end
503
504 # The view of the class definition in `mclassdef_hierarchy`
505 var in_hierarchy: nullable POSetElement[MClassDef] = null
506
507 # Is the definition the one that introduced `mclass`?
508 fun is_intro: Bool do return mclass.intro == self
509
510 # All properties introduced by the classdef
511 var intro_mproperties: Array[MProperty] = new Array[MProperty]
512
513 # All property definitions in the class (introductions and redefinitions)
514 var mpropdefs: Array[MPropDef] = new Array[MPropDef]
515 end
516
517 # A global static type
518 #
519 # MType are global to the model; it means that a `MType` is not bound to a
520 # specific `MModule`.
521 # This characteristic helps the reasoning about static types in a program
522 # since a single `MType` object always denote the same type.
523 #
524 # However, because a `MType` is global, it does not really have properties
525 # nor have subtypes to a hierarchy since the property and the class hierarchy
526 # depends of a module.
527 # Moreover, virtual types an formal generic parameter types also depends on
528 # a receiver to have sense.
529 #
530 # Therefore, most method of the types require a module and an anchor.
531 # The module is used to know what are the classes and the specialization
532 # links.
533 # The anchor is used to know what is the bound of the virtual types and formal
534 # generic parameter types.
535 #
536 # MType are not directly usable to get properties. See the `anchor_to` method
537 # and the `MClassType` class.
538 #
539 # FIXME: the order of the parameters is not the best. We mus pick on from:
540 # * foo(mmodule, anchor, othertype)
541 # * foo(othertype, anchor, mmodule)
542 # * foo(anchor, mmodule, othertype)
543 # * foo(othertype, mmodule, anchor)
544 abstract class MType
545
546 # The model of the type
547 fun model: Model is abstract
548
549 # Return true if `self` is an subtype of `sup`.
550 # The typing is done using the standard typing policy of Nit.
551 #
552 # REQUIRE: `anchor == null implies not self.need_anchor and not sup.need_anchor`
553 # REQUIRE: `anchor != null implies self.can_resolve_for(anchor, null, mmodule) and sup.can_resolve_for(anchor, null, mmodule)`
554 fun is_subtype(mmodule: MModule, anchor: nullable MClassType, sup: MType): Bool
555 do
556 var sub = self
557 if sub == sup then return true
558 if anchor == null then
559 assert not sub.need_anchor
560 assert not sup.need_anchor
561 else
562 assert sub.can_resolve_for(anchor, null, mmodule)
563 assert sup.can_resolve_for(anchor, null, mmodule)
564 end
565
566 # First, resolve the formal types to a common version in the receiver
567 # The trick here is that fixed formal type will be associed to the bound
568 # And unfixed formal types will be associed to a canonical formal type.
569 if sub isa MParameterType or sub isa MVirtualType then
570 assert anchor != null
571 sub = sub.resolve_for(anchor.mclass.mclass_type, anchor, mmodule, false)
572 end
573 if sup isa MParameterType or sup isa MVirtualType then
574 assert anchor != null
575 sup = sup.resolve_for(anchor.mclass.mclass_type, anchor, mmodule, false)
576 end
577
578 # Does `sup` accept null or not?
579 # Discard the nullable marker if it exists
580 var sup_accept_null = false
581 if sup isa MNullableType then
582 sup_accept_null = true
583 sup = sup.mtype
584 else if sup isa MNullType then
585 sup_accept_null = true
586 end
587
588 # Can `sub` provide null or not?
589 # Thus we can match with `sup_accept_null`
590 # Also discard the nullable marker if it exists
591 if sub isa MNullableType then
592 if not sup_accept_null then return false
593 sub = sub.mtype
594 else if sub isa MNullType then
595 return sup_accept_null
596 end
597 # Now the case of direct null and nullable is over.
598
599 # A unfixed formal type can only accept itself
600 if sup isa MParameterType or sup isa MVirtualType then
601 return sub == sup
602 end
603
604 # If `sub` is a formal type, then it is accepted if its bound is accepted
605 if sub isa MParameterType or sub isa MVirtualType then
606 assert anchor != null
607 sub = sub.anchor_to(mmodule, anchor)
608
609 # Manage the second layer of null/nullable
610 if sub isa MNullableType then
611 if not sup_accept_null then return false
612 sub = sub.mtype
613 else if sub isa MNullType then
614 return sup_accept_null
615 end
616 end
617
618 assert sub isa MClassType # It is the only remaining type
619
620 if sup isa MNullType then
621 # `sup` accepts only null
622 return false
623 end
624
625 assert sup isa MClassType # It is the only remaining type
626
627 # Now both are MClassType, we need to dig
628
629 if sub == sup then return true
630
631 if anchor == null then anchor = sub # UGLY: any anchor will work
632 var resolved_sub = sub.anchor_to(mmodule, anchor)
633 var res = resolved_sub.collect_mclasses(mmodule).has(sup.mclass)
634 if res == false then return false
635 if not sup isa MGenericType then return true
636 var sub2 = sub.supertype_to(mmodule, anchor, sup.mclass)
637 assert sub2.mclass == sup.mclass
638 for i in [0..sup.mclass.arity[ do
639 var sub_arg = sub2.arguments[i]
640 var sup_arg = sup.arguments[i]
641 res = sub_arg.is_subtype(mmodule, anchor, sup_arg)
642 if res == false then return false
643 end
644 return true
645 end
646
647 # The base class type on which self is based
648 #
649 # This base type is used to get property (an internally to perform
650 # unsafe type comparison).
651 #
652 # Beware: some types (like null) are not based on a class thus this
653 # method will crash
654 #
655 # Basically, this function transform the virtual types and parameter
656 # types to their bounds.
657 #
658 # Example
659 # class A end
660 # class B super A end
661 # class X end
662 # class Y super X end
663 # class G[T: A]
664 # type U: X
665 # end
666 # class H
667 # super G[B]
668 # redef type U: Y
669 # end
670 # Map[T,U] anchor_to H #-> Map[B,Y]
671 #
672 # Explanation of the example:
673 # In H, T is set to B, because "H super G[B]", and U is bound to Y,
674 # because "redef type U: Y". Therefore, Map[T, U] is bound to
675 # Map[B, Y]
676 #
677 # ENSURE: `not self.need_anchor implies result == self`
678 # ENSURE: `not result.need_anchor`
679 fun anchor_to(mmodule: MModule, anchor: MClassType): MType
680 do
681 if not need_anchor then return self
682 assert not anchor.need_anchor
683 # Just resolve to the anchor and clear all the virtual types
684 var res = self.resolve_for(anchor, null, mmodule, true)
685 assert not res.need_anchor
686 return res
687 end
688
689 # Does `self` contain a virtual type or a formal generic parameter type?
690 # In order to remove those types, you usually want to use `anchor_to`.
691 fun need_anchor: Bool do return true
692
693 # Return the supertype when adapted to a class.
694 #
695 # In Nit, for each super-class of a type, there is a equivalent super-type.
696 #
697 # Example:
698 # class G[T, U] end
699 # class H[V] super G[V, Bool] end
700 # H[Int] supertype_to G #-> G[Int, Bool]
701 #
702 # REQUIRE: `super_mclass` is a super-class of `self`
703 # REQUIRE: `self.need_anchor implies anchor != null and self.can_resolve_for(anchor, null, mmodule)`
704 # ENSURE: `result.mclass = super_mclass`
705 fun supertype_to(mmodule: MModule, anchor: nullable MClassType, super_mclass: MClass): MClassType
706 do
707 if super_mclass.arity == 0 then return super_mclass.mclass_type
708 if self isa MClassType and self.mclass == super_mclass then return self
709 var resolved_self
710 if self.need_anchor then
711 assert anchor != null
712 resolved_self = self.anchor_to(mmodule, anchor)
713 else
714 resolved_self = self
715 end
716 var supertypes = resolved_self.collect_mtypes(mmodule)
717 for supertype in supertypes do
718 if supertype.mclass == super_mclass then
719 # FIXME: Here, we stop on the first goal. Should we check others and detect inconsistencies?
720 return supertype.resolve_for(self, anchor, mmodule, false)
721 end
722 end
723 abort
724 end
725
726 # Replace formals generic types in self with resolved values in `mtype`
727 # If `cleanup_virtual` is true, then virtual types are also replaced
728 # with their bounds
729 #
730 # This function returns self if `need_anchor` is false.
731 #
732 # ## Example 1
733 #
734 # class G[E] end
735 # class H[F] super G[F] end
736 # class X[Z] end
737 #
738 # * Array[E].resolve_for(H[Int]) #-> Array[Int]
739 # * Array[E].resolve_for(G[Z], X[Int]) #-> Array[Z]
740 #
741 # Explanation of the example:
742 # * Array[E].need_anchor is true because there is a formal generic parameter type E
743 # * E makes sense for H[Int] because E is a formal parameter of G and H specialize G
744 # * Since "H[F] super G[F]", E is in fact F for H
745 # * More specifically, in H[Int], E is Int
746 # * So, in H[Int], Array[E] is Array[Int]
747 #
748 # This function is mainly used to inherit a signature.
749 # Because, unlike `anchor_to`, we do not want a full resolution of
750 # a type but only an adapted version of it.
751 #
752 # ## Example 2
753 #
754 # class A[E]
755 # fun foo(e:E):E is abstract
756 # end
757 # class B super A[Int] end
758 #
759 # The signature on foo is (e: E): E
760 # If we resolve the signature for B, we get (e:Int):Int
761 #
762 # ## Example 3
763 #
764 # class A[E]
765 # fun foo(e:E) is abstract
766 # end
767 # class B[F]
768 # var a: A[Array[F]]
769 # fun bar do a.foo(x) # <- x is here
770 # end
771 #
772 # The first question is: is foo available on `a`?
773 #
774 # The static type of a is `A[Array[F]]`, that is an open type.
775 # in order to find a method `foo`, whe must look at a resolved type.
776 #
777 # A[Array[F]].anchor_to(B[nullable Object]) #-> A[Array[nullable Object]]
778 #
779 # the method `foo` exists in `A[Array[nullable Object]]`, therefore `foo` exists for `a`.
780 #
781 # The next question is: what is the accepted types for `x`?
782 #
783 # the signature of `foo` is `foo(e:E)`, thus we must resolve the type E
784 #
785 # E.resolve_for(A[Array[F]],B[nullable Object]) #-> Array[F]
786 #
787 # The resolution can be done because `E` make sense for the class A (see `can_resolve_for`)
788 #
789 # TODO: Explain the cleanup_virtual
790 #
791 # FIXME: the parameter `cleanup_virtual` is just a bad idea, but having
792 # two function instead of one seems also to be a bad idea.
793 #
794 # REQUIRE: `can_resolve_for(mtype, anchor, mmodule)`
795 # ENSURE: `not self.need_anchor implies result == self`
796 fun resolve_for(mtype: MType, anchor: nullable MClassType, mmodule: MModule, cleanup_virtual: Bool): MType is abstract
797
798 # Can the type be resolved?
799 #
800 # In order to resolve open types, the formal types must make sence.
801 #
802 # ## Example
803 #
804 # class A[E]
805 # end
806 # class B[F]
807 # end
808 #
809 # * E.can_resolve_for(A[Int]) #-> true, E make sense in A
810 # * E.can_resolve_for(B[Int]) #-> false, E does not make sense in B
811 # * B[E].can_resolve_for(A[F], B[Object]) #-> true,
812 # B[E] is a red hearing only the E is important,
813 # E make sense in A
814 #
815 # REQUIRE: `anchor != null implies not anchor.need_anchor`
816 # REQUIRE: `mtype.need_anchor implies anchor != null and mtype.can_resolve_for(anchor, null, mmodule)`
817 # ENSURE: `not self.need_anchor implies result == true`
818 fun can_resolve_for(mtype: MType, anchor: nullable MClassType, mmodule: MModule): Bool is abstract
819
820 # Return the nullable version of the type
821 # If the type is already nullable then self is returned
822 fun as_nullable: MType
823 do
824 var res = self.as_nullable_cache
825 if res != null then return res
826 res = new MNullableType(self)
827 self.as_nullable_cache = res
828 return res
829 end
830
831 private var as_nullable_cache: nullable MType = null
832
833
834 # The deph of the type seen as a tree.
835 #
836 # * A -> 1
837 # * G[A] -> 2
838 # * H[A, B] -> 2
839 # * H[G[A], B] -> 3
840 #
841 # Formal types have a depth of 1.
842 fun depth: Int
843 do
844 return 1
845 end
846
847 # The length of the type seen as a tree.
848 #
849 # * A -> 1
850 # * G[A] -> 2
851 # * H[A, B] -> 3
852 # * H[G[A], B] -> 4
853 #
854 # Formal types have a length of 1.
855 fun length: Int
856 do
857 return 1
858 end
859
860 # Compute all the classdefs inherited/imported.
861 # The returned set contains:
862 # * the class definitions from `mmodule` and its imported modules
863 # * the class definitions of this type and its super-types
864 #
865 # This function is used mainly internally.
866 #
867 # REQUIRE: `not self.need_anchor`
868 fun collect_mclassdefs(mmodule: MModule): Set[MClassDef] is abstract
869
870 # Compute all the super-classes.
871 # This function is used mainly internally.
872 #
873 # REQUIRE: `not self.need_anchor`
874 fun collect_mclasses(mmodule: MModule): Set[MClass] is abstract
875
876 # Compute all the declared super-types.
877 # Super-types are returned as declared in the classdefs (verbatim).
878 # This function is used mainly internally.
879 #
880 # REQUIRE: `not self.need_anchor`
881 fun collect_mtypes(mmodule: MModule): Set[MClassType] is abstract
882
883 # Is the property in self for a given module
884 # This method does not filter visibility or whatever
885 #
886 # REQUIRE: `not self.need_anchor`
887 fun has_mproperty(mmodule: MModule, mproperty: MProperty): Bool
888 do
889 assert not self.need_anchor
890 return self.collect_mclassdefs(mmodule).has(mproperty.intro_mclassdef)
891 end
892 end
893
894 # A type based on a class.
895 #
896 # `MClassType` have properties (see `has_mproperty`).
897 class MClassType
898 super MType
899
900 # The associated class
901 var mclass: MClass
902
903 redef fun model do return self.mclass.intro_mmodule.model
904
905 private init(mclass: MClass)
906 do
907 self.mclass = mclass
908 end
909
910 # The formal arguments of the type
911 # ENSURE: `result.length == self.mclass.arity`
912 var arguments: Array[MType] = new Array[MType]
913
914 redef fun to_s do return mclass.to_s
915
916 redef fun need_anchor do return false
917
918 redef fun anchor_to(mmodule: MModule, anchor: MClassType): MClassType
919 do
920 return super.as(MClassType)
921 end
922
923 redef fun resolve_for(mtype: MType, anchor: nullable MClassType, mmodule: MModule, cleanup_virtual: Bool): MClassType do return self
924
925 redef fun can_resolve_for(mtype, anchor, mmodule) do return true
926
927 redef fun collect_mclassdefs(mmodule)
928 do
929 assert not self.need_anchor
930 var cache = self.collect_mclassdefs_cache
931 if not cache.has_key(mmodule) then
932 self.collect_things(mmodule)
933 end
934 return cache[mmodule]
935 end
936
937 redef fun collect_mclasses(mmodule)
938 do
939 assert not self.need_anchor
940 var cache = self.collect_mclasses_cache
941 if not cache.has_key(mmodule) then
942 self.collect_things(mmodule)
943 end
944 return cache[mmodule]
945 end
946
947 redef fun collect_mtypes(mmodule)
948 do
949 assert not self.need_anchor
950 var cache = self.collect_mtypes_cache
951 if not cache.has_key(mmodule) then
952 self.collect_things(mmodule)
953 end
954 return cache[mmodule]
955 end
956
957 # common implementation for `collect_mclassdefs`, `collect_mclasses`, and `collect_mtypes`.
958 private fun collect_things(mmodule: MModule)
959 do
960 var res = new HashSet[MClassDef]
961 var seen = new HashSet[MClass]
962 var types = new HashSet[MClassType]
963 seen.add(self.mclass)
964 var todo = [self.mclass]
965 while not todo.is_empty do
966 var mclass = todo.pop
967 #print "process {mclass}"
968 for mclassdef in mclass.mclassdefs do
969 if not mmodule.in_importation <= mclassdef.mmodule then continue
970 #print " process {mclassdef}"
971 res.add(mclassdef)
972 for supertype in mclassdef.supertypes do
973 types.add(supertype)
974 var superclass = supertype.mclass
975 if seen.has(superclass) then continue
976 #print " add {superclass}"
977 seen.add(superclass)
978 todo.add(superclass)
979 end
980 end
981 end
982 collect_mclassdefs_cache[mmodule] = res
983 collect_mclasses_cache[mmodule] = seen
984 collect_mtypes_cache[mmodule] = types
985 end
986
987 private var collect_mclassdefs_cache: HashMap[MModule, Set[MClassDef]] = new HashMap[MModule, Set[MClassDef]]
988 private var collect_mclasses_cache: HashMap[MModule, Set[MClass]] = new HashMap[MModule, Set[MClass]]
989 private var collect_mtypes_cache: HashMap[MModule, Set[MClassType]] = new HashMap[MModule, Set[MClassType]]
990
991 end
992
993 # A type based on a generic class.
994 # A generic type a just a class with additional formal generic arguments.
995 class MGenericType
996 super MClassType
997
998 private init(mclass: MClass, arguments: Array[MType])
999 do
1000 super(mclass)
1001 assert self.mclass.arity == arguments.length
1002 self.arguments = arguments
1003
1004 self.need_anchor = false
1005 for t in arguments do
1006 if t.need_anchor then
1007 self.need_anchor = true
1008 break
1009 end
1010 end
1011
1012 self.to_s = "{mclass}[{arguments.join(", ")}]"
1013 end
1014
1015 # Recursively print the type of the arguments within brackets.
1016 # Example: `"Map[String, List[Int]]"`
1017 redef var to_s: String
1018
1019 redef var need_anchor: Bool
1020
1021 redef fun resolve_for(mtype, anchor, mmodule, cleanup_virtual)
1022 do
1023 if not need_anchor then return self
1024 assert can_resolve_for(mtype, anchor, mmodule)
1025 var types = new Array[MType]
1026 for t in arguments do
1027 types.add(t.resolve_for(mtype, anchor, mmodule, cleanup_virtual))
1028 end
1029 return mclass.get_mtype(types)
1030 end
1031
1032 redef fun can_resolve_for(mtype, anchor, mmodule)
1033 do
1034 if not need_anchor then return true
1035 for t in arguments do
1036 if not t.can_resolve_for(mtype, anchor, mmodule) then return false
1037 end
1038 return true
1039 end
1040
1041
1042 redef fun depth
1043 do
1044 var dmax = 0
1045 for a in self.arguments do
1046 var d = a.depth
1047 if d > dmax then dmax = d
1048 end
1049 return dmax + 1
1050 end
1051
1052 redef fun length
1053 do
1054 var res = 1
1055 for a in self.arguments do
1056 res += a.length
1057 end
1058 return res
1059 end
1060 end
1061
1062 # A virtual formal type.
1063 class MVirtualType
1064 super MType
1065
1066 # The property associated with the type.
1067 # Its the definitions of this property that determine the bound or the virtual type.
1068 var mproperty: MProperty
1069
1070 redef fun model do return self.mproperty.intro_mclassdef.mmodule.model
1071
1072 # Lookup the bound for a given resolved_receiver
1073 # The result may be a other virtual type (or a parameter type)
1074 #
1075 # The result is returned exactly as declared in the "type" property (verbatim).
1076 #
1077 # In case of conflict, the method aborts.
1078 fun lookup_bound(mmodule: MModule, resolved_receiver: MType): MType
1079 do
1080 assert not resolved_receiver.need_anchor
1081 var props = self.mproperty.lookup_definitions(mmodule, resolved_receiver)
1082 if props.is_empty then
1083 abort
1084 else if props.length == 1 then
1085 return props.first.as(MVirtualTypeDef).bound.as(not null)
1086 end
1087 var types = new ArraySet[MType]
1088 for p in props do
1089 types.add(p.as(MVirtualTypeDef).bound.as(not null))
1090 end
1091 if types.length == 1 then
1092 return types.first
1093 end
1094 abort
1095 end
1096
1097 redef fun resolve_for(mtype, anchor, mmodule, cleanup_virtual)
1098 do
1099 assert can_resolve_for(mtype, anchor, mmodule)
1100 # self is a virtual type declared (or inherited) in mtype
1101 # The point of the function it to get the bound of the virtual type that make sense for mtype
1102 # But because mtype is maybe a virtual/formal type, we need to get a real receiver first
1103 #print "{class_name}: {self}/{mtype}/{anchor}?"
1104 var resolved_reciever
1105 if mtype.need_anchor then
1106 assert anchor != null
1107 resolved_reciever = mtype.resolve_for(anchor, null, mmodule, true)
1108 else
1109 resolved_reciever = mtype
1110 end
1111 # Now, we can get the bound
1112 var verbatim_bound = lookup_bound(mmodule, resolved_reciever)
1113 # The bound is exactly as declared in the "type" property, so we must resolve it again
1114 var res = verbatim_bound.resolve_for(mtype, anchor, mmodule, cleanup_virtual)
1115 #print "{class_name}: {self}/{mtype}/{anchor} -> {self}/{resolved_reciever}/{anchor} -> {verbatim_bound}/{mtype}/{anchor} -> {res}"
1116
1117 # What to return here? There is a bunch a special cases:
1118 # If 'cleanup_virtual' we must return the resolved type, since we cannot return self
1119 if cleanup_virtual then return res
1120 # If the reciever is a intern class, then the virtual type cannot be redefined since there is no possible subclass. self is just fixed. so simply return the resolution
1121 if resolved_reciever isa MNullableType then resolved_reciever = resolved_reciever.mtype
1122 if resolved_reciever.as(MClassType).mclass.kind == enum_kind then return res
1123 # If the resolved type isa MVirtualType, it means that self was bound to it, and cannot be unbound. self is just fixed. so return the resolution.
1124 if res isa MVirtualType then return res
1125 # It the resolved type isa intern class, then there is no possible valid redefinition is any potentiel subclass. self is just fixed. so simply return the resolution
1126 if res isa MClassType and res.mclass.kind == enum_kind then return res
1127 # TODO: Add 'fixed' virtual type in the specification.
1128 # TODO: What if bound to a MParameterType?
1129 # Note that Nullable types can always be redefined by the non nullable version, so there is no specific case on it.
1130
1131 # If anything apply, then `self' cannot be resolved, so return self
1132 return self
1133 end
1134
1135 redef fun can_resolve_for(mtype, anchor, mmodule)
1136 do
1137 if mtype.need_anchor then
1138 assert anchor != null
1139 mtype = mtype.anchor_to(mmodule, anchor)
1140 end
1141 return mtype.has_mproperty(mmodule, mproperty)
1142 end
1143
1144 redef fun to_s do return self.mproperty.to_s
1145
1146 init(mproperty: MProperty)
1147 do
1148 self.mproperty = mproperty
1149 end
1150 end
1151
1152 # The type associated the a formal parameter generic type of a class
1153 #
1154 # Each parameter type is associated to a specific class.
1155 # It's mean that all refinements of a same class "share" the parameter type,
1156 # but that a generic subclass has its on parameter types.
1157 #
1158 # However, in the sense of the meta-model, the a parameter type of a class is
1159 # a valid types in a subclass. The "in the sense of the meta-model" is
1160 # important because, in the Nit language, the programmer cannot refers
1161 # directly to the parameter types of the super-classes.
1162 #
1163 # Example:
1164 # class A[E]
1165 # fun e: E is abstract
1166 # end
1167 # class B[F]
1168 # super A[Array[F]]
1169 # end
1170 # In the class definition B[F], `F` is a valid type but `E` is not.
1171 # However, `self.e` is a valid method call, and the signature of `e` is
1172 # declared `e: E`.
1173 #
1174 # Note that parameter types are shared among class refinements.
1175 # Therefore parameter only have an internal name (see `to_s` for details).
1176 # TODO: Add a `name_for` to get better messages.
1177 class MParameterType
1178 super MType
1179
1180 # The generic class where the parameter belong
1181 var mclass: MClass
1182
1183 redef fun model do return self.mclass.intro_mmodule.model
1184
1185 # The position of the parameter (0 for the first parameter)
1186 # FIXME: is `position` a better name?
1187 var rank: Int
1188
1189 # Internal name of the parameter type
1190 # Names of parameter types changes in each class definition
1191 # Therefore, this method return an internal name.
1192 # Example: return "G#1" for the second parameter of the class G
1193 # FIXME: add a way to get the real name in a classdef
1194 redef fun to_s do return "{mclass}#{rank}"
1195
1196 # Resolve the bound for a given resolved_receiver
1197 # The result may be a other virtual type (or a parameter type)
1198 fun lookup_bound(mmodule: MModule, resolved_receiver: MType): MType
1199 do
1200 assert not resolved_receiver.need_anchor
1201 var goalclass = self.mclass
1202 var supertypes = resolved_receiver.collect_mtypes(mmodule)
1203 for t in supertypes do
1204 if t.mclass == goalclass then
1205 # Yeah! c specialize goalclass with a "super `t'". So the question is what is the argument of f
1206 # FIXME: Here, we stop on the first goal. Should we check others and detect inconsistencies?
1207 var res = t.arguments[self.rank]
1208 return res
1209 end
1210 end
1211 abort
1212 end
1213
1214 redef fun resolve_for(mtype, anchor, mmodule, cleanup_virtual)
1215 do
1216 assert can_resolve_for(mtype, anchor, mmodule)
1217 #print "{class_name}: {self}/{mtype}/{anchor}?"
1218
1219 if mtype isa MGenericType and mtype.mclass == self.mclass then
1220 return mtype.arguments[self.rank]
1221 end
1222
1223 # self is a parameter type of mtype (or of a super-class of mtype)
1224 # The point of the function it to get the bound of the virtual type that make sense for mtype
1225 # But because mtype is maybe a virtual/formal type, we need to get a real receiver first
1226 # FIXME: What happend here is far from clear. Thus this part must be validated and clarified
1227 var resolved_receiver
1228 if mtype.need_anchor then
1229 assert anchor != null
1230 resolved_receiver = mtype.resolve_for(anchor.mclass.mclass_type, anchor, mmodule, true)
1231 else
1232 resolved_receiver = mtype
1233 end
1234 if resolved_receiver isa MNullableType then resolved_receiver = resolved_receiver.mtype
1235 if resolved_receiver isa MParameterType then
1236 assert resolved_receiver.mclass == anchor.mclass
1237 resolved_receiver = anchor.arguments[resolved_receiver.rank]
1238 if resolved_receiver isa MNullableType then resolved_receiver = resolved_receiver.mtype
1239 end
1240 assert resolved_receiver isa MClassType
1241
1242 # Eh! The parameter is in the current class.
1243 # So we return the corresponding argument, no mater what!
1244 if resolved_receiver.mclass == self.mclass then
1245 var res = resolved_receiver.arguments[self.rank]
1246 #print "{class_name}: {self}/{mtype}/{anchor} -> direct {res}"
1247 return res
1248 end
1249
1250 if resolved_receiver.need_anchor then
1251 assert anchor != null
1252 resolved_receiver = resolved_receiver.resolve_for(anchor, null, mmodule, false)
1253 end
1254 # Now, we can get the bound
1255 var verbatim_bound = lookup_bound(mmodule, resolved_receiver)
1256 # The bound is exactly as declared in the "type" property, so we must resolve it again
1257 var res = verbatim_bound.resolve_for(mtype, anchor, mmodule, cleanup_virtual)
1258
1259 #print "{class_name}: {self}/{mtype}/{anchor} -> indirect {res}"
1260
1261 return res
1262 end
1263
1264 redef fun can_resolve_for(mtype, anchor, mmodule)
1265 do
1266 if mtype.need_anchor then
1267 assert anchor != null
1268 mtype = mtype.anchor_to(mmodule, anchor)
1269 end
1270 return mtype.collect_mclassdefs(mmodule).has(mclass.intro)
1271 end
1272
1273 init(mclass: MClass, rank: Int)
1274 do
1275 self.mclass = mclass
1276 self.rank = rank
1277 end
1278 end
1279
1280 # A type prefixed with "nullable"
1281 class MNullableType
1282 super MType
1283
1284 # The base type of the nullable type
1285 var mtype: MType
1286
1287 redef fun model do return self.mtype.model
1288
1289 init(mtype: MType)
1290 do
1291 self.mtype = mtype
1292 self.to_s = "nullable {mtype}"
1293 end
1294
1295 redef var to_s: String
1296
1297 redef fun need_anchor do return mtype.need_anchor
1298 redef fun as_nullable do return self
1299 redef fun resolve_for(mtype, anchor, mmodule, cleanup_virtual)
1300 do
1301 var res = self.mtype.resolve_for(mtype, anchor, mmodule, cleanup_virtual)
1302 return res.as_nullable
1303 end
1304
1305 redef fun can_resolve_for(mtype, anchor, mmodule)
1306 do
1307 return self.mtype.can_resolve_for(mtype, anchor, mmodule)
1308 end
1309
1310 redef fun depth do return self.mtype.depth
1311
1312 redef fun length do return self.mtype.length
1313
1314 redef fun collect_mclassdefs(mmodule)
1315 do
1316 assert not self.need_anchor
1317 return self.mtype.collect_mclassdefs(mmodule)
1318 end
1319
1320 redef fun collect_mclasses(mmodule)
1321 do
1322 assert not self.need_anchor
1323 return self.mtype.collect_mclasses(mmodule)
1324 end
1325
1326 redef fun collect_mtypes(mmodule)
1327 do
1328 assert not self.need_anchor
1329 return self.mtype.collect_mtypes(mmodule)
1330 end
1331 end
1332
1333 # The type of the only value null
1334 #
1335 # The is only one null type per model, see `MModel::null_type`.
1336 class MNullType
1337 super MType
1338 redef var model: Model
1339 protected init(model: Model)
1340 do
1341 self.model = model
1342 end
1343 redef fun to_s do return "null"
1344 redef fun as_nullable do return self
1345 redef fun need_anchor do return false
1346 redef fun resolve_for(mtype, anchor, mmodule, cleanup_virtual) do return self
1347 redef fun can_resolve_for(mtype, anchor, mmodule) do return true
1348
1349 redef fun collect_mclassdefs(mmodule) do return new HashSet[MClassDef]
1350
1351 redef fun collect_mclasses(mmodule) do return new HashSet[MClass]
1352
1353 redef fun collect_mtypes(mmodule) do return new HashSet[MClassType]
1354 end
1355
1356 # A signature of a method (or a closure)
1357 class MSignature
1358 super MType
1359
1360 # The each parameter (in order)
1361 var mparameters: Array[MParameter]
1362
1363 var mclosures = new Array[MParameter]
1364
1365 # The return type (null for a procedure)
1366 var return_mtype: nullable MType
1367
1368 redef fun depth
1369 do
1370 var dmax = 0
1371 var t = self.return_mtype
1372 if t != null then dmax = t.depth
1373 for p in mparameters do
1374 var d = p.mtype.depth
1375 if d > dmax then dmax = d
1376 end
1377 for p in mclosures do
1378 var d = p.mtype.depth
1379 if d > dmax then dmax = d
1380 end
1381 return dmax + 1
1382 end
1383
1384 redef fun length
1385 do
1386 var res = 1
1387 var t = self.return_mtype
1388 if t != null then res += t.length
1389 for p in mparameters do
1390 res += p.mtype.length
1391 end
1392 for p in mclosures do
1393 res += p.mtype.length
1394 end
1395 return res
1396 end
1397
1398 # REQUIRE: 1 <= mparameters.count p -> p.is_vararg
1399 init(mparameters: Array[MParameter], return_mtype: nullable MType)
1400 do
1401 var vararg_rank = -1
1402 for i in [0..mparameters.length[ do
1403 var parameter = mparameters[i]
1404 if parameter.is_vararg then
1405 assert vararg_rank == -1
1406 vararg_rank = i
1407 end
1408 end
1409 self.mparameters = mparameters
1410 self.return_mtype = return_mtype
1411 self.vararg_rank = vararg_rank
1412 end
1413
1414 # The rank of the ellipsis (`...`) for vararg (starting from 0).
1415 # value is -1 if there is no vararg.
1416 # Example: for "(a: Int, b: Bool..., c: Char)" #-> vararg_rank=1
1417 var vararg_rank: Int
1418
1419 # The number or parameters
1420 fun arity: Int do return mparameters.length
1421
1422 redef fun to_s
1423 do
1424 var b = new Buffer
1425 if not mparameters.is_empty then
1426 b.append("(")
1427 for i in [0..mparameters.length[ do
1428 var mparameter = mparameters[i]
1429 if i > 0 then b.append(", ")
1430 b.append(mparameter.name)
1431 b.append(": ")
1432 b.append(mparameter.mtype.to_s)
1433 if mparameter.is_vararg then
1434 b.append("...")
1435 end
1436 end
1437 b.append(")")
1438 end
1439 var ret = self.return_mtype
1440 if ret != null then
1441 b.append(": ")
1442 b.append(ret.to_s)
1443 end
1444 return b.to_s
1445 end
1446
1447 redef fun resolve_for(mtype: MType, anchor: nullable MClassType, mmodule: MModule, cleanup_virtual: Bool): MSignature
1448 do
1449 var params = new Array[MParameter]
1450 for p in self.mparameters do
1451 params.add(p.resolve_for(mtype, anchor, mmodule, cleanup_virtual))
1452 end
1453 var ret = self.return_mtype
1454 if ret != null then
1455 ret = ret.resolve_for(mtype, anchor, mmodule, cleanup_virtual)
1456 end
1457 var res = new MSignature(params, ret)
1458 for p in self.mclosures do
1459 res.mclosures.add(p.resolve_for(mtype, anchor, mmodule, cleanup_virtual))
1460 end
1461 return res
1462 end
1463 end
1464
1465 # A parameter in a signature
1466 class MParameter
1467 # The name of the parameter
1468 var name: String
1469
1470 # The static type of the parameter
1471 var mtype: MType
1472
1473 # Is the parameter a vararg?
1474 var is_vararg: Bool
1475
1476 fun resolve_for(mtype: MType, anchor: nullable MClassType, mmodule: MModule, cleanup_virtual: Bool): MParameter
1477 do
1478 if not self.mtype.need_anchor then return self
1479 var newtype = self.mtype.resolve_for(mtype, anchor, mmodule, cleanup_virtual)
1480 var res = new MParameter(self.name, newtype, self.is_vararg)
1481 return res
1482 end
1483 end
1484
1485 # A service (global property) that generalize method, attribute, etc.
1486 #
1487 # `MProperty` are global to the model; it means that a `MProperty` is not bound
1488 # to a specific `MModule` nor a specific `MClass`.
1489 #
1490 # A MProperty gather definitions (see `mpropdefs`) ; one for the introduction
1491 # and the other in subclasses and in refinements.
1492 #
1493 # A `MProperty` is used to denotes services in polymorphic way (ie. independent
1494 # of any dynamic type).
1495 # For instance, a call site "x.foo" is associated to a `MProperty`.
1496 abstract class MProperty
1497 # The associated MPropDef subclass.
1498 # The two specialization hierarchy are symmetric.
1499 type MPROPDEF: MPropDef
1500
1501 # The classdef that introduce the property
1502 # While a property is not bound to a specific module, or class,
1503 # the introducing mclassdef is used for naming and visibility
1504 var intro_mclassdef: MClassDef
1505
1506 # The (short) name of the property
1507 var name: String
1508
1509 # The canonical name of the property
1510 # Example: "owner::my_module::MyClass::my_method"
1511 fun full_name: String
1512 do
1513 return "{self.intro_mclassdef.mmodule.full_name}::{self.intro_mclassdef.mclass.name}::{name}"
1514 end
1515
1516 # The visibility of the property
1517 var visibility: MVisibility
1518
1519 init(intro_mclassdef: MClassDef, name: String, visibility: MVisibility)
1520 do
1521 self.intro_mclassdef = intro_mclassdef
1522 self.name = name
1523 self.visibility = visibility
1524 intro_mclassdef.intro_mproperties.add(self)
1525 var model = intro_mclassdef.mmodule.model
1526 model.mproperties_by_name.add_one(name, self)
1527 model.mproperties.add(self)
1528 end
1529
1530 # All definitions of the property.
1531 # The first is the introduction,
1532 # The other are redefinitions (in refinements and in subclasses)
1533 var mpropdefs: Array[MPROPDEF] = new Array[MPROPDEF]
1534
1535 # The definition that introduced the property
1536 # Warning: the introduction is the first `MPropDef` object
1537 # associated to self. If self is just created without having any
1538 # associated definition, this method will abort
1539 fun intro: MPROPDEF do return mpropdefs.first
1540
1541 # Alias for `name`
1542 redef fun to_s do return name
1543
1544 # Return the most specific property definitions defined or inherited by a type.
1545 # The selection knows that refinement is stronger than specialization;
1546 # however, in case of conflict more than one property are returned.
1547 # If mtype does not know mproperty then an empty array is returned.
1548 #
1549 # If you want the really most specific property, then look at `lookup_first_definition`
1550 fun lookup_definitions(mmodule: MModule, mtype: MType): Array[MPROPDEF]
1551 do
1552 assert not mtype.need_anchor
1553 if mtype isa MNullableType then mtype = mtype.mtype
1554
1555 var cache = self.lookup_definitions_cache[mmodule, mtype]
1556 if cache != null then return cache
1557
1558 #print "select prop {mproperty} for {mtype} in {self}"
1559 # First, select all candidates
1560 var candidates = new Array[MPROPDEF]
1561 for mpropdef in self.mpropdefs do
1562 # If the definition is not imported by the module, then skip
1563 if not mmodule.in_importation <= mpropdef.mclassdef.mmodule then continue
1564 # If the definition is not inherited by the type, then skip
1565 if not mtype.is_subtype(mmodule, null, mpropdef.mclassdef.bound_mtype) then continue
1566 # Else, we keep it
1567 candidates.add(mpropdef)
1568 end
1569 # Fast track for only one candidate
1570 if candidates.length <= 1 then
1571 self.lookup_definitions_cache[mmodule, mtype] = candidates
1572 return candidates
1573 end
1574
1575 # Second, filter the most specific ones
1576 var res = new Array[MPROPDEF]
1577 for pd1 in candidates do
1578 var cd1 = pd1.mclassdef
1579 var c1 = cd1.mclass
1580 var keep = true
1581 for pd2 in candidates do
1582 if pd2 == pd1 then continue # do not compare with self!
1583 var cd2 = pd2.mclassdef
1584 var c2 = cd2.mclass
1585 if c2.mclass_type == c1.mclass_type then
1586 if cd2.mmodule.in_importation <= cd1.mmodule then
1587 # cd2 refines cd1; therefore we skip pd1
1588 keep = false
1589 break
1590 end
1591 else if cd2.bound_mtype.is_subtype(mmodule, null, cd1.bound_mtype) then
1592 # cd2 < cd1; therefore we skip pd1
1593 keep = false
1594 break
1595 end
1596 end
1597 if keep then
1598 res.add(pd1)
1599 end
1600 end
1601 if res.is_empty then
1602 print "All lost! {candidates.join(", ")}"
1603 # FIXME: should be abort!
1604 end
1605 self.lookup_definitions_cache[mmodule, mtype] = res
1606 return res
1607 end
1608
1609 private var lookup_definitions_cache: HashMap2[MModule, MType, Array[MPROPDEF]] = new HashMap2[MModule, MType, Array[MPROPDEF]]
1610
1611 # Return the most specific property definitions inherited by a type.
1612 # The selection knows that refinement is stronger than specialization;
1613 # however, in case of conflict more than one property are returned.
1614 # If mtype does not know mproperty then an empty array is returned.
1615 #
1616 # If you want the really most specific property, then look at `lookup_next_definition`
1617 #
1618 # FIXME: Move to `MPropDef`?
1619 fun lookup_super_definitions(mmodule: MModule, mtype: MType): Array[MPropDef]
1620 do
1621 assert not mtype.need_anchor
1622 if mtype isa MNullableType then mtype = mtype.mtype
1623
1624 # First, select all candidates
1625 var candidates = new Array[MPropDef]
1626 for mpropdef in self.mpropdefs do
1627 # If the definition is not imported by the module, then skip
1628 if not mmodule.in_importation <= mpropdef.mclassdef.mmodule then continue
1629 # If the definition is not inherited by the type, then skip
1630 if not mtype.is_subtype(mmodule, null, mpropdef.mclassdef.bound_mtype) then continue
1631 # If the definition is defined by the type, then skip (we want the super, so e skip the current)
1632 if mtype == mpropdef.mclassdef.bound_mtype and mmodule == mpropdef.mclassdef.mmodule then continue
1633 # Else, we keep it
1634 candidates.add(mpropdef)
1635 end
1636 # Fast track for only one candidate
1637 if candidates.length <= 1 then return candidates
1638
1639 # Second, filter the most specific ones
1640 var res = new Array[MPropDef]
1641 for pd1 in candidates do
1642 var cd1 = pd1.mclassdef
1643 var c1 = cd1.mclass
1644 var keep = true
1645 for pd2 in candidates do
1646 if pd2 == pd1 then continue # do not compare with self!
1647 var cd2 = pd2.mclassdef
1648 var c2 = cd2.mclass
1649 if c2.mclass_type == c1.mclass_type then
1650 if cd2.mmodule.in_importation <= cd1.mmodule then
1651 # cd2 refines cd1; therefore we skip pd1
1652 keep = false
1653 break
1654 end
1655 else if cd2.bound_mtype.is_subtype(mmodule, null, cd1.bound_mtype) then
1656 # cd2 < cd1; therefore we skip pd1
1657 keep = false
1658 break
1659 end
1660 end
1661 if keep then
1662 res.add(pd1)
1663 end
1664 end
1665 if res.is_empty then
1666 print "All lost! {candidates.join(", ")}"
1667 # FIXME: should be abort!
1668 end
1669 return res
1670 end
1671
1672 # Return the most specific definition in the linearization of `mtype`.
1673 #
1674 # If you want to know the next properties in the linearization,
1675 # look at `MPropDef::lookup_next_definition`.
1676 #
1677 # FIXME: the linearisation is still unspecified
1678 #
1679 # REQUIRE: `not mtype.need_anchor`
1680 # REQUIRE: `mtype.has_mproperty(mmodule, self)`
1681 fun lookup_first_definition(mmodule: MModule, mtype: MType): MPROPDEF
1682 do
1683 return lookup_all_definitions(mmodule, mtype).first
1684 end
1685
1686 # Return all definitions in a linearisation order
1687 # Most speficic first, most general last
1688 fun lookup_all_definitions(mmodule: MModule, mtype: MType): Array[MPROPDEF]
1689 do
1690 assert not mtype.need_anchor
1691 if mtype isa MNullableType then mtype = mtype.mtype
1692
1693 var cache = self.lookup_all_definitions_cache[mmodule, mtype]
1694 if cache != null then return cache
1695
1696 #print "select prop {mproperty} for {mtype} in {self}"
1697 # First, select all candidates
1698 var candidates = new Array[MPROPDEF]
1699 for mpropdef in self.mpropdefs do
1700 # If the definition is not imported by the module, then skip
1701 if not mmodule.in_importation <= mpropdef.mclassdef.mmodule then continue
1702 # If the definition is not inherited by the type, then skip
1703 if not mtype.is_subtype(mmodule, null, mpropdef.mclassdef.bound_mtype) then continue
1704 # Else, we keep it
1705 candidates.add(mpropdef)
1706 end
1707 # Fast track for only one candidate
1708 if candidates.length <= 1 then
1709 self.lookup_all_definitions_cache[mmodule, mtype] = candidates
1710 return candidates
1711 end
1712
1713 mmodule.linearize_mpropdefs(candidates)
1714 candidates = candidates.reversed
1715 self.lookup_all_definitions_cache[mmodule, mtype] = candidates
1716 return candidates
1717 end
1718
1719 private var lookup_all_definitions_cache: HashMap2[MModule, MType, Array[MPROPDEF]] = new HashMap2[MModule, MType, Array[MPROPDEF]]
1720 end
1721
1722 # A global method
1723 class MMethod
1724 super MProperty
1725
1726 redef type MPROPDEF: MMethodDef
1727
1728 init(intro_mclassdef: MClassDef, name: String, visibility: MVisibility)
1729 do
1730 super
1731 end
1732
1733 # Is the property a constructor?
1734 # Warning, this property can be inherited by subclasses with or without being a constructor
1735 # therefore, you should use `is_init_for` the verify if the property is a legal constructor for a given class
1736 var is_init: Bool writable = false
1737
1738 # The the property a 'new' contructor?
1739 var is_new: Bool writable = false
1740
1741 # Is the property a legal constructor for a given class?
1742 # As usual, visibility is not considered.
1743 # FIXME not implemented
1744 fun is_init_for(mclass: MClass): Bool
1745 do
1746 return self.is_init
1747 end
1748 end
1749
1750 # A global attribute
1751 class MAttribute
1752 super MProperty
1753
1754 redef type MPROPDEF: MAttributeDef
1755
1756 init(intro_mclassdef: MClassDef, name: String, visibility: MVisibility)
1757 do
1758 super
1759 end
1760 end
1761
1762 # A global virtual type
1763 class MVirtualTypeProp
1764 super MProperty
1765
1766 redef type MPROPDEF: MVirtualTypeDef
1767
1768 init(intro_mclassdef: MClassDef, name: String, visibility: MVisibility)
1769 do
1770 super
1771 end
1772
1773 # The formal type associated to the virtual type property
1774 var mvirtualtype: MVirtualType = new MVirtualType(self)
1775 end
1776
1777 # A definition of a property (local property)
1778 #
1779 # Unlike `MProperty`, a `MPropDef` is a local definition that belong to a
1780 # specific class definition (which belong to a specific module)
1781 abstract class MPropDef
1782
1783 # The associated `MProperty` subclass.
1784 # the two specialization hierarchy are symmetric
1785 type MPROPERTY: MProperty
1786
1787 # Self class
1788 type MPROPDEF: MPropDef
1789
1790 # The origin of the definition
1791 var location: Location
1792
1793 # The class definition where the property definition is
1794 var mclassdef: MClassDef
1795
1796 # The associated global property
1797 var mproperty: MPROPERTY
1798
1799 init(mclassdef: MClassDef, mproperty: MPROPERTY, location: Location)
1800 do
1801 self.mclassdef = mclassdef
1802 self.mproperty = mproperty
1803 self.location = location
1804 mclassdef.mpropdefs.add(self)
1805 mproperty.mpropdefs.add(self)
1806 self.to_s = "{mclassdef}#{mproperty}"
1807 end
1808
1809 # Internal name combining the module, the class and the property
1810 # Example: "mymodule#MyClass#mymethod"
1811 redef var to_s: String
1812
1813 # Is self the definition that introduce the property?
1814 fun is_intro: Bool do return mproperty.intro == self
1815
1816 # Return the next definition in linearization of `mtype`.
1817 #
1818 # This method is used to determine what method is called by a super.
1819 #
1820 # REQUIRE: `not mtype.need_anchor`
1821 fun lookup_next_definition(mmodule: MModule, mtype: MType): MPROPDEF
1822 do
1823 assert not mtype.need_anchor
1824
1825 var mpropdefs = self.mproperty.lookup_all_definitions(mmodule, mtype)
1826 var i = mpropdefs.iterator
1827 while i.is_ok and i.item != self do i.next
1828 assert has_property: i.is_ok
1829 i.next
1830 assert has_next_property: i.is_ok
1831 return i.item
1832 end
1833 end
1834
1835 # A local definition of a method
1836 class MMethodDef
1837 super MPropDef
1838
1839 redef type MPROPERTY: MMethod
1840 redef type MPROPDEF: MMethodDef
1841
1842 init(mclassdef: MClassDef, mproperty: MPROPERTY, location: Location)
1843 do
1844 super
1845 end
1846
1847 # The signature attached to the property definition
1848 var msignature: nullable MSignature writable = null
1849
1850 # The the method definition abstract?
1851 var is_abstract: Bool writable = false
1852 end
1853
1854 # A local definition of an attribute
1855 class MAttributeDef
1856 super MPropDef
1857
1858 redef type MPROPERTY: MAttribute
1859 redef type MPROPDEF: MAttributeDef
1860
1861 init(mclassdef: MClassDef, mproperty: MPROPERTY, location: Location)
1862 do
1863 super
1864 end
1865
1866 # The static type of the attribute
1867 var static_mtype: nullable MType writable = null
1868 end
1869
1870 # A local definition of a virtual type
1871 class MVirtualTypeDef
1872 super MPropDef
1873
1874 redef type MPROPERTY: MVirtualTypeProp
1875 redef type MPROPDEF: MVirtualTypeDef
1876
1877 init(mclassdef: MClassDef, mproperty: MPROPERTY, location: Location)
1878 do
1879 super
1880 end
1881
1882 # The bound of the virtual type
1883 var bound: nullable MType writable = null
1884 end
1885
1886 # A kind of class.
1887 #
1888 # * `abstract_kind`
1889 # * `concrete_kind`
1890 # * `interface_kind`
1891 # * `enum_kind`
1892 # * `extern_kind`
1893 #
1894 # Note this class is basically an enum.
1895 # FIXME: use a real enum once user-defined enums are available
1896 class MClassKind
1897 redef var to_s: String
1898
1899 # Is a constructor required?
1900 var need_init: Bool
1901 private init(s: String, need_init: Bool)
1902 do
1903 self.to_s = s
1904 self.need_init = need_init
1905 end
1906 end
1907
1908 fun abstract_kind: MClassKind do return once new MClassKind("abstract class", true)
1909 fun concrete_kind: MClassKind do return once new MClassKind("class", true)
1910 fun interface_kind: MClassKind do return once new MClassKind("interface", false)
1911 fun enum_kind: MClassKind do return once new MClassKind("enum", false)
1912 fun extern_kind: MClassKind do return once new MClassKind("extern", false)