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