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