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