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