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