Merge: model: Fix minor documentation mistakes
[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 # Classes, types and properties
18 #
19 # All three concepts are defined in this same module because these are strongly connected:
20 # * types are based on classes
21 # * classes contains properties
22 # * some properties are types (virtual types)
23 #
24 # TODO: liearization, extern stuff
25 # FIXME: better handling of the types
26 module model
27
28 import mmodule
29 import mdoc
30 import ordered_tree
31 private import more_collections
32
33 redef class MEntity
34 # The visibility of the MEntity.
35 #
36 # MPackages, MGroups and MModules are always public.
37 # The visibility of `MClass` and `MProperty` is defined by the keyword used.
38 # `MClassDef` and `MPropDef` return the visibility of `MClass` and `MProperty`.
39 fun visibility: MVisibility do return public_visibility
40 end
41
42 redef class Model
43 # All known classes
44 var mclasses = new Array[MClass]
45
46 # All known properties
47 var mproperties = new Array[MProperty]
48
49 # Hierarchy of class definition.
50 #
51 # Each classdef is associated with its super-classdefs in regard to
52 # its module of definition.
53 var mclassdef_hierarchy = new POSet[MClassDef]
54
55 # Class-type hierarchy restricted to the introduction.
56 #
57 # The idea is that what is true on introduction is always true whatever
58 # the module considered.
59 # Therefore, this hierarchy is used for a fast positive subtype check.
60 #
61 # This poset will evolve in a monotonous way:
62 # * Two non connected nodes will remain unconnected
63 # * New nodes can appear with new edges
64 private var intro_mtype_specialization_hierarchy = new POSet[MClassType]
65
66 # Global overlapped class-type hierarchy.
67 # The hierarchy when all modules are combined.
68 # Therefore, this hierarchy is used for a fast negative subtype check.
69 #
70 # This poset will evolve in an anarchic way. Loops can even be created.
71 #
72 # FIXME decide what to do on loops
73 private var full_mtype_specialization_hierarchy = new POSet[MClassType]
74
75 # Collections of classes grouped by their short name
76 private var mclasses_by_name = new MultiHashMap[String, MClass]
77
78 # Return all classes named `name`.
79 #
80 # If such a class does not exist, null is returned
81 # (instead of an empty array)
82 #
83 # Visibility or modules are not considered
84 fun get_mclasses_by_name(name: String): nullable Array[MClass]
85 do
86 return mclasses_by_name.get_or_null(name)
87 end
88
89 # Collections of properties grouped by their short name
90 private var mproperties_by_name = 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 return mproperties_by_name.get_or_null(name)
101 end
102
103 # The only null type
104 var null_type = new MNullType(self)
105
106 # The only bottom type
107 var bottom_type: MBottomType = null_type.as_notnull
108
109 # Build an ordered tree with from `concerns`
110 fun concerns_tree(mconcerns: Collection[MConcern]): ConcernsTree do
111 var seen = new HashSet[MConcern]
112 var res = new ConcernsTree
113
114 var todo = new Array[MConcern]
115 todo.add_all mconcerns
116
117 while not todo.is_empty do
118 var c = todo.pop
119 if seen.has(c) then continue
120 var pc = c.parent_concern
121 if pc == null then
122 res.add(null, c)
123 else
124 res.add(pc, c)
125 todo.add(pc)
126 end
127 seen.add(c)
128 end
129
130 return res
131 end
132 end
133
134 # An OrderedTree bound to MEntity.
135 #
136 # We introduce a new class so it can be easily refined by tools working
137 # with a Model.
138 class MEntityTree
139 super OrderedTree[MEntity]
140 end
141
142 # A MEntityTree borned to MConcern.
143 #
144 # TODO remove when nitdoc is fully merged with model_collect
145 class ConcernsTree
146 super OrderedTree[MConcern]
147 end
148
149 redef class MModule
150 # All the classes introduced in the module
151 var intro_mclasses = new Array[MClass]
152
153 # All the class definitions of the module
154 # (introduction and refinement)
155 var mclassdefs = new Array[MClassDef]
156
157 private var mclassdef_sorter: MClassDefSorter is lazy do
158 return new MClassDefSorter(self)
159 end
160
161 private var mpropdef_sorter: MPropDefSorter is lazy do
162 return new MPropDefSorter(self)
163 end
164
165 # Does the current module has a given class `mclass`?
166 # Return true if the mmodule introduces, refines or imports a class.
167 # Visibility is not considered.
168 fun has_mclass(mclass: MClass): Bool
169 do
170 return self.in_importation <= mclass.intro_mmodule
171 end
172
173 # Full hierarchy of introduced and imported classes.
174 #
175 # Create a new hierarchy got by flattening the classes for the module
176 # and its imported modules.
177 # Visibility is not considered.
178 #
179 # Note: this function is expensive and is usually used for the main
180 # module of a program only. Do not use it to do your own subtype
181 # functions.
182 fun flatten_mclass_hierarchy: POSet[MClass]
183 do
184 var res = self.flatten_mclass_hierarchy_cache
185 if res != null then return res
186 res = new POSet[MClass]
187 for m in self.in_importation.greaters do
188 for cd in m.mclassdefs do
189 var c = cd.mclass
190 res.add_node(c)
191 for s in cd.supertypes do
192 res.add_edge(c, s.mclass)
193 end
194 end
195 end
196 self.flatten_mclass_hierarchy_cache = res
197 return res
198 end
199
200 # Sort a given array of classes using the linearization order of the module
201 # The most general is first, the most specific is last
202 fun linearize_mclasses(mclasses: Array[MClass])
203 do
204 self.flatten_mclass_hierarchy.sort(mclasses)
205 end
206
207 # Sort a given array of class definitions using the linearization order of the module
208 # the refinement link is stronger than the specialisation link
209 # The most general is first, the most specific is last
210 fun linearize_mclassdefs(mclassdefs: Array[MClassDef])
211 do
212 mclassdef_sorter.sort(mclassdefs)
213 end
214
215 # Sort a given array of property definitions using the linearization order of the module
216 # the refinement link is stronger than the specialisation link
217 # The most general is first, the most specific is last
218 fun linearize_mpropdefs(mpropdefs: Array[MPropDef])
219 do
220 mpropdef_sorter.sort(mpropdefs)
221 end
222
223 private var flatten_mclass_hierarchy_cache: nullable POSet[MClass] = null
224
225 # The primitive type `Object`, the root of the class hierarchy
226 var object_type: MClassType = self.get_primitive_class("Object").mclass_type is lazy
227
228 # The type `Pointer`, super class to all extern classes
229 var pointer_type: MClassType = self.get_primitive_class("Pointer").mclass_type is lazy
230
231 # The primitive type `Bool`
232 var bool_type: MClassType = self.get_primitive_class("Bool").mclass_type is lazy
233
234 # The primitive type `Int`
235 var int_type: MClassType = self.get_primitive_class("Int").mclass_type is lazy
236
237 # The primitive type `Byte`
238 var byte_type: MClassType = self.get_primitive_class("Byte").mclass_type is lazy
239
240 # The primitive type `Int8`
241 var int8_type: MClassType = self.get_primitive_class("Int8").mclass_type is lazy
242
243 # The primitive type `Int16`
244 var int16_type: MClassType = self.get_primitive_class("Int16").mclass_type is lazy
245
246 # The primitive type `UInt16`
247 var uint16_type: MClassType = self.get_primitive_class("UInt16").mclass_type is lazy
248
249 # The primitive type `Int32`
250 var int32_type: MClassType = self.get_primitive_class("Int32").mclass_type is lazy
251
252 # The primitive type `UInt32`
253 var uint32_type: MClassType = self.get_primitive_class("UInt32").mclass_type is lazy
254
255 # The primitive type `Char`
256 var char_type: MClassType = self.get_primitive_class("Char").mclass_type is lazy
257
258 # The primitive type `Float`
259 var float_type: MClassType = self.get_primitive_class("Float").mclass_type is lazy
260
261 # The primitive type `String`
262 var string_type: MClassType = self.get_primitive_class("String").mclass_type is lazy
263
264 # The primitive type `CString`
265 var c_string_type: MClassType = self.get_primitive_class("CString").mclass_type is lazy
266
267 # A primitive type of `Array`
268 fun array_type(elt_type: MType): MClassType do return array_class.get_mtype([elt_type])
269
270 # The primitive class `Array`
271 var array_class: MClass = self.get_primitive_class("Array") is lazy
272
273 # A primitive type of `NativeArray`
274 fun native_array_type(elt_type: MType): MClassType do return native_array_class.get_mtype([elt_type])
275
276 # The primitive class `NativeArray`
277 var native_array_class: MClass = self.get_primitive_class("NativeArray") is lazy
278
279 # The primitive type `Sys`, the main type of the program, if any
280 fun sys_type: nullable MClassType
281 do
282 var clas = self.model.get_mclasses_by_name("Sys")
283 if clas == null then return null
284 return get_primitive_class("Sys").mclass_type
285 end
286
287 # The primitive type `Finalizable`
288 # Used to tag classes that need to be finalized.
289 fun finalizable_type: nullable MClassType
290 do
291 var clas = self.model.get_mclasses_by_name("Finalizable")
292 if clas == null then return null
293 return get_primitive_class("Finalizable").mclass_type
294 end
295
296 # Force to get the primitive class named `name` or abort
297 fun get_primitive_class(name: String): MClass
298 do
299 var cla = self.model.get_mclasses_by_name(name)
300 # Filter classes by introducing module
301 if cla != null then cla = [for c in cla do if self.in_importation <= c.intro_mmodule then c]
302 if cla == null or cla.is_empty then
303 if name == "Bool" and self.model.get_mclasses_by_name("Object") != null then
304 # Bool is injected because it is needed by engine to code the result
305 # of the implicit casts.
306 var loc = model.no_location
307 var c = new MClass(self, name, loc, null, enum_kind, public_visibility)
308 var cladef = new MClassDef(self, c.mclass_type, loc)
309 cladef.set_supertypes([object_type])
310 cladef.add_in_hierarchy
311 return c
312 end
313 print_error("Fatal Error: no primitive class {name} in {self}")
314 exit(1)
315 abort
316 end
317 if cla.length != 1 then
318 var msg = "Fatal Error: more than one primitive class {name} in {self}:"
319 for c in cla do msg += " {c.full_name}"
320 print_error msg
321 #exit(1)
322 end
323 return cla.first
324 end
325
326 # Try to get the primitive method named `name` on the type `recv`
327 fun try_get_primitive_method(name: String, recv: MClass): nullable MMethod
328 do
329 var props = self.model.get_mproperties_by_name(name)
330 if props == null then return null
331 var res: nullable MMethod = null
332 var recvtype = recv.intro.bound_mtype
333 for mprop in props do
334 assert mprop isa MMethod
335 if not recvtype.has_mproperty(self, mprop) then continue
336 if res == null then
337 res = mprop
338 else if res != mprop then
339 print_error("Fatal Error: ambigous property name '{name}'; conflict between {mprop.full_name} and {res.full_name}")
340 abort
341 end
342 end
343 return res
344 end
345 end
346
347 private class MClassDefSorter
348 super Comparator
349 redef type COMPARED: MClassDef
350 var mmodule: MModule
351 redef fun compare(a, b)
352 do
353 var ca = a.mclass
354 var cb = b.mclass
355 if ca != cb then return mmodule.flatten_mclass_hierarchy.compare(ca, cb)
356 return mmodule.model.mclassdef_hierarchy.compare(a, b)
357 end
358 end
359
360 private class MPropDefSorter
361 super Comparator
362 redef type COMPARED: MPropDef
363 var mmodule: MModule
364
365 redef fun compare(pa, pb)
366 do
367 var a = pa.mclassdef
368 var b = pb.mclassdef
369 return mmodule.mclassdef_sorter.compare(a, b)
370 end
371 end
372
373 # A named class
374 #
375 # `MClass`es are global to the model; it means that a `MClass` is not bound
376 # to a specific `MModule`.
377 #
378 # This characteristic helps the reasoning about classes in a program since a
379 # single `MClass` object always denote the same class.
380 #
381 # The drawback is that classes (`MClass`) contain almost nothing by themselves.
382 # These do not really have properties nor belong to a hierarchy since the property and the
383 # hierarchy of a class depends of the refinement in the modules.
384 #
385 # Most services on classes require the precision of a module, and no one can asks what are
386 # the super-classes of a class nor what are properties of a class without precising what is
387 # the module considered.
388 #
389 # For instance, during the typing of a source-file, the module considered is the module of the file.
390 # eg. the question *is the method `foo` exists in the class `Bar`?* must be reformulated into
391 # *is the method `foo` exists in the class `Bar` in the current module?*
392 #
393 # During some global analysis, the module considered may be the main module of the program.
394 class MClass
395 super MEntity
396
397 # The module that introduce the class
398 #
399 # While classes are not bound to a specific module,
400 # the introducing module is used for naming and visibility.
401 var intro_mmodule: MModule
402
403 # The short name of the class
404 # In Nit, the name of a class cannot evolve in refinements
405 redef var name
406
407 redef var location
408
409 # The canonical name of the class
410 #
411 # It is the name of the class prefixed by the full_name of the `intro_mmodule`
412 # Example: `"owner::module::MyClass"`
413 redef var full_name is lazy do
414 return "{self.intro_mmodule.namespace_for(visibility)}::{name}"
415 end
416
417 redef var c_name is lazy do
418 return "{intro_mmodule.c_namespace_for(visibility)}__{name.to_cmangle}"
419 end
420
421 # The number of generic formal parameters
422 # 0 if the class is not generic
423 var arity: Int is noinit
424
425 # Each generic formal parameters in order.
426 # is empty if the class is not generic
427 var mparameters = new Array[MParameterType]
428
429 # A string version of the signature a generic class.
430 #
431 # eg. `Map[K: nullable Object, V: nullable Object]`
432 #
433 # If the class in non generic the name is just given.
434 #
435 # eg. `Object`
436 fun signature_to_s: String
437 do
438 if arity == 0 then return name
439 var res = new FlatBuffer
440 res.append name
441 res.append "["
442 for i in [0..arity[ do
443 if i > 0 then res.append ", "
444 res.append mparameters[i].name
445 res.append ": "
446 res.append intro.bound_mtype.arguments[i].to_s
447 end
448 res.append "]"
449 return res.to_s
450 end
451
452 # Initialize `mparameters` from their names.
453 protected fun setup_parameter_names(parameter_names: nullable Array[String]) is
454 autoinit
455 do
456 if parameter_names == null then
457 self.arity = 0
458 else
459 self.arity = parameter_names.length
460 end
461
462 # Create the formal parameter types
463 if arity > 0 then
464 assert parameter_names != null
465 var mparametertypes = new Array[MParameterType]
466 for i in [0..arity[ do
467 var mparametertype = new MParameterType(self, i, parameter_names[i])
468 mparametertypes.add(mparametertype)
469 end
470 self.mparameters = mparametertypes
471 var mclass_type = new MGenericType(self, mparametertypes)
472 self.mclass_type = mclass_type
473 self.get_mtype_cache[mparametertypes] = mclass_type
474 else
475 self.mclass_type = new MClassType(self)
476 end
477 end
478
479 # The kind of the class (interface, abstract class, etc.)
480 #
481 # In Nit, the kind of a class cannot evolve in refinements.
482 var kind: MClassKind
483
484 # The visibility of the class
485 #
486 # In Nit, the visibility of a class cannot evolve in refinements.
487 redef var visibility
488
489 init
490 do
491 intro_mmodule.intro_mclasses.add(self)
492 var model = intro_mmodule.model
493 model.mclasses_by_name.add_one(name, self)
494 model.mclasses.add(self)
495 end
496
497 redef fun model do return intro_mmodule.model
498
499 # All class definitions (introduction and refinements)
500 var mclassdefs = new Array[MClassDef]
501
502 # Alias for `name`
503 redef fun to_s do return self.name
504
505 # The definition that introduces the class.
506 #
507 # Warning: such a definition may not exist in the early life of the object.
508 # In this case, the method will abort.
509 #
510 # Use `try_intro` instead.
511 var intro: MClassDef is noinit
512
513 # The definition that introduces the class or `null` if not yet known.
514 #
515 # SEE: `intro`
516 fun try_intro: nullable MClassDef do
517 if isset _intro then return _intro else return null
518 end
519
520 # Return the class `self` in the class hierarchy of the module `mmodule`.
521 #
522 # SEE: `MModule::flatten_mclass_hierarchy`
523 # REQUIRE: `mmodule.has_mclass(self)`
524 fun in_hierarchy(mmodule: MModule): POSetElement[MClass]
525 do
526 return mmodule.flatten_mclass_hierarchy[self]
527 end
528
529 # The principal static type of the class.
530 #
531 # For non-generic class, `mclass_type` is the only `MClassType` based
532 # on self.
533 #
534 # For a generic class, the arguments are the formal parameters.
535 # i.e.: for the class `Array[E:Object]`, the `mclass_type` is `Array[E]`.
536 # If you want `Array[Object]`, see `MClassDef::bound_mtype`.
537 #
538 # For generic classes, the mclass_type is also the way to get a formal
539 # generic parameter type.
540 #
541 # To get other types based on a generic class, see `get_mtype`.
542 #
543 # ENSURE: `mclass_type.mclass == self`
544 var mclass_type: MClassType is noinit
545
546 # Return a generic type based on the class
547 # Is the class is not generic, then the result is `mclass_type`
548 #
549 # REQUIRE: `mtype_arguments.length == self.arity`
550 fun get_mtype(mtype_arguments: Array[MType]): MClassType
551 do
552 assert mtype_arguments.length == self.arity
553 if self.arity == 0 then return self.mclass_type
554 var res = get_mtype_cache.get_or_null(mtype_arguments)
555 if res != null then return res
556 res = new MGenericType(self, mtype_arguments)
557 self.get_mtype_cache[mtype_arguments.to_a] = res
558 return res
559 end
560
561 private var get_mtype_cache = new HashMap[Array[MType], MGenericType]
562
563 # Is there a `new` factory to allow the pseudo instantiation?
564 var has_new_factory = false is writable
565
566 # Is `self` a standard or abstract class kind?
567 var is_class: Bool is lazy do return kind == concrete_kind or kind == abstract_kind
568
569 # Is `self` an interface kind?
570 var is_interface: Bool is lazy do return kind == interface_kind
571
572 # Is `self` an enum kind?
573 var is_enum: Bool is lazy do return kind == enum_kind
574
575 # Is `self` and abstract class?
576 var is_abstract: Bool is lazy do return kind == abstract_kind
577
578 redef fun mdoc_or_fallback
579 do
580 # Don’t use `intro.mdoc_or_fallback` because it would create an infinite
581 # recursion.
582 return intro.mdoc
583 end
584 end
585
586
587 # A definition (an introduction or a refinement) of a class in a module
588 #
589 # A `MClassDef` is associated with an explicit (or almost) definition of a
590 # class. Unlike `MClass`, a `MClassDef` is a local definition that belong to
591 # a specific class and a specific module, and contains declarations like super-classes
592 # or properties.
593 #
594 # It is the class definitions that are the backbone of most things in the model:
595 # ClassDefs are defined with regard with other classdefs.
596 # Refinement and specialization are combined to produce a big poset called the `Model::mclassdef_hierarchy`.
597 #
598 # Moreover, the extension and the intention of types is defined by looking at the MClassDefs.
599 class MClassDef
600 super MEntity
601
602 # The module where the definition is
603 var mmodule: MModule
604
605 # The associated `MClass`
606 var mclass: MClass is noinit
607
608 # The bounded type associated to the mclassdef
609 #
610 # For a non-generic class, `bound_mtype` and `mclass.mclass_type`
611 # are the same type.
612 #
613 # Example:
614 # For the classdef Array[E: Object], the bound_mtype is Array[Object].
615 # If you want Array[E], then see `mclass.mclass_type`
616 #
617 # ENSURE: `bound_mtype.mclass == self.mclass`
618 var bound_mtype: MClassType
619
620 redef var location
621
622 redef fun visibility do return mclass.visibility
623
624 # Internal name combining the module and the class
625 # Example: "mymodule$MyClass"
626 redef var to_s is noinit
627
628 init
629 do
630 self.mclass = bound_mtype.mclass
631 mmodule.mclassdefs.add(self)
632 mclass.mclassdefs.add(self)
633 if mclass.intro_mmodule == mmodule then
634 assert not isset mclass._intro
635 mclass.intro = self
636 end
637 self.to_s = "{mmodule}${mclass}"
638 end
639
640 # Actually the name of the `mclass`
641 redef fun name do return mclass.name
642
643 # The module and class name separated by a '$'.
644 #
645 # The short-name of the class is used for introduction.
646 # Example: "my_module$MyClass"
647 #
648 # The full-name of the class is used for refinement.
649 # Example: "my_module$intro_module::MyClass"
650 redef var full_name is lazy do
651 if is_intro then
652 # public gives 'p$A'
653 # private gives 'p::m$A'
654 return "{mmodule.namespace_for(mclass.visibility)}${mclass.name}"
655 else if mclass.intro_mmodule.mpackage != mmodule.mpackage then
656 # public gives 'q::n$p::A'
657 # private gives 'q::n$p::m::A'
658 return "{mmodule.full_name}${mclass.full_name}"
659 else if mclass.visibility > private_visibility then
660 # public gives 'p::n$A'
661 return "{mmodule.full_name}${mclass.name}"
662 else
663 # private gives 'p::n$::m::A' (redundant p is omitted)
664 return "{mmodule.full_name}$::{mclass.intro_mmodule.name}::{mclass.name}"
665 end
666 end
667
668 redef var c_name is lazy do
669 if is_intro then
670 return "{mmodule.c_namespace_for(mclass.visibility)}___{mclass.c_name}"
671 else if mclass.intro_mmodule.mpackage == mmodule.mpackage and mclass.visibility > private_visibility then
672 return "{mmodule.c_name}___{mclass.name.to_cmangle}"
673 else
674 return "{mmodule.c_name}___{mclass.c_name}"
675 end
676 end
677
678 redef fun model do return mmodule.model
679
680 # All declared super-types
681 # FIXME: quite ugly but not better idea yet
682 var supertypes = new Array[MClassType]
683
684 # Register some super-types for the class (ie "super SomeType")
685 #
686 # The hierarchy must not already be set
687 # REQUIRE: `self.in_hierarchy == null`
688 fun set_supertypes(supertypes: Array[MClassType])
689 do
690 assert unique_invocation: self.in_hierarchy == null
691 var mmodule = self.mmodule
692 var model = mmodule.model
693 var mtype = self.bound_mtype
694
695 for supertype in supertypes do
696 self.supertypes.add(supertype)
697
698 # Register in full_type_specialization_hierarchy
699 model.full_mtype_specialization_hierarchy.add_edge(mtype, supertype)
700 # Register in intro_type_specialization_hierarchy
701 if mclass.intro_mmodule == mmodule and supertype.mclass.intro_mmodule == mmodule then
702 model.intro_mtype_specialization_hierarchy.add_edge(mtype, supertype)
703 end
704 end
705
706 end
707
708 # Collect the super-types (set by set_supertypes) to build the hierarchy
709 #
710 # This function can only invoked once by class
711 # REQUIRE: `self.in_hierarchy == null`
712 # ENSURE: `self.in_hierarchy != null`
713 fun add_in_hierarchy
714 do
715 assert unique_invocation: self.in_hierarchy == null
716 var model = mmodule.model
717 var res = model.mclassdef_hierarchy.add_node(self)
718 self.in_hierarchy = res
719 var mtype = self.bound_mtype
720
721 # Here we need to connect the mclassdef to its pairs in the mclassdef_hierarchy
722 # The simpliest way is to attach it to collect_mclassdefs
723 for mclassdef in mtype.collect_mclassdefs(mmodule) do
724 res.poset.add_edge(self, mclassdef)
725 end
726 end
727
728 # The view of the class definition in `mclassdef_hierarchy`
729 var in_hierarchy: nullable POSetElement[MClassDef] = null
730
731 # Is the definition the one that introduced `mclass`?
732 fun is_intro: Bool do return isset mclass._intro and mclass.intro == self
733
734 # All properties introduced by the classdef
735 var intro_mproperties = new Array[MProperty]
736
737 # All property introductions and redefinitions in `self` (not inheritance).
738 var mpropdefs = new Array[MPropDef]
739
740 # All property introductions and redefinitions (not inheritance) in `self` by its associated property.
741 var mpropdefs_by_property = new HashMap[MProperty, MPropDef]
742
743 redef fun mdoc_or_fallback do return mdoc or else mclass.mdoc_or_fallback
744 end
745
746 # A global static type
747 #
748 # MType are global to the model; it means that a `MType` is not bound to a
749 # specific `MModule`.
750 # This characteristic helps the reasoning about static types in a program
751 # since a single `MType` object always denote the same type.
752 #
753 # However, because a `MType` is global, it does not really have properties
754 # nor have subtypes to a hierarchy since the property and the class hierarchy
755 # depends of a module.
756 # Moreover, virtual types an formal generic parameter types also depends on
757 # a receiver to have sense.
758 #
759 # Therefore, most method of the types require a module and an anchor.
760 # The module is used to know what are the classes and the specialization
761 # links.
762 # The anchor is used to know what is the bound of the virtual types and formal
763 # generic parameter types.
764 #
765 # MType are not directly usable to get properties. See the `anchor_to` method
766 # and the `MClassType` class.
767 #
768 # FIXME: the order of the parameters is not the best. We mus pick on from:
769 # * foo(mmodule, anchor, othertype)
770 # * foo(othertype, anchor, mmodule)
771 # * foo(anchor, mmodule, othertype)
772 # * foo(othertype, mmodule, anchor)
773 abstract class MType
774 super MEntity
775
776 redef fun name do return to_s
777
778 # Return true if `self` is an subtype of `sup`.
779 # The typing is done using the standard typing policy of Nit.
780 #
781 # REQUIRE: `anchor == null implies not self.need_anchor and not sup.need_anchor`
782 # REQUIRE: `anchor != null implies self.can_resolve_for(anchor, null, mmodule) and sup.can_resolve_for(anchor, null, mmodule)`
783 fun is_subtype(mmodule: MModule, anchor: nullable MClassType, sup: MType): Bool
784 do
785 var sub = self
786 if sub == sup then return true
787
788 #print "1.is {sub} a {sup}? ===="
789
790 if anchor == null then
791 assert not sub.need_anchor
792 assert not sup.need_anchor
793 else
794 # First, resolve the formal types to the simplest equivalent forms in the receiver
795 assert sub.can_resolve_for(anchor, null, mmodule)
796 sub = sub.lookup_fixed(mmodule, anchor)
797 assert sup.can_resolve_for(anchor, null, mmodule)
798 sup = sup.lookup_fixed(mmodule, anchor)
799 end
800
801 # Does `sup` accept null or not?
802 # Discard the nullable marker if it exists
803 var sup_accept_null = false
804 if sup isa MNullableType then
805 sup_accept_null = true
806 sup = sup.mtype
807 else if sup isa MNotNullType then
808 sup = sup.mtype
809 else if sup isa MNullType then
810 sup_accept_null = true
811 end
812
813 # Can `sub` provide null or not?
814 # Thus we can match with `sup_accept_null`
815 # Also discard the nullable marker if it exists
816 var sub_reject_null = false
817 if sub isa MNullableType then
818 if not sup_accept_null then return false
819 sub = sub.mtype
820 else if sub isa MNotNullType then
821 sub_reject_null = true
822 sub = sub.mtype
823 else if sub isa MNullType then
824 return sup_accept_null
825 end
826 # Now the case of direct null and nullable is over.
827
828 # If `sub` is a formal type, then it is accepted if its bound is accepted
829 while sub isa MFormalType do
830 #print "3.is {sub} a {sup}?"
831
832 # A unfixed formal type can only accept itself
833 if sub == sup then return true
834
835 assert anchor != null
836 sub = sub.lookup_bound(mmodule, anchor)
837 if sub_reject_null then sub = sub.as_notnull
838
839 #print "3.is {sub} a {sup}?"
840
841 # Manage the second layer of null/nullable
842 if sub isa MNullableType then
843 if not sup_accept_null and not sub_reject_null then return false
844 sub = sub.mtype
845 else if sub isa MNotNullType then
846 sub_reject_null = true
847 sub = sub.mtype
848 else if sub isa MNullType then
849 return sup_accept_null
850 end
851 end
852 #print "4.is {sub} a {sup}? <- no more resolution"
853
854 if sub isa MBottomType or sub isa MErrorType then
855 return true
856 end
857
858 assert sub isa MClassType else print_error "{sub} <? {sup}" # It is the only remaining type
859
860 # Handle sup-type when the sub-type is class-based (other cases must have be identified before).
861 if sup isa MFormalType or sup isa MNullType or sup isa MBottomType or sup isa MErrorType then
862 # These types are not super-types of Class-based types.
863 return false
864 end
865
866 assert sup isa MClassType else print_error "got {sup} {sub.inspect}" # It is the only remaining type
867
868 # Now both are MClassType, we need to dig
869
870 if sub == sup then return true
871
872 if anchor == null then anchor = sub # UGLY: any anchor will work
873 var resolved_sub = sub.anchor_to(mmodule, anchor)
874 var res = resolved_sub.collect_mclasses(mmodule).has(sup.mclass)
875 if res == false then return false
876 if not sup isa MGenericType then return true
877 var sub2 = sub.supertype_to(mmodule, anchor, sup.mclass)
878 assert sub2.mclass == sup.mclass
879 for i in [0..sup.mclass.arity[ do
880 var sub_arg = sub2.arguments[i]
881 var sup_arg = sup.arguments[i]
882 res = sub_arg.is_subtype(mmodule, anchor, sup_arg)
883 if res == false then return false
884 end
885 return true
886 end
887
888 # The base class type on which self is based
889 #
890 # This base type is used to get property (an internally to perform
891 # unsafe type comparison).
892 #
893 # Beware: some types (like null) are not based on a class thus this
894 # method will crash
895 #
896 # Basically, this function transform the virtual types and parameter
897 # types to their bounds.
898 #
899 # Example
900 #
901 # class A end
902 # class B super A end
903 # class X end
904 # class Y super X end
905 # class G[T: A]
906 # type U: X
907 # end
908 # class H
909 # super G[B]
910 # redef type U: Y
911 # end
912 #
913 # Map[T,U] anchor_to H #-> Map[B,Y]
914 #
915 # Explanation of the example:
916 # In H, T is set to B, because "H super G[B]", and U is bound to Y,
917 # because "redef type U: Y". Therefore, Map[T, U] is bound to
918 # Map[B, Y]
919 #
920 # REQUIRE: `self.need_anchor implies anchor != null`
921 # ENSURE: `not self.need_anchor implies result == self`
922 # ENSURE: `not result.need_anchor`
923 fun anchor_to(mmodule: MModule, anchor: nullable MClassType): MType
924 do
925 if not need_anchor then return self
926 assert anchor != null and not anchor.need_anchor
927 # Just resolve to the anchor and clear all the virtual types
928 var res = self.resolve_for(anchor, null, mmodule, true)
929 assert not res.need_anchor
930 return res
931 end
932
933 # Does `self` contain a virtual type or a formal generic parameter type?
934 # In order to remove those types, you usually want to use `anchor_to`.
935 fun need_anchor: Bool do return true
936
937 # Return the supertype when adapted to a class.
938 #
939 # In Nit, for each super-class of a type, there is a equivalent super-type.
940 #
941 # Example:
942 #
943 # ~~~nitish
944 # class G[T, U] end
945 # class H[V] super G[V, Bool] end
946 #
947 # H[Int] supertype_to G #-> G[Int, Bool]
948 # ~~~
949 #
950 # REQUIRE: `super_mclass` is a super-class of `self`
951 # REQUIRE: `self.need_anchor implies anchor != null and self.can_resolve_for(anchor, null, mmodule)`
952 # ENSURE: `result.mclass = super_mclass`
953 fun supertype_to(mmodule: MModule, anchor: nullable MClassType, super_mclass: MClass): MClassType
954 do
955 if super_mclass.arity == 0 then return super_mclass.mclass_type
956 if self isa MClassType and self.mclass == super_mclass then return self
957 var resolved_self
958 if self.need_anchor then
959 assert anchor != null
960 resolved_self = self.anchor_to(mmodule, anchor)
961 else
962 resolved_self = self
963 end
964 var supertypes = resolved_self.collect_mtypes(mmodule)
965 for supertype in supertypes do
966 if supertype.mclass == super_mclass then
967 # FIXME: Here, we stop on the first goal. Should we check others and detect inconsistencies?
968 return supertype.resolve_for(self, anchor, mmodule, false)
969 end
970 end
971 abort
972 end
973
974 # Replace formals generic types in self with resolved values in `mtype`
975 # If `cleanup_virtual` is true, then virtual types are also replaced
976 # with their bounds.
977 #
978 # This function returns self if `need_anchor` is false.
979 #
980 # ## Example 1
981 #
982 # ~~~
983 # class G[E] end
984 # class H[F] super G[F] end
985 # class X[Z] end
986 # ~~~
987 #
988 # * Array[E].resolve_for(H[Int]) #-> Array[Int]
989 # * Array[E].resolve_for(G[Z], X[Int]) #-> Array[Z]
990 #
991 # Explanation of the example:
992 # * Array[E].need_anchor is true because there is a formal generic parameter type E
993 # * E makes sense for H[Int] because E is a formal parameter of G and H specialize G
994 # * Since "H[F] super G[F]", E is in fact F for H
995 # * More specifically, in H[Int], E is Int
996 # * So, in H[Int], Array[E] is Array[Int]
997 #
998 # This function is mainly used to inherit a signature.
999 # Because, unlike `anchor_to`, we do not want a full resolution of
1000 # a type but only an adapted version of it.
1001 #
1002 # ## Example 2
1003 #
1004 # ~~~
1005 # class A[E]
1006 # fun foo(e:E):E is abstract
1007 # end
1008 # class B super A[Int] end
1009 # ~~~
1010 #
1011 # The signature on foo is (e: E): E
1012 # If we resolve the signature for B, we get (e:Int):Int
1013 #
1014 # ## Example 3
1015 #
1016 # ~~~nitish
1017 # class A[E]
1018 # fun foo(e:E):E is abstract
1019 # end
1020 # class C[F]
1021 # var a: A[Array[F]]
1022 # fun bar do a.foo(x) # <- x is here
1023 # end
1024 # ~~~
1025 #
1026 # The first question is: is foo available on `a`?
1027 #
1028 # The static type of a is `A[Array[F]]`, that is an open type.
1029 # in order to find a method `foo`, whe must look at a resolved type.
1030 #
1031 # A[Array[F]].anchor_to(C[nullable Object]) #-> A[Array[nullable Object]]
1032 #
1033 # the method `foo` exists in `A[Array[nullable Object]]`, therefore `foo` exists for `a`.
1034 #
1035 # The next question is: what is the accepted types for `x`?
1036 #
1037 # the signature of `foo` is `foo(e:E)`, thus we must resolve the type E
1038 #
1039 # E.resolve_for(A[Array[F]],C[nullable Object]) #-> Array[F]
1040 #
1041 # The resolution can be done because `E` make sense for the class A (see `can_resolve_for`)
1042 #
1043 # FIXME: the parameter `cleanup_virtual` is just a bad idea, but having
1044 # two function instead of one seems also to be a bad idea.
1045 #
1046 # REQUIRE: `can_resolve_for(mtype, anchor, mmodule)`
1047 # ENSURE: `not self.need_anchor implies result == self`
1048 fun resolve_for(mtype: MType, anchor: nullable MClassType, mmodule: MModule, cleanup_virtual: Bool): MType is abstract
1049
1050 # Resolve formal type to its verbatim bound.
1051 # If the type is not formal, just return self
1052 #
1053 # The result is returned exactly as declared in the "type" property (verbatim).
1054 # So it could be another formal type.
1055 #
1056 # In case of conflicts or inconsistencies in the model, the method returns a `MErrorType`.
1057 fun lookup_bound(mmodule: MModule, resolved_receiver: MType): MType do return self
1058
1059 # Resolve the formal type to its simplest equivalent form.
1060 #
1061 # Formal types are either free or fixed.
1062 # When it is fixed, it means that it is equivalent with a simpler type.
1063 # When a formal type is free, it means that it is only equivalent with itself.
1064 # This method return the most simple equivalent type of `self`.
1065 #
1066 # This method is mainly used for subtype test in order to sanely compare fixed.
1067 #
1068 # By default, return self.
1069 # See the redefinitions for specific behavior in each kind of type.
1070 #
1071 # In case of conflicts or inconsistencies in the model, the method returns a `MErrorType`.
1072 fun lookup_fixed(mmodule: MModule, resolved_receiver: MType): MType do return self
1073
1074 # Is the type a `MErrorType` or contains an `MErrorType`?
1075 #
1076 # `MErrorType` are used in result with conflict or inconsistencies.
1077 #
1078 # See `is_legal_in` to check conformity with generic bounds.
1079 fun is_ok: Bool do return true
1080
1081 # Is the type legal in a given `mmodule` (with an optional `anchor`)?
1082 #
1083 # A type is valid if:
1084 #
1085 # * it does not contain a `MErrorType` (see `is_ok`).
1086 # * its generic formal arguments are within their bounds.
1087 fun is_legal_in(mmodule: MModule, anchor: nullable MClassType): Bool do return is_ok
1088
1089 # Can the type be resolved?
1090 #
1091 # In order to resolve open types, the formal types must make sence.
1092 #
1093 # ## Example
1094 #
1095 # class A[E]
1096 # end
1097 # class B[F]
1098 # end
1099 #
1100 # ~~~nitish
1101 # E.can_resolve_for(A[Int]) #-> true, E make sense in A
1102 #
1103 # E.can_resolve_for(B[Int]) #-> false, E does not make sense in B
1104 #
1105 # B[E].can_resolve_for(A[F], B[Object]) #-> true,
1106 # # B[E] is a red hearing only the E is important,
1107 # # E make sense in A
1108 # ~~~
1109 #
1110 # REQUIRE: `anchor != null implies not anchor.need_anchor`
1111 # REQUIRE: `mtype.need_anchor implies anchor != null and mtype.can_resolve_for(anchor, null, mmodule)`
1112 # ENSURE: `not self.need_anchor implies result == true`
1113 fun can_resolve_for(mtype: MType, anchor: nullable MClassType, mmodule: MModule): Bool is abstract
1114
1115 # Return the nullable version of the type
1116 # If the type is already nullable then self is returned
1117 fun as_nullable: MType
1118 do
1119 var res = self.as_nullable_cache
1120 if res != null then return res
1121 res = new MNullableType(self)
1122 self.as_nullable_cache = res
1123 return res
1124 end
1125
1126 # Remove the base type of a decorated (proxy) type.
1127 # Is the type is not decorated, then self is returned.
1128 #
1129 # Most of the time it is used to return the not nullable version of a nullable type.
1130 # In this case, this just remove the `nullable` notation, but the result can still contains null.
1131 # For instance if `self isa MNullType` or self is a formal type bounded by a nullable type.
1132 # If you really want to exclude the `null` value, then use `as_notnull`
1133 fun undecorate: MType
1134 do
1135 return self
1136 end
1137
1138 # Returns the not null version of the type.
1139 # That is `self` minus the `null` value.
1140 #
1141 # For most types, this return `self`.
1142 # For formal types, this returns a special `MNotNullType`
1143 fun as_notnull: MType do return self
1144
1145 private var as_nullable_cache: nullable MType = null
1146
1147
1148 # The depth of the type seen as a tree.
1149 #
1150 # * A -> 1
1151 # * G[A] -> 2
1152 # * H[A, B] -> 2
1153 # * H[G[A], B] -> 3
1154 #
1155 # Formal types have a depth of 1.
1156 # Only `MClassType` and `MFormalType` nodes are counted.
1157 fun depth: Int
1158 do
1159 return 1
1160 end
1161
1162 # The length of the type seen as a tree.
1163 #
1164 # * A -> 1
1165 # * G[A] -> 2
1166 # * H[A, B] -> 3
1167 # * H[G[A], B] -> 4
1168 #
1169 # Formal types have a length of 1.
1170 # Only `MClassType` and `MFormalType` nodes are counted.
1171 fun length: Int
1172 do
1173 return 1
1174 end
1175
1176 # Compute all the classdefs inherited/imported.
1177 # The returned set contains:
1178 # * the class definitions from `mmodule` and its imported modules
1179 # * the class definitions of this type and its super-types
1180 #
1181 # This function is used mainly internally.
1182 #
1183 # REQUIRE: `not self.need_anchor`
1184 fun collect_mclassdefs(mmodule: MModule): Set[MClassDef] is abstract
1185
1186 # Compute all the super-classes.
1187 # This function is used mainly internally.
1188 #
1189 # REQUIRE: `not self.need_anchor`
1190 fun collect_mclasses(mmodule: MModule): Set[MClass] is abstract
1191
1192 # Compute all the declared super-types.
1193 # Super-types are returned as declared in the classdefs (verbatim).
1194 # This function is used mainly internally.
1195 #
1196 # REQUIRE: `not self.need_anchor`
1197 fun collect_mtypes(mmodule: MModule): Set[MClassType] is abstract
1198
1199 # Is the property in self for a given module
1200 # This method does not filter visibility or whatever
1201 #
1202 # REQUIRE: `not self.need_anchor`
1203 fun has_mproperty(mmodule: MModule, mproperty: MProperty): Bool
1204 do
1205 assert not self.need_anchor
1206 return self.collect_mclassdefs(mmodule).has(mproperty.intro_mclassdef)
1207 end
1208 end
1209
1210 # A type based on a class.
1211 #
1212 # `MClassType` have properties (see `has_mproperty`).
1213 class MClassType
1214 super MType
1215
1216 # The associated class
1217 var mclass: MClass
1218
1219 redef fun model do return self.mclass.intro_mmodule.model
1220
1221 redef fun location do return mclass.location
1222
1223 # TODO: private init because strongly bounded to its mclass. see `mclass.mclass_type`
1224
1225 # The formal arguments of the type
1226 # ENSURE: `result.length == self.mclass.arity`
1227 var arguments = new Array[MType]
1228
1229 redef fun to_s do return mclass.to_s
1230
1231 redef fun full_name do return mclass.full_name
1232
1233 redef fun c_name do return mclass.c_name
1234
1235 redef fun need_anchor do return false
1236
1237 redef fun anchor_to(mmodule, anchor): MClassType
1238 do
1239 return super.as(MClassType)
1240 end
1241
1242 redef fun resolve_for(mtype: MType, anchor: nullable MClassType, mmodule: MModule, cleanup_virtual: Bool): MClassType do return self
1243
1244 redef fun can_resolve_for(mtype, anchor, mmodule) do return true
1245
1246 redef fun collect_mclassdefs(mmodule)
1247 do
1248 assert not self.need_anchor
1249 var cache = self.collect_mclassdefs_cache
1250 if not cache.has_key(mmodule) then
1251 self.collect_things(mmodule)
1252 end
1253 return cache[mmodule]
1254 end
1255
1256 redef fun collect_mclasses(mmodule)
1257 do
1258 if collect_mclasses_last_module == mmodule then return collect_mclasses_last_module_cache
1259 assert not self.need_anchor
1260 var cache = self.collect_mclasses_cache
1261 if not cache.has_key(mmodule) then
1262 self.collect_things(mmodule)
1263 end
1264 var res = cache[mmodule]
1265 collect_mclasses_last_module = mmodule
1266 collect_mclasses_last_module_cache = res
1267 return res
1268 end
1269
1270 private var collect_mclasses_last_module: nullable MModule = null
1271 private var collect_mclasses_last_module_cache: Set[MClass] is noinit
1272
1273 redef fun collect_mtypes(mmodule)
1274 do
1275 assert not self.need_anchor
1276 var cache = self.collect_mtypes_cache
1277 if not cache.has_key(mmodule) then
1278 self.collect_things(mmodule)
1279 end
1280 return cache[mmodule]
1281 end
1282
1283 # common implementation for `collect_mclassdefs`, `collect_mclasses`, and `collect_mtypes`.
1284 private fun collect_things(mmodule: MModule)
1285 do
1286 var res = new HashSet[MClassDef]
1287 var seen = new HashSet[MClass]
1288 var types = new HashSet[MClassType]
1289 seen.add(self.mclass)
1290 var todo = [self.mclass]
1291 while not todo.is_empty do
1292 var mclass = todo.pop
1293 #print "process {mclass}"
1294 for mclassdef in mclass.mclassdefs do
1295 if not mmodule.in_importation <= mclassdef.mmodule then continue
1296 #print " process {mclassdef}"
1297 res.add(mclassdef)
1298 for supertype in mclassdef.supertypes do
1299 types.add(supertype)
1300 var superclass = supertype.mclass
1301 if seen.has(superclass) then continue
1302 #print " add {superclass}"
1303 seen.add(superclass)
1304 todo.add(superclass)
1305 end
1306 end
1307 end
1308 collect_mclassdefs_cache[mmodule] = res
1309 collect_mclasses_cache[mmodule] = seen
1310 collect_mtypes_cache[mmodule] = types
1311 end
1312
1313 private var collect_mclassdefs_cache = new HashMap[MModule, Set[MClassDef]]
1314 private var collect_mclasses_cache = new HashMap[MModule, Set[MClass]]
1315 private var collect_mtypes_cache = new HashMap[MModule, Set[MClassType]]
1316
1317 redef fun mdoc_or_fallback do return mclass.mdoc_or_fallback
1318 end
1319
1320 # A type based on a generic class.
1321 # A generic type a just a class with additional formal generic arguments.
1322 class MGenericType
1323 super MClassType
1324
1325 redef var arguments
1326
1327 # TODO: private init because strongly bounded to its mclass. see `mclass.get_mtype`
1328
1329 init
1330 do
1331 assert self.mclass.arity == arguments.length
1332
1333 self.need_anchor = false
1334 for t in arguments do
1335 if t.need_anchor then
1336 self.need_anchor = true
1337 break
1338 end
1339 end
1340
1341 self.to_s = "{mclass}[{arguments.join(", ")}]"
1342 end
1343
1344 # The short-name of the class, then the full-name of each type arguments within brackets.
1345 # Example: `"Map[String, List[Int]]"`
1346 redef var to_s is noinit
1347
1348 # The full-name of the class, then the full-name of each type arguments within brackets.
1349 # Example: `"core::Map[core::String, core::List[core::Int]]"`
1350 redef var full_name is lazy do
1351 var args = new Array[String]
1352 for t in arguments do
1353 args.add t.full_name
1354 end
1355 return "{mclass.full_name}[{args.join(", ")}]"
1356 end
1357
1358 redef var c_name is lazy do
1359 var res = mclass.c_name
1360 # Note: because the arity is known, a prefix notation is enough
1361 for t in arguments do
1362 res += "__"
1363 res += t.c_name
1364 end
1365 return res.to_s
1366 end
1367
1368 redef var need_anchor is noinit
1369
1370 redef fun resolve_for(mtype, anchor, mmodule, cleanup_virtual)
1371 do
1372 if not need_anchor then return self
1373 assert can_resolve_for(mtype, anchor, mmodule)
1374 var types = new Array[MType]
1375 for t in arguments do
1376 types.add(t.resolve_for(mtype, anchor, mmodule, cleanup_virtual))
1377 end
1378 return mclass.get_mtype(types)
1379 end
1380
1381 redef fun can_resolve_for(mtype, anchor, mmodule)
1382 do
1383 if not need_anchor then return true
1384 for t in arguments do
1385 if not t.can_resolve_for(mtype, anchor, mmodule) then return false
1386 end
1387 return true
1388 end
1389
1390 redef fun is_ok
1391 do
1392 for t in arguments do if not t.is_ok then return false
1393 return super
1394 end
1395
1396 redef fun is_legal_in(mmodule, anchor)
1397 do
1398 var mtype
1399 if need_anchor then
1400 assert anchor != null
1401 mtype = anchor_to(mmodule, anchor)
1402 else
1403 mtype = self
1404 end
1405 if not mtype.is_ok then return false
1406 return mtype.is_subtype(mmodule, null, mtype.mclass.intro.bound_mtype)
1407 end
1408
1409 redef fun depth
1410 do
1411 var dmax = 0
1412 for a in self.arguments do
1413 var d = a.depth
1414 if d > dmax then dmax = d
1415 end
1416 return dmax + 1
1417 end
1418
1419 redef fun length
1420 do
1421 var res = 1
1422 for a in self.arguments do
1423 res += a.length
1424 end
1425 return res
1426 end
1427 end
1428
1429 # A formal type (either virtual of parametric).
1430 #
1431 # The main issue with formal types is that they offer very little information on their own
1432 # and need a context (anchor and mmodule) to be useful.
1433 abstract class MFormalType
1434 super MType
1435
1436 redef var as_notnull = new MNotNullType(self) is lazy
1437 end
1438
1439 # A virtual formal type.
1440 class MVirtualType
1441 super MFormalType
1442
1443 # The property associated with the type.
1444 # Its the definitions of this property that determine the bound or the virtual type.
1445 var mproperty: MVirtualTypeProp
1446
1447 redef fun location do return mproperty.location
1448
1449 redef fun model do return self.mproperty.intro_mclassdef.mmodule.model
1450
1451 redef fun lookup_bound(mmodule, resolved_receiver)
1452 do
1453 # There is two possible invalid cases: the vt does not exists in resolved_receiver or the bound is broken
1454 if not resolved_receiver.has_mproperty(mmodule, mproperty) then return new MErrorType(model)
1455 return lookup_single_definition(mmodule, resolved_receiver).bound or else new MErrorType(model)
1456 end
1457
1458 private fun lookup_single_definition(mmodule: MModule, resolved_receiver: MType): MVirtualTypeDef
1459 do
1460 assert not resolved_receiver.need_anchor
1461 var props = self.mproperty.lookup_definitions(mmodule, resolved_receiver)
1462 if props.is_empty then
1463 abort
1464 else if props.length == 1 then
1465 return props.first
1466 end
1467 var types = new ArraySet[MType]
1468 var res = props.first
1469 for p in props do
1470 types.add(p.bound.as(not null))
1471 if not res.is_fixed then res = p
1472 end
1473 if types.length == 1 then
1474 return res
1475 end
1476 abort
1477 end
1478
1479 # A VT is fixed when:
1480 # * the VT is (re-)defined with the annotation `is fixed`
1481 # * the VT is (indirectly) bound to an enum class (see `enum_kind`) since there is no subtype possible
1482 # * the receiver is an enum class since there is no subtype possible
1483 redef fun lookup_fixed(mmodule: MModule, resolved_receiver: MType): MType
1484 do
1485 assert not resolved_receiver.need_anchor
1486 resolved_receiver = resolved_receiver.undecorate
1487 assert resolved_receiver isa MClassType # It is the only remaining type
1488
1489 var prop = lookup_single_definition(mmodule, resolved_receiver)
1490 var res = prop.bound
1491 if res == null then return new MErrorType(model)
1492
1493 # Recursively lookup the fixed result
1494 res = res.lookup_fixed(mmodule, resolved_receiver)
1495
1496 # 1. For a fixed VT, return the resolved bound
1497 if prop.is_fixed then return res
1498
1499 # 2. For a enum boud, return the bound
1500 if res isa MClassType and res.mclass.kind == enum_kind then return res
1501
1502 # 3. for a enum receiver return the bound
1503 if resolved_receiver.mclass.kind == enum_kind then return res
1504
1505 return self
1506 end
1507
1508 redef fun resolve_for(mtype, anchor, mmodule, cleanup_virtual)
1509 do
1510 if not cleanup_virtual then return self
1511 assert can_resolve_for(mtype, anchor, mmodule)
1512
1513 if mproperty.is_selftype then return mtype
1514
1515 # self is a virtual type declared (or inherited) in mtype
1516 # The point of the function it to get the bound of the virtual type that make sense for mtype
1517 # But because mtype is maybe a virtual/formal type, we need to get a real receiver first
1518 #print "{class_name}: {self}/{mtype}/{anchor}?"
1519 var resolved_receiver
1520 if mtype.need_anchor then
1521 assert anchor != null
1522 resolved_receiver = mtype.resolve_for(anchor, null, mmodule, true)
1523 else
1524 resolved_receiver = mtype
1525 end
1526 # Now, we can get the bound
1527 var verbatim_bound = lookup_bound(mmodule, resolved_receiver)
1528 # The bound is exactly as declared in the "type" property, so we must resolve it again
1529 var res = verbatim_bound.resolve_for(mtype, anchor, mmodule, cleanup_virtual)
1530
1531 return res
1532 end
1533
1534 redef fun can_resolve_for(mtype, anchor, mmodule)
1535 do
1536 if mtype.need_anchor then
1537 assert anchor != null
1538 mtype = mtype.anchor_to(mmodule, anchor)
1539 end
1540 return mtype.has_mproperty(mmodule, mproperty)
1541 end
1542
1543 redef fun to_s do return self.mproperty.to_s
1544
1545 redef fun full_name do return self.mproperty.full_name
1546
1547 redef fun c_name do return self.mproperty.c_name
1548
1549 redef fun mdoc_or_fallback do return mproperty.mdoc_or_fallback
1550 end
1551
1552 # The type associated to a formal parameter generic type of a class
1553 #
1554 # Each parameter type is associated to a specific class.
1555 # It means that all refinements of a same class "share" the parameter type,
1556 # but that a generic subclass has its own parameter types.
1557 #
1558 # However, in the sense of the meta-model, a parameter type of a class is
1559 # a valid type in a subclass. The "in the sense of the meta-model" is
1560 # important because, in the Nit language, the programmer cannot refers
1561 # directly to the parameter types of the super-classes.
1562 #
1563 # Example:
1564 #
1565 # class A[E]
1566 # fun e: E is abstract
1567 # end
1568 # class B[F]
1569 # super A[Array[F]]
1570 # end
1571 #
1572 # In the class definition B[F], `F` is a valid type but `E` is not.
1573 # However, `self.e` is a valid method call, and the signature of `e` is
1574 # declared `e: E`.
1575 #
1576 # Note that parameter types are shared among class refinements.
1577 # Therefore parameter only have an internal name (see `to_s` for details).
1578 class MParameterType
1579 super MFormalType
1580
1581 # The generic class where the parameter belong
1582 var mclass: MClass
1583
1584 redef fun model do return self.mclass.intro_mmodule.model
1585
1586 redef fun location do return mclass.location
1587
1588 # The position of the parameter (0 for the first parameter)
1589 # FIXME: is `position` a better name?
1590 var rank: Int
1591
1592 redef var name
1593
1594 redef fun to_s do return name
1595
1596 redef var full_name is lazy do return "{mclass.full_name}::{name}"
1597
1598 redef var c_name is lazy do return mclass.c_name + "__" + "#{name}".to_cmangle
1599
1600 redef fun lookup_bound(mmodule: MModule, resolved_receiver: MType): MType
1601 do
1602 assert not resolved_receiver.need_anchor
1603 resolved_receiver = resolved_receiver.undecorate
1604 assert resolved_receiver isa MClassType # It is the only remaining type
1605 var goalclass = self.mclass
1606 if resolved_receiver.mclass == goalclass then
1607 return resolved_receiver.arguments[self.rank]
1608 end
1609 var supertypes = resolved_receiver.collect_mtypes(mmodule)
1610 for t in supertypes do
1611 if t.mclass == goalclass then
1612 # Yeah! c specialize goalclass with a "super `t'". So the question is what is the argument of f
1613 # FIXME: Here, we stop on the first goal. Should we check others and detect inconsistencies?
1614 var res = t.arguments[self.rank]
1615 return res
1616 end
1617 end
1618 # Cannot found `self` in `resolved_receiver`
1619 return new MErrorType(model)
1620 end
1621
1622 # A PT is fixed when:
1623 # * Its bound is a enum class (see `enum_kind`).
1624 # The PT is just useless, but it is still a case.
1625 # * More usually, the `resolved_receiver` is a subclass of `self.mclass`,
1626 # so it is necessarily fixed in a `super` clause, either with a normal type
1627 # or with another PT.
1628 # See `resolve_for` for examples about related issues.
1629 redef fun lookup_fixed(mmodule: MModule, resolved_receiver: MType): MType
1630 do
1631 assert not resolved_receiver.need_anchor
1632 resolved_receiver = resolved_receiver.undecorate
1633 assert resolved_receiver isa MClassType # It is the only remaining type
1634 var res = self.resolve_for(resolved_receiver.mclass.mclass_type, resolved_receiver, mmodule, false)
1635 return res
1636 end
1637
1638 redef fun resolve_for(mtype, anchor, mmodule, cleanup_virtual)
1639 do
1640 assert can_resolve_for(mtype, anchor, mmodule)
1641 #print "{class_name}: {self}/{mtype}/{anchor}?"
1642
1643 if mtype isa MGenericType and mtype.mclass == self.mclass then
1644 var res = mtype.arguments[self.rank]
1645 if anchor != null and res.need_anchor then
1646 # Maybe the result can be resolved more if are bound to a final class
1647 var r2 = res.anchor_to(mmodule, anchor)
1648 if r2 isa MClassType and r2.mclass.kind == enum_kind then return r2
1649 end
1650 return res
1651 end
1652
1653 # self is a parameter type of mtype (or of a super-class of mtype)
1654 # The point of the function it to get the bound of the virtual type that make sense for mtype
1655 # But because mtype is maybe a virtual/formal type, we need to get a real receiver first
1656 # FIXME: What happens here is far from clear. Thus this part must be validated and clarified
1657 var resolved_receiver
1658 if mtype.need_anchor then
1659 assert anchor != null
1660 resolved_receiver = mtype.resolve_for(anchor.mclass.mclass_type, anchor, mmodule, true)
1661 else
1662 resolved_receiver = mtype
1663 end
1664 if resolved_receiver isa MNullableType then resolved_receiver = resolved_receiver.mtype
1665 if resolved_receiver isa MParameterType then
1666 assert anchor != null
1667 assert resolved_receiver.mclass == anchor.mclass
1668 resolved_receiver = anchor.arguments[resolved_receiver.rank]
1669 if resolved_receiver isa MNullableType then resolved_receiver = resolved_receiver.mtype
1670 end
1671 assert resolved_receiver isa MClassType # It is the only remaining type
1672
1673 # Eh! The parameter is in the current class.
1674 # So we return the corresponding argument, no mater what!
1675 if resolved_receiver.mclass == self.mclass then
1676 var res = resolved_receiver.arguments[self.rank]
1677 #print "{class_name}: {self}/{mtype}/{anchor} -> direct {res}"
1678 return res
1679 end
1680
1681 if resolved_receiver.need_anchor then
1682 assert anchor != null
1683 resolved_receiver = resolved_receiver.resolve_for(anchor, null, mmodule, false)
1684 end
1685 # Now, we can get the bound
1686 var verbatim_bound = lookup_bound(mmodule, resolved_receiver)
1687 # The bound is exactly as declared in the "type" property, so we must resolve it again
1688 var res = verbatim_bound.resolve_for(mtype, anchor, mmodule, cleanup_virtual)
1689
1690 #print "{class_name}: {self}/{mtype}/{anchor} -> indirect {res}"
1691
1692 return res
1693 end
1694
1695 redef fun can_resolve_for(mtype, anchor, mmodule)
1696 do
1697 if mtype.need_anchor then
1698 assert anchor != null
1699 mtype = mtype.anchor_to(mmodule, anchor)
1700 end
1701 return mtype.collect_mclassdefs(mmodule).has(mclass.intro)
1702 end
1703 end
1704
1705 # A type that decorates another type.
1706 #
1707 # The point of this class is to provide a common implementation of sevices that just forward to the original type.
1708 # Specific decorator are expected to redefine (or to extend) the default implementation as this suit them.
1709 abstract class MProxyType
1710 super MType
1711 # The base type
1712 var mtype: MType
1713
1714 redef fun location do return mtype.location
1715
1716 redef fun model do return self.mtype.model
1717 redef fun need_anchor do return mtype.need_anchor
1718 redef fun as_nullable do return mtype.as_nullable
1719 redef fun as_notnull do return mtype.as_notnull
1720 redef fun undecorate do return mtype.undecorate
1721 redef fun resolve_for(mtype, anchor, mmodule, cleanup_virtual)
1722 do
1723 var res = self.mtype.resolve_for(mtype, anchor, mmodule, cleanup_virtual)
1724 return res
1725 end
1726
1727 redef fun can_resolve_for(mtype, anchor, mmodule)
1728 do
1729 return self.mtype.can_resolve_for(mtype, anchor, mmodule)
1730 end
1731
1732 redef fun is_ok do return mtype.is_ok
1733
1734 redef fun is_legal_in(mmodule, anchor) do return mtype.is_legal_in(mmodule, anchor)
1735
1736 redef fun lookup_fixed(mmodule, resolved_receiver)
1737 do
1738 var t = mtype.lookup_fixed(mmodule, resolved_receiver)
1739 return t
1740 end
1741
1742 redef fun depth do return self.mtype.depth
1743
1744 redef fun length do return self.mtype.length
1745
1746 redef fun collect_mclassdefs(mmodule)
1747 do
1748 assert not self.need_anchor
1749 return self.mtype.collect_mclassdefs(mmodule)
1750 end
1751
1752 redef fun collect_mclasses(mmodule)
1753 do
1754 assert not self.need_anchor
1755 return self.mtype.collect_mclasses(mmodule)
1756 end
1757
1758 redef fun collect_mtypes(mmodule)
1759 do
1760 assert not self.need_anchor
1761 return self.mtype.collect_mtypes(mmodule)
1762 end
1763 end
1764
1765 # A type prefixed with "nullable"
1766 class MNullableType
1767 super MProxyType
1768
1769 init
1770 do
1771 self.to_s = "nullable {mtype}"
1772 end
1773
1774 redef var to_s is noinit
1775
1776 redef var full_name is lazy do return "nullable {mtype.full_name}"
1777
1778 redef var c_name is lazy do return "nullable__{mtype.c_name}"
1779
1780 redef fun as_nullable do return self
1781 redef fun resolve_for(mtype, anchor, mmodule, cleanup_virtual)
1782 do
1783 var res = super
1784 return res.as_nullable
1785 end
1786
1787 # Efficiently returns `mtype.lookup_fixed(mmodule, resolved_receiver).as_nullable`
1788 redef fun lookup_fixed(mmodule, resolved_receiver)
1789 do
1790 var t = super
1791 if t == mtype then return self
1792 return t.as_nullable
1793 end
1794 end
1795
1796 # A non-null version of a formal type.
1797 #
1798 # When a formal type in bounded to a nullable type, this is the type of the not null version of it.
1799 class MNotNullType
1800 super MProxyType
1801
1802 redef fun to_s do return "not null {mtype}"
1803 redef var full_name is lazy do return "not null {mtype.full_name}"
1804 redef var c_name is lazy do return "notnull__{mtype.c_name}"
1805
1806 redef fun as_notnull do return self
1807
1808 redef fun resolve_for(mtype, anchor, mmodule, cleanup_virtual)
1809 do
1810 var res = super
1811 return res.as_notnull
1812 end
1813
1814 # Efficiently returns `mtype.lookup_fixed(mmodule, resolved_receiver).as_notnull`
1815 redef fun lookup_fixed(mmodule, resolved_receiver)
1816 do
1817 var t = super
1818 if t == mtype then return self
1819 return t.as_notnull
1820 end
1821 end
1822
1823 # The type of the only value null
1824 #
1825 # The is only one null type per model, see `MModel::null_type`.
1826 class MNullType
1827 super MType
1828 redef var model
1829 redef fun to_s do return "null"
1830 redef fun full_name do return "null"
1831 redef fun c_name do return "null"
1832 redef fun as_nullable do return self
1833
1834 redef var as_notnull: MBottomType = new MBottomType(model) is lazy
1835 redef fun need_anchor do return false
1836 redef fun resolve_for(mtype, anchor, mmodule, cleanup_virtual) do return self
1837 redef fun can_resolve_for(mtype, anchor, mmodule) do return true
1838
1839 redef fun collect_mclassdefs(mmodule) do return new HashSet[MClassDef]
1840
1841 redef fun collect_mclasses(mmodule) do return new HashSet[MClass]
1842
1843 redef fun collect_mtypes(mmodule) do return new HashSet[MClassType]
1844 end
1845
1846 # The special universal most specific type.
1847 #
1848 # This type is intended to be only used internally for type computation or analysis and should not be exposed to the user.
1849 # The bottom type can de used to denote things that are dead (no instance).
1850 #
1851 # Semantically it is the singleton `null.as_notnull`.
1852 # Is also means that `self.as_nullable == null`.
1853 class MBottomType
1854 super MType
1855 redef var model
1856 redef fun to_s do return "bottom"
1857 redef fun full_name do return "bottom"
1858 redef fun c_name do return "bottom"
1859 redef fun as_nullable do return model.null_type
1860 redef fun as_notnull do return self
1861 redef fun need_anchor do return false
1862 redef fun resolve_for(mtype, anchor, mmodule, cleanup_virtual) do return self
1863 redef fun can_resolve_for(mtype, anchor, mmodule) do return true
1864
1865 redef fun collect_mclassdefs(mmodule) do return new HashSet[MClassDef]
1866
1867 redef fun collect_mclasses(mmodule) do return new HashSet[MClass]
1868
1869 redef fun collect_mtypes(mmodule) do return new HashSet[MClassType]
1870 end
1871
1872 # A special type used as a silent error marker when building types.
1873 #
1874 # This type is intended to be only used internally for type operation and should not be exposed to the user.
1875 # The error type can de used to denote things that are conflicting or inconsistent.
1876 #
1877 # Some methods on types can return a `MErrorType` to denote a broken or a conflicting result.
1878 # Use `is_ok` to check if a type is (or contains) a `MErrorType` .
1879 class MErrorType
1880 super MType
1881 redef var model
1882 redef fun to_s do return "error"
1883 redef fun full_name do return "error"
1884 redef fun c_name do return "error"
1885 redef fun need_anchor do return false
1886 redef fun resolve_for(mtype, anchor, mmodule, cleanup_virtual) do return self
1887 redef fun can_resolve_for(mtype, anchor, mmodule) do return true
1888 redef fun is_ok do return false
1889
1890 redef fun collect_mclassdefs(mmodule) do return new HashSet[MClassDef]
1891
1892 redef fun collect_mclasses(mmodule) do return new HashSet[MClass]
1893
1894 redef fun collect_mtypes(mmodule) do return new HashSet[MClassType]
1895 end
1896
1897 # A signature of a method
1898 class MSignature
1899 super MType
1900
1901 # The each parameter (in order)
1902 var mparameters: Array[MParameter]
1903
1904 # Returns a parameter named `name`, if any.
1905 fun mparameter_by_name(name: String): nullable MParameter
1906 do
1907 for p in mparameters do
1908 if p.name == name then return p
1909 end
1910 return null
1911 end
1912
1913 # The return type (null for a procedure)
1914 var return_mtype: nullable MType
1915
1916 redef fun depth
1917 do
1918 var dmax = 0
1919 var t = self.return_mtype
1920 if t != null then dmax = t.depth
1921 for p in mparameters do
1922 var d = p.mtype.depth
1923 if d > dmax then dmax = d
1924 end
1925 return dmax + 1
1926 end
1927
1928 redef fun length
1929 do
1930 var res = 1
1931 var t = self.return_mtype
1932 if t != null then res += t.length
1933 for p in mparameters do
1934 res += p.mtype.length
1935 end
1936 return res
1937 end
1938
1939 # REQUIRE: 1 <= mparameters.count p -> p.is_vararg
1940 init
1941 do
1942 var vararg_rank = -1
1943 for i in [0..mparameters.length[ do
1944 var parameter = mparameters[i]
1945 if parameter.is_vararg then
1946 if vararg_rank >= 0 then
1947 # If there is more than one vararg,
1948 # consider that additional arguments cannot be mapped.
1949 vararg_rank = -1
1950 break
1951 end
1952 vararg_rank = i
1953 end
1954 end
1955 self.vararg_rank = vararg_rank
1956 end
1957
1958 # The rank of the main ellipsis (`...`) for vararg (starting from 0).
1959 # value is -1 if there is no vararg.
1960 # Example: for "(a: Int, b: Bool..., c: Char)" #-> vararg_rank=1
1961 #
1962 # From a model POV, a signature can contain more than one vararg parameter,
1963 # the `vararg_rank` just indicates the one that will receive the additional arguments.
1964 # However, currently, if there is more that one vararg parameter, no one will be the main one,
1965 # and additional arguments will be refused.
1966 var vararg_rank: Int is noinit
1967
1968 # The number of parameters
1969 fun arity: Int do return mparameters.length
1970
1971 redef fun to_s
1972 do
1973 var b = new FlatBuffer
1974 if not mparameters.is_empty then
1975 b.append("(")
1976 for i in [0..mparameters.length[ do
1977 var mparameter = mparameters[i]
1978 if i > 0 then b.append(", ")
1979 b.append(mparameter.name)
1980 b.append(": ")
1981 b.append(mparameter.mtype.to_s)
1982 if mparameter.is_vararg then
1983 b.append("...")
1984 end
1985 end
1986 b.append(")")
1987 end
1988 var ret = self.return_mtype
1989 if ret != null then
1990 b.append(": ")
1991 b.append(ret.to_s)
1992 end
1993 return b.to_s
1994 end
1995
1996 redef fun resolve_for(mtype: MType, anchor: nullable MClassType, mmodule: MModule, cleanup_virtual: Bool): MSignature
1997 do
1998 var params = new Array[MParameter]
1999 for p in self.mparameters do
2000 params.add(p.resolve_for(mtype, anchor, mmodule, cleanup_virtual))
2001 end
2002 var ret = self.return_mtype
2003 if ret != null then
2004 ret = ret.resolve_for(mtype, anchor, mmodule, cleanup_virtual)
2005 end
2006 var res = new MSignature(params, ret)
2007 return res
2008 end
2009 end
2010
2011 # A parameter in a signature
2012 class MParameter
2013 super MEntity
2014
2015 # The name of the parameter
2016 redef var name
2017
2018 # The static type of the parameter
2019 var mtype: MType
2020
2021 # Is the parameter a vararg?
2022 var is_vararg: Bool
2023
2024 redef fun to_s
2025 do
2026 if is_vararg then
2027 return "{name}: {mtype}..."
2028 else
2029 return "{name}: {mtype}"
2030 end
2031 end
2032
2033 # Returns a new parameter with the `mtype` resolved.
2034 # See `MType::resolve_for` for details.
2035 fun resolve_for(mtype: MType, anchor: nullable MClassType, mmodule: MModule, cleanup_virtual: Bool): MParameter
2036 do
2037 if not self.mtype.need_anchor then return self
2038 var newtype = self.mtype.resolve_for(mtype, anchor, mmodule, cleanup_virtual)
2039 var res = new MParameter(self.name, newtype, self.is_vararg)
2040 return res
2041 end
2042
2043 redef fun model do return mtype.model
2044 end
2045
2046 # A service (global property) that generalize method, attribute, etc.
2047 #
2048 # `MProperty` are global to the model; it means that a `MProperty` is not bound
2049 # to a specific `MModule` nor a specific `MClass`.
2050 #
2051 # A MProperty gather definitions (see `mpropdefs`) ; one for the introduction
2052 # and the other in subclasses and in refinements.
2053 #
2054 # A `MProperty` is used to denotes services in polymorphic way (ie. independent
2055 # of any dynamic type).
2056 # For instance, a call site "x.foo" is associated to a `MProperty`.
2057 abstract class MProperty
2058 super MEntity
2059
2060 # The associated MPropDef subclass.
2061 # The two specialization hierarchy are symmetric.
2062 type MPROPDEF: MPropDef
2063
2064 # The classdef that introduce the property
2065 # While a property is not bound to a specific module, or class,
2066 # the introducing mclassdef is used for naming and visibility
2067 var intro_mclassdef: MClassDef
2068
2069 # The (short) name of the property
2070 redef var name
2071
2072 redef var location
2073
2074 redef fun mdoc_or_fallback
2075 do
2076 # Don’t use `intro.mdoc_or_fallback` because it would create an infinite
2077 # recursion.
2078 return intro.mdoc
2079 end
2080
2081 # The canonical name of the property.
2082 #
2083 # It is currently the short-`name` prefixed by the short-name of the class and the full-name of the module.
2084 # Example: "my_package::my_module::MyClass::my_method"
2085 #
2086 # The full-name of the module is needed because two distinct modules of the same package can
2087 # still refine the same class and introduce homonym properties.
2088 #
2089 # For public properties not introduced by refinement, the module name is not used.
2090 #
2091 # Example: `my_package::MyClass::My_method`
2092 redef var full_name is lazy do
2093 if intro_mclassdef.is_intro then
2094 return "{intro_mclassdef.mmodule.namespace_for(visibility)}::{intro_mclassdef.mclass.name}::{name}"
2095 else
2096 return "{intro_mclassdef.mmodule.full_name}::{intro_mclassdef.mclass.name}::{name}"
2097 end
2098 end
2099
2100 redef var c_name is lazy do
2101 # FIXME use `namespace_for`
2102 return "{intro_mclassdef.mmodule.c_name}__{intro_mclassdef.mclass.name.to_cmangle}__{name.to_cmangle}"
2103 end
2104
2105 # The visibility of the property
2106 redef var visibility
2107
2108 # Is the property usable as an initializer?
2109 var is_autoinit = false is writable
2110
2111 init
2112 do
2113 intro_mclassdef.intro_mproperties.add(self)
2114 var model = intro_mclassdef.mmodule.model
2115 model.mproperties_by_name.add_one(name, self)
2116 model.mproperties.add(self)
2117 end
2118
2119 # All definitions of the property.
2120 # The first is the introduction,
2121 # The other are redefinitions (in refinements and in subclasses)
2122 var mpropdefs = new Array[MPROPDEF]
2123
2124 # The definition that introduces the property.
2125 #
2126 # Warning: such a definition may not exist in the early life of the object.
2127 # In this case, the method will abort.
2128 var intro: MPROPDEF is noinit
2129
2130 redef fun model do return intro.model
2131
2132 # Alias for `name`
2133 redef fun to_s do return name
2134
2135 # Return the most specific property definitions defined or inherited by a type.
2136 # The selection knows that refinement is stronger than specialization;
2137 # however, in case of conflict more than one property are returned.
2138 # If mtype does not know mproperty then an empty array is returned.
2139 #
2140 # If you want the really most specific property, then look at `lookup_first_definition`
2141 #
2142 # REQUIRE: `not mtype.need_anchor` to simplify the API (no `anchor` parameter)
2143 # ENSURE: `not mtype.has_mproperty(mmodule, self) == result.is_empty`
2144 fun lookup_definitions(mmodule: MModule, mtype: MType): Array[MPROPDEF]
2145 do
2146 assert not mtype.need_anchor
2147 mtype = mtype.undecorate
2148
2149 var cache = self.lookup_definitions_cache[mmodule, mtype]
2150 if cache != null then return cache
2151
2152 #print "select prop {mproperty} for {mtype} in {self}"
2153 # First, select all candidates
2154 var candidates = new Array[MPROPDEF]
2155
2156 # Here we have two strategies: iterate propdefs or iterate classdefs.
2157 var mpropdefs = self.mpropdefs
2158 if mpropdefs.length <= 1 or mpropdefs.length < mtype.collect_mclassdefs(mmodule).length then
2159 # Iterate on all definitions of `self`, keep only those inherited by `mtype` in `mmodule`
2160 for mpropdef in mpropdefs do
2161 # If the definition is not imported by the module, then skip
2162 if not mmodule.in_importation <= mpropdef.mclassdef.mmodule then continue
2163 # If the definition is not inherited by the type, then skip
2164 if not mtype.is_subtype(mmodule, null, mpropdef.mclassdef.bound_mtype) then continue
2165 # Else, we keep it
2166 candidates.add(mpropdef)
2167 end
2168 else
2169 # Iterate on all super-classdefs of `mtype`, keep only the definitions of `self`, if any.
2170 for mclassdef in mtype.collect_mclassdefs(mmodule) do
2171 var p = mclassdef.mpropdefs_by_property.get_or_null(self)
2172 if p != null then candidates.add p
2173 end
2174 end
2175
2176 # Fast track for only one candidate
2177 if candidates.length <= 1 then
2178 self.lookup_definitions_cache[mmodule, mtype] = candidates
2179 return candidates
2180 end
2181
2182 # Second, filter the most specific ones
2183 return select_most_specific(mmodule, candidates)
2184 end
2185
2186 private var lookup_definitions_cache = new HashMap2[MModule, MType, Array[MPROPDEF]]
2187
2188 # Return the most specific property definitions inherited by a type.
2189 # The selection knows that refinement is stronger than specialization;
2190 # however, in case of conflict more than one property are returned.
2191 # If mtype does not know mproperty then an empty array is returned.
2192 #
2193 # If you want the really most specific property, then look at `lookup_next_definition`
2194 #
2195 # REQUIRE: `not mtype.need_anchor` to simplify the API (no `anchor` parameter)
2196 # ENSURE: `not mtype.has_mproperty(mmodule, self) implies result.is_empty`
2197 fun lookup_super_definitions(mmodule: MModule, mtype: MType): Array[MPROPDEF]
2198 do
2199 assert not mtype.need_anchor
2200 mtype = mtype.undecorate
2201
2202 # First, select all candidates
2203 var candidates = new Array[MPROPDEF]
2204 for mpropdef in self.mpropdefs do
2205 # If the definition is not imported by the module, then skip
2206 if not mmodule.in_importation <= mpropdef.mclassdef.mmodule then continue
2207 # If the definition is not inherited by the type, then skip
2208 if not mtype.is_subtype(mmodule, null, mpropdef.mclassdef.bound_mtype) then continue
2209 # If the definition is defined by the type, then skip (we want the super, so e skip the current)
2210 if mtype == mpropdef.mclassdef.bound_mtype and mmodule == mpropdef.mclassdef.mmodule then continue
2211 # Else, we keep it
2212 candidates.add(mpropdef)
2213 end
2214 # Fast track for only one candidate
2215 if candidates.length <= 1 then return candidates
2216
2217 # Second, filter the most specific ones
2218 return select_most_specific(mmodule, candidates)
2219 end
2220
2221 # Return an array containing olny the most specific property definitions
2222 # This is an helper function for `lookup_definitions` and `lookup_super_definitions`
2223 private fun select_most_specific(mmodule: MModule, candidates: Array[MPROPDEF]): Array[MPROPDEF]
2224 do
2225 var res = new Array[MPROPDEF]
2226 for pd1 in candidates do
2227 var cd1 = pd1.mclassdef
2228 var c1 = cd1.mclass
2229 var keep = true
2230 for pd2 in candidates do
2231 if pd2 == pd1 then continue # do not compare with self!
2232 var cd2 = pd2.mclassdef
2233 var c2 = cd2.mclass
2234 if c2.mclass_type == c1.mclass_type then
2235 if cd2.mmodule.in_importation < cd1.mmodule then
2236 # cd2 refines cd1; therefore we skip pd1
2237 keep = false
2238 break
2239 end
2240 else if cd2.bound_mtype.is_subtype(mmodule, null, cd1.bound_mtype) and cd2.bound_mtype != cd1.bound_mtype then
2241 # cd2 < cd1; therefore we skip pd1
2242 keep = false
2243 break
2244 end
2245 end
2246 if keep then
2247 res.add(pd1)
2248 end
2249 end
2250 if res.is_empty then
2251 print_error "All lost! {candidates.join(", ")}"
2252 # FIXME: should be abort!
2253 end
2254 return res
2255 end
2256
2257 # Return the most specific definition in the linearization of `mtype`.
2258 #
2259 # If you want to know the next properties in the linearization,
2260 # look at `MPropDef::lookup_next_definition`.
2261 #
2262 # FIXME: the linearization is still unspecified
2263 #
2264 # REQUIRE: `not mtype.need_anchor` to simplify the API (no `anchor` parameter)
2265 # REQUIRE: `mtype.has_mproperty(mmodule, self)`
2266 fun lookup_first_definition(mmodule: MModule, mtype: MType): MPROPDEF
2267 do
2268 return lookup_all_definitions(mmodule, mtype).first
2269 end
2270
2271 # Return all definitions in a linearization order
2272 # Most specific first, most general last
2273 #
2274 # REQUIRE: `not mtype.need_anchor` to simplify the API (no `anchor` parameter)
2275 # REQUIRE: `mtype.has_mproperty(mmodule, self)`
2276 fun lookup_all_definitions(mmodule: MModule, mtype: MType): Array[MPROPDEF]
2277 do
2278 mtype = mtype.undecorate
2279
2280 var cache = self.lookup_all_definitions_cache[mmodule, mtype]
2281 if cache != null then return cache
2282
2283 assert not mtype.need_anchor
2284 assert mtype.has_mproperty(mmodule, self)
2285
2286 #print "select prop {mproperty} for {mtype} in {self}"
2287 # First, select all candidates
2288 var candidates = new Array[MPROPDEF]
2289 for mpropdef in self.mpropdefs do
2290 # If the definition is not imported by the module, then skip
2291 if not mmodule.in_importation <= mpropdef.mclassdef.mmodule then continue
2292 # If the definition is not inherited by the type, then skip
2293 if not mtype.is_subtype(mmodule, null, mpropdef.mclassdef.bound_mtype) then continue
2294 # Else, we keep it
2295 candidates.add(mpropdef)
2296 end
2297 # Fast track for only one candidate
2298 if candidates.length <= 1 then
2299 self.lookup_all_definitions_cache[mmodule, mtype] = candidates
2300 return candidates
2301 end
2302
2303 mmodule.linearize_mpropdefs(candidates)
2304 candidates = candidates.reversed
2305 self.lookup_all_definitions_cache[mmodule, mtype] = candidates
2306 return candidates
2307 end
2308
2309 private var lookup_all_definitions_cache = new HashMap2[MModule, MType, Array[MPROPDEF]]
2310 end
2311
2312 # A global method
2313 class MMethod
2314 super MProperty
2315
2316 redef type MPROPDEF: MMethodDef
2317
2318 # Is the property defined at the top_level of the module?
2319 # Currently such a property are stored in `Object`
2320 var is_toplevel: Bool = false is writable
2321
2322 # Is the property a constructor?
2323 # Warning, this property can be inherited by subclasses with or without being a constructor
2324 # therefore, you should use `is_init_for` the verify if the property is a legal constructor for a given class
2325 var is_init: Bool = false is writable
2326
2327 # The constructor is a (the) root init with empty signature but a set of initializers
2328 var is_root_init: Bool = false is writable
2329
2330 # Is the property a 'new' constructor?
2331 var is_new: Bool = false is writable
2332
2333 # Is the property a legal constructor for a given class?
2334 # As usual, visibility is not considered.
2335 # FIXME not implemented
2336 fun is_init_for(mclass: MClass): Bool
2337 do
2338 return self.is_init
2339 end
2340
2341 # A specific method that is safe to call on null.
2342 # Currently, only `==`, `!=` and `is_same_instance` are safe
2343 fun is_null_safe: Bool do return name == "==" or name == "!=" or name == "is_same_instance"
2344 end
2345
2346 # A global attribute
2347 class MAttribute
2348 super MProperty
2349
2350 redef type MPROPDEF: MAttributeDef
2351
2352 end
2353
2354 # A global virtual type
2355 class MVirtualTypeProp
2356 super MProperty
2357
2358 redef type MPROPDEF: MVirtualTypeDef
2359
2360 # The formal type associated to the virtual type property
2361 var mvirtualtype = new MVirtualType(self)
2362
2363 # Is `self` the special virtual type `SELF`?
2364 var is_selftype: Bool is lazy do return name == "SELF"
2365 end
2366
2367 # A definition of a property (local property)
2368 #
2369 # Unlike `MProperty`, a `MPropDef` is a local definition that belong to a
2370 # specific class definition (which belong to a specific module)
2371 abstract class MPropDef
2372 super MEntity
2373
2374 # The associated `MProperty` subclass.
2375 # the two specialization hierarchy are symmetric
2376 type MPROPERTY: MProperty
2377
2378 # Self class
2379 type MPROPDEF: MPropDef
2380
2381 # The class definition where the property definition is
2382 var mclassdef: MClassDef
2383
2384 # The associated global property
2385 var mproperty: MPROPERTY
2386
2387 redef var location: Location
2388
2389 redef fun visibility do return mproperty.visibility
2390
2391 init
2392 do
2393 mclassdef.mpropdefs.add(self)
2394 mproperty.mpropdefs.add(self)
2395 mclassdef.mpropdefs_by_property[mproperty] = self
2396 if mproperty.intro_mclassdef == mclassdef then
2397 assert not isset mproperty._intro
2398 mproperty.intro = self
2399 end
2400 self.to_s = "{mclassdef}${mproperty}"
2401 end
2402
2403 # Actually the name of the `mproperty`
2404 redef fun name do return mproperty.name
2405
2406 # The full-name of mpropdefs combine the information about the `classdef` and the `mproperty`.
2407 #
2408 # Therefore the combination of identifiers is awful,
2409 # the worst case being
2410 #
2411 # * a property "p::m::A::x"
2412 # * redefined in a refinement of a class "q::n::B"
2413 # * in a module "r::o"
2414 # * so "r::o$q::n::B$p::m::A::x"
2415 #
2416 # Fortunately, the full-name is simplified when entities are repeated.
2417 # For the previous case, the simplest form is "p$A$x".
2418 redef var full_name is lazy do
2419 var res = new FlatBuffer
2420
2421 # The first part is the mclassdef. Worst case is "r::o$q::n::B"
2422 res.append mclassdef.full_name
2423
2424 res.append "$"
2425
2426 if mclassdef.mclass == mproperty.intro_mclassdef.mclass then
2427 # intro are unambiguous in a class
2428 res.append name
2429 else
2430 # Just try to simplify each part
2431 if mclassdef.mmodule.mpackage != mproperty.intro_mclassdef.mmodule.mpackage then
2432 # precise "p::m" only if "p" != "r"
2433 res.append mproperty.intro_mclassdef.mmodule.namespace_for(mproperty.visibility)
2434 res.append "::"
2435 else if mproperty.visibility <= private_visibility then
2436 # Same package ("p"=="q"), but private visibility,
2437 # does the module part ("::m") need to be displayed
2438 if mclassdef.mmodule.namespace_for(mclassdef.mclass.visibility) != mproperty.intro_mclassdef.mmodule.mpackage then
2439 res.append "::"
2440 res.append mproperty.intro_mclassdef.mmodule.name
2441 res.append "::"
2442 end
2443 end
2444 if mclassdef.mclass != mproperty.intro_mclassdef.mclass then
2445 # precise "B" only if not the same class than "A"
2446 res.append mproperty.intro_mclassdef.name
2447 res.append "::"
2448 end
2449 # Always use the property name "x"
2450 res.append mproperty.name
2451 end
2452 return res.to_s
2453 end
2454
2455 redef var c_name is lazy do
2456 var res = new FlatBuffer
2457 res.append mclassdef.c_name
2458 res.append "___"
2459 if mclassdef.mclass == mproperty.intro_mclassdef.mclass then
2460 res.append name.to_cmangle
2461 else
2462 if mclassdef.mmodule != mproperty.intro_mclassdef.mmodule then
2463 res.append mproperty.intro_mclassdef.mmodule.c_name
2464 res.append "__"
2465 end
2466 if mclassdef.mclass != mproperty.intro_mclassdef.mclass then
2467 res.append mproperty.intro_mclassdef.name.to_cmangle
2468 res.append "__"
2469 end
2470 res.append mproperty.name.to_cmangle
2471 end
2472 return res.to_s
2473 end
2474
2475 redef fun model do return mclassdef.model
2476
2477 # Internal name combining the module, the class and the property
2478 # Example: "mymodule$MyClass$mymethod"
2479 redef var to_s is noinit
2480
2481 # Is self the definition that introduce the property?
2482 fun is_intro: Bool do return isset mproperty._intro and mproperty.intro == self
2483
2484 # Return the next definition in linearization of `mtype`.
2485 #
2486 # This method is used to determine what method is called by a super.
2487 #
2488 # REQUIRE: `not mtype.need_anchor`
2489 fun lookup_next_definition(mmodule: MModule, mtype: MType): MPROPDEF
2490 do
2491 assert not mtype.need_anchor
2492
2493 var mpropdefs = self.mproperty.lookup_all_definitions(mmodule, mtype)
2494 var i = mpropdefs.iterator
2495 while i.is_ok and i.item != self do i.next
2496 assert has_property: i.is_ok
2497 i.next
2498 assert has_next_property: i.is_ok
2499 return i.item
2500 end
2501
2502 redef fun mdoc_or_fallback do return mdoc or else mproperty.mdoc_or_fallback
2503 end
2504
2505 # A local definition of a method
2506 class MMethodDef
2507 super MPropDef
2508
2509 redef type MPROPERTY: MMethod
2510 redef type MPROPDEF: MMethodDef
2511
2512 # The signature attached to the property definition
2513 var msignature: nullable MSignature = null is writable
2514
2515 # The signature attached to the `new` call on a root-init
2516 # This is a concatenation of the signatures of the initializers
2517 #
2518 # REQUIRE `mproperty.is_root_init == (new_msignature != null)`
2519 var new_msignature: nullable MSignature = null is writable
2520
2521 # List of initialisers to call in root-inits
2522 #
2523 # They could be setters or attributes
2524 #
2525 # REQUIRE `mproperty.is_root_init == (new_msignature != null)`
2526 var initializers = new Array[MProperty]
2527
2528 # Is the method definition abstract?
2529 var is_abstract: Bool = false is writable
2530
2531 # Is the method definition intern?
2532 var is_intern = false is writable
2533
2534 # Is the method definition extern?
2535 var is_extern = false is writable
2536
2537 # An optional constant value returned in functions.
2538 #
2539 # Only some specific primitife value are accepted by engines.
2540 # Is used when there is no better implementation available.
2541 #
2542 # Currently used only for the implementation of the `--define`
2543 # command-line option.
2544 # SEE: module `mixin`.
2545 var constant_value: nullable Object = null is writable
2546 end
2547
2548 # A local definition of an attribute
2549 class MAttributeDef
2550 super MPropDef
2551
2552 redef type MPROPERTY: MAttribute
2553 redef type MPROPDEF: MAttributeDef
2554
2555 # The static type of the attribute
2556 var static_mtype: nullable MType = null is writable
2557 end
2558
2559 # A local definition of a virtual type
2560 class MVirtualTypeDef
2561 super MPropDef
2562
2563 redef type MPROPERTY: MVirtualTypeProp
2564 redef type MPROPDEF: MVirtualTypeDef
2565
2566 # The bound of the virtual type
2567 var bound: nullable MType = null is writable
2568
2569 # Is the bound fixed?
2570 var is_fixed = false is writable
2571 end
2572
2573 # A kind of class.
2574 #
2575 # * `abstract_kind`
2576 # * `concrete_kind`
2577 # * `interface_kind`
2578 # * `enum_kind`
2579 # * `extern_kind`
2580 #
2581 # Note this class is basically an enum.
2582 # FIXME: use a real enum once user-defined enums are available
2583 class MClassKind
2584 redef var to_s
2585
2586 # Is a constructor required?
2587 var need_init: Bool
2588
2589 # TODO: private init because enumeration.
2590
2591 # Can a class of kind `self` specializes a class of kind `other`?
2592 fun can_specialize(other: MClassKind): Bool
2593 do
2594 if other == interface_kind then return true # everybody can specialize interfaces
2595 if self == interface_kind or self == enum_kind then
2596 # no other case for interfaces
2597 return false
2598 else if self == extern_kind then
2599 # only compatible with themselves
2600 return self == other
2601 else if other == enum_kind or other == extern_kind then
2602 # abstract_kind and concrete_kind are incompatible
2603 return false
2604 end
2605 # remain only abstract_kind and concrete_kind
2606 return true
2607 end
2608 end
2609
2610 # The class kind `abstract`
2611 fun abstract_kind: MClassKind do return once new MClassKind("abstract class", true)
2612 # The class kind `concrete`
2613 fun concrete_kind: MClassKind do return once new MClassKind("class", true)
2614 # The class kind `interface`
2615 fun interface_kind: MClassKind do return once new MClassKind("interface", false)
2616 # The class kind `enum`
2617 fun enum_kind: MClassKind do return once new MClassKind("enum", false)
2618 # The class kind `extern`
2619 fun extern_kind: MClassKind do return once new MClassKind("extern class", false)