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