src: use `as_notnullable` in code
[nit.git] / src / modelize_class.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 # Analysis and verification of class definitions to instantiate model element
18 module modelize_class
19
20 import modelbuilder
21
22 redef class ToolContext
23 var modelize_class_phase: Phase = new ModelizeClassPhase(self, null)
24 end
25
26 private class ModelizeClassPhase
27 super Phase
28
29 redef fun process_nmodule(nmodule)
30 do
31 toolcontext.modelbuilder.build_classes(nmodule)
32 end
33 end
34
35 redef class ModelBuilder
36 # Visit the AST and create the `MClass` objects
37 private fun build_a_mclass(nmodule: AModule, nclassdef: AClassdef)
38 do
39 var mmodule = nmodule.mmodule.as(not null)
40
41 var name: String
42 var nkind: nullable AClasskind
43 var mkind: MClassKind
44 var nvisibility: nullable AVisibility
45 var mvisibility: nullable MVisibility
46 var arity = 0
47 if nclassdef isa AStdClassdef then
48 name = nclassdef.n_id.text
49 nkind = nclassdef.n_classkind
50 mkind = nkind.mkind
51 nvisibility = nclassdef.n_visibility
52 mvisibility = nvisibility.mvisibility
53 arity = nclassdef.n_formaldefs.length
54 if mvisibility == protected_visibility then
55 error(nvisibility, "Error: only properties can be protected.")
56 return
57 else if mvisibility == intrude_visibility then
58 error(nvisibility, "Error: intrude is not a legal visibility for classes.")
59 return
60 end
61 else if nclassdef isa ATopClassdef then
62 name = "Object"
63 nkind = null
64 mkind = interface_kind
65 nvisibility = null
66 mvisibility = public_visibility
67 else if nclassdef isa AMainClassdef then
68 name = "Sys"
69 nkind = null
70 mkind = concrete_kind
71 nvisibility = null
72 mvisibility = public_visibility
73 else
74 abort
75 end
76
77 var mclass = try_get_mclass_by_name(nclassdef, mmodule, name)
78 if mclass == null then
79 if nclassdef isa AStdClassdef and nclassdef.n_kwredef != null then
80 error(nclassdef, "Redef error: No imported class {name} to refine.")
81 return
82 end
83 mclass = new MClass(mmodule, name, arity, mkind, mvisibility)
84 #print "new class {mclass}"
85 else if nclassdef isa AStdClassdef and nmodule.mclass2nclassdef.has_key(mclass) then
86 error(nclassdef, "Error: A class {name} is already defined at line {nmodule.mclass2nclassdef[mclass].location.line_start}.")
87 return
88 else if nclassdef isa AStdClassdef and nclassdef.n_kwredef == null then
89 error(nclassdef, "Redef error: {name} is an imported class. Add the redef keyword to refine it.")
90 return
91 else if mclass.arity != arity then
92 error(nclassdef, "Redef error: Formal parameter arity missmatch; got {arity}, expected {mclass.arity}.")
93 return
94 else if nkind != null and mkind != concrete_kind and mclass.kind != mkind then
95 error(nkind, "Error: refinement changed the kind from a {mclass.kind} to a {mkind}")
96 else if nvisibility != null and mvisibility != public_visibility and mclass.visibility != mvisibility then
97 error(nvisibility, "Error: refinement changed the visibility from a {mclass.visibility} to a {mvisibility}")
98 end
99 nclassdef.mclass = mclass
100 if not nmodule.mclass2nclassdef.has_key(mclass) then
101 nmodule.mclass2nclassdef[mclass] = nclassdef
102 nclassdef.all_defs = [nclassdef]
103 else
104 nmodule.mclass2nclassdef[mclass].all_defs.add(nclassdef)
105 end
106 end
107
108 # Visit the AST and create the `MClassDef` objects
109 private fun build_a_mclassdef(nmodule: AModule, nclassdef: AClassdef)
110 do
111 var mmodule = nmodule.mmodule.as(not null)
112 var objectclass = try_get_mclass_by_name(nmodule, mmodule, "Object")
113 var mclass = nclassdef.mclass
114 if mclass == null then return # Skip error
115
116 # In case of non-standard AClassdef, try to attach to an already existing mclassdef
117 var other_nclassdef = nmodule.mclass2nclassdef[mclass]
118 if other_nclassdef != nclassdef then
119 assert not nclassdef isa AStdClassdef
120 nclassdef.mclassdef = other_nclassdef.mclassdef
121 return
122 end
123
124 var names = new Array[String]
125 var bounds = new Array[MType]
126 if nclassdef isa AStdClassdef and mclass.arity > 0 then
127 # Collect formal parameter names
128 for i in [0..mclass.arity[ do
129 var nfd = nclassdef.n_formaldefs[i]
130 var ptname = nfd.n_id.text
131 if names.has(ptname) then
132 error(nfd, "Error: A formal parameter type `{ptname}' already exists")
133 return
134 end
135 for c in ptname.chars do if c >= 'a' and c<= 'z' then
136 warning(nfd, "Warning: lowercase in the formal parameter type {ptname}")
137 break
138 end
139 names.add(ptname)
140 nfd.mtype = mclass.mclass_type.arguments[i].as(MParameterType)
141 end
142
143 # Revolve bound for formal parameter names
144 for i in [0..mclass.arity[ do
145 var nfd = nclassdef.n_formaldefs[i]
146 var nfdt = nfd.n_type
147 if nfdt != null then
148 var bound = resolve_mtype_unchecked(mmodule, null, nfdt, false)
149 if bound == null then return # Forward error
150 if bound.need_anchor then
151 # No F-bounds!
152 error(nfd, "Error: Formal parameter type `{names[i]}' bounded with a formal parameter type")
153 else
154 bounds.add(bound)
155 nfd.bound = bound
156 end
157 else if mclass.mclassdefs.is_empty then
158 # No bound, then implicitely bound by nullable Object
159 var bound = objectclass.mclass_type.as_nullable
160 bounds.add(bound)
161 nfd.bound = bound
162 else
163 # Inherit the bound
164 var bound = mclass.intro.bound_mtype.arguments[i]
165 bounds.add(bound)
166 nfd.bound = bound
167 end
168 end
169 end
170
171 var bound_mtype = mclass.get_mtype(bounds)
172 var mclassdef = new MClassDef(mmodule, bound_mtype, nclassdef.location, names)
173 nclassdef.mclassdef = mclassdef
174 self.mclassdef2nclassdef[mclassdef] = nclassdef
175
176 if nclassdef isa AStdClassdef then
177 var ndoc = nclassdef.n_doc
178 if ndoc != null then
179 var mdoc = ndoc.to_mdoc
180 mclassdef.mdoc = mdoc
181 mdoc.original_mentity = mclassdef
182 end
183 end
184
185 if mclassdef.is_intro then
186 self.toolcontext.info("{mclassdef} introduces new {mclass.kind} {mclass.full_name}", 3)
187 else
188 self.toolcontext.info("{mclassdef} refine {mclass.kind} {mclass.full_name}", 3)
189 end
190 end
191
192 # Visit the AST and set the super-types of the `MClassDef` objects
193 private fun collect_a_mclassdef_inheritance(nmodule: AModule, nclassdef: AClassdef)
194 do
195 var mmodule = nmodule.mmodule.as(not null)
196 var objectclass = try_get_mclass_by_name(nmodule, mmodule, "Object")
197 var pointerclass = try_get_mclass_by_name(nmodule, mmodule, "Pointer")
198 var mclass = nclassdef.mclass.as(not null)
199 var mclassdef = nclassdef.mclassdef.as(not null)
200
201 # Do we need to specify Object as a super class?
202 var specobject = true
203
204 # Do we need to specify Pointer as a super class? (is only valid
205 # if `nclassdef` is an extern class)
206 var specpointer = true
207
208 var supertypes = new Array[MClassType]
209 if nclassdef isa AStdClassdef then
210 for nsc in nclassdef.n_superclasses do
211 specobject = false
212 var ntype = nsc.n_type
213 var mtype = resolve_mtype_unchecked(mmodule, mclassdef, ntype, false)
214 if mtype == null then continue # Skip because of error
215 if not mtype isa MClassType then
216 error(ntype, "Error: supertypes cannot be a formal type")
217 return
218 end
219 if not mclass.kind.can_specialize(mtype.mclass.kind) then
220 error(ntype, "Error: {mclass.kind} {mclass} cannot specialize {mtype.mclass.kind} {mtype.mclass}")
221 end
222 supertypes.add mtype
223 #print "new super : {mclass} < {mtype}"
224 if mtype.mclass.kind == extern_kind then specpointer = false
225 end
226 end
227
228 if mclassdef.is_intro and objectclass != null then
229 if mclass.kind == extern_kind and mclass.name != "Pointer" then
230 # it is an extern class, but not a Pointer
231 if specpointer then supertypes.add pointerclass.mclass_type
232 else if specobject and mclass.name != "Object" then
233 # it is a standard class without super class (but is not Object)
234 supertypes.add objectclass.mclass_type
235 end
236 end
237
238 mclassdef.set_supertypes(supertypes)
239 if not supertypes.is_empty then self.toolcontext.info("{mclassdef} new super-types: {supertypes.join(", ")}", 3)
240 end
241
242 # Check the validity of the specialization heirarchy
243 private fun check_supertypes(nmodule: AModule, nclassdef: AClassdef)
244 do
245 var mmodule = nmodule.mmodule.as(not null)
246 var objectclass = try_get_mclass_by_name(nmodule, mmodule, "Object")
247 var mclass = nclassdef.mclass.as(not null)
248 var mclassdef = nclassdef.mclassdef.as(not null)
249
250 for s in mclassdef.supertypes do
251 if s.is_subtype(mmodule, mclassdef.bound_mtype, mclassdef.bound_mtype) then
252 error(nclassdef, "Error: Inheritance loop for class {mclass} with type {s}")
253 end
254 end
255 end
256
257 # Build the classes of the module `nmodule`.
258 # REQUIRE: classes of imported modules are already build. (let `phase` do the job)
259 private fun build_classes(nmodule: AModule)
260 do
261 var errcount = toolcontext.error_count
262 # Force building recursively
263 if nmodule.build_classes_is_done then return
264 nmodule.build_classes_is_done = true
265 var mmodule = nmodule.mmodule.as(not null)
266 for imp in mmodule.in_importation.direct_greaters do
267
268 if not mmodule2nmodule.has_key(imp) then continue
269 build_classes(mmodule2nmodule[imp])
270 end
271
272 if errcount != toolcontext.error_count then return
273
274 # Create all classes
275 for nclassdef in nmodule.n_classdefs do
276 self.build_a_mclass(nmodule, nclassdef)
277 end
278
279 if errcount != toolcontext.error_count then return
280
281 # Create all classdefs
282 for nclassdef in nmodule.n_classdefs do
283 self.build_a_mclassdef(nmodule, nclassdef)
284 end
285
286 if errcount != toolcontext.error_count then return
287
288 # Create inheritance on all classdefs
289 for nclassdef in nmodule.n_classdefs do
290 self.collect_a_mclassdef_inheritance(nmodule, nclassdef)
291 end
292
293 if errcount != toolcontext.error_count then return
294
295 # Create the mclassdef hierarchy
296 for mclassdef in mmodule.mclassdefs do
297 mclassdef.add_in_hierarchy
298 end
299
300 if errcount != toolcontext.error_count then return
301
302 # Check inheritance
303 for nclassdef in nmodule.n_classdefs do
304 self.check_supertypes(nmodule, nclassdef)
305 end
306
307 if errcount != toolcontext.error_count then return
308
309 # Check unchecked ntypes
310 for nclassdef in nmodule.n_classdefs do
311 if nclassdef isa AStdClassdef then
312 var mclassdef = nclassdef.mclassdef
313 # check bound of formal parameter
314 for nfd in nclassdef.n_formaldefs do
315 var nfdt = nfd.n_type
316 if nfdt != null and nfdt.mtype != null then
317 var bound = resolve_mtype(mmodule, mclassdef, nfdt)
318 if bound == null then return # Forward error
319 end
320 end
321 # check declared super types
322 for nsc in nclassdef.n_superclasses do
323 var ntype = nsc.n_type
324 if ntype.mtype != null then
325 var mtype = resolve_mtype(mmodule, mclassdef, ntype)
326 if mtype == null then return # Forward error
327 end
328 end
329 end
330 end
331
332 if errcount != toolcontext.error_count then return
333
334 # Check clash of ancestors
335 for nclassdef in nmodule.n_classdefs do
336 var mclassdef = nclassdef.mclassdef.as(not null)
337 var superclasses = new HashMap[MClass, MClassType]
338 for scd in mclassdef.in_hierarchy.greaters do
339 for st in scd.supertypes do
340 if not superclasses.has_key(st.mclass) then
341 superclasses[st.mclass] = st
342 else if superclasses[st.mclass] != st then
343 var st1 = superclasses[st.mclass].resolve_for(mclassdef.mclass.mclass_type, mclassdef.bound_mtype, mmodule, false)
344 var st2 = st.resolve_for(mclassdef.mclass.mclass_type, mclassdef.bound_mtype, mmodule, false)
345 if st1 != st2 then
346 error(nclassdef, "Error: Incompatibles ancestors for {mclassdef.mclass}: {st1}, {st2}")
347 end
348 end
349 end
350 end
351 end
352
353 if errcount != toolcontext.error_count then return
354
355 # TODO: Check that the super-class is not intrusive
356
357 # Check that the superclasses are not already known (by transitivity)
358 for nclassdef in nmodule.n_classdefs do
359 if not nclassdef isa AStdClassdef then continue
360 var mclassdef = nclassdef.mclassdef.as(not null)
361
362 # Get the direct superclasses
363 # Since we are a mclassdef, just look at the mclassdef hierarchy
364 var parents = new Array[MClass]
365 for sup in mclassdef.in_hierarchy.direct_greaters do
366 parents.add(sup.mclass)
367 end
368
369 # Used to track duplicates of superclasses
370 var seen_parents = new ArrayMap[MClass, AType]
371
372 # The Object class
373 var objectclass = try_get_mclass_by_name(nmodule, mmodule, "Object")
374
375 # Check each declared superclass to see if it belong to the direct superclass
376 for nsc in nclassdef.n_superclasses do
377 var ntype = nsc.n_type
378 var mtype = ntype.mtype
379 if mtype == null then continue
380 assert mtype isa MClassType
381 var sc = mtype.mclass
382 if not parents.has(sc) or sc == objectclass then
383 # Skip the warning on generated code
384 if ntype.location.file != null and not ntype.location.file.filename.is_empty then
385 warning(ntype, "Warning: superfluous super-class {mtype} in class {mclassdef.mclass}.")
386 end
387 else if not seen_parents.has_key(sc) then
388 seen_parents[sc] = ntype
389 else
390 warning(ntype, "Warning: duplicated super-class {mtype} in class {mclassdef.mclass}.")
391 end
392 end
393 end
394 end
395
396 # Register the nclassdef associated to each mclassdef
397 # FIXME: why not refine the `MClassDef` class with a nullable attribute?
398 var mclassdef2nclassdef: HashMap[MClassDef, AClassdef] = new HashMap[MClassDef, AClassdef]
399
400 # Return the static type associated to the node `ntype`.
401 # `mmodule` and `mclassdef` is the context where the call is made (used to understand formal types)
402 # In case of problem, an error is displayed on `ntype` and null is returned.
403 # FIXME: the name "resolve_mtype" is awful
404 fun resolve_mtype_unchecked(mmodule: MModule, mclassdef: nullable MClassDef, ntype: AType, with_virtual: Bool): nullable MType
405 do
406 var name = ntype.n_id.text
407 var res: MType
408
409 # Check virtual type
410 if mclassdef != null and with_virtual then
411 var prop = try_get_mproperty_by_name(ntype, mclassdef, name).as(nullable MVirtualTypeProp)
412 if prop != null then
413 if not ntype.n_types.is_empty then
414 error(ntype, "Type error: formal type {name} cannot have formal parameters.")
415 end
416 res = prop.mvirtualtype
417 if ntype.n_kwnullable != null then res = res.as_nullable
418 ntype.mtype = res
419 return res
420 end
421 end
422
423 # Check parameter type
424 if mclassdef != null and mclassdef.parameter_names.has(name) then
425 if not ntype.n_types.is_empty then
426 error(ntype, "Type error: formal type {name} cannot have formal parameters.")
427 end
428 for i in [0..mclassdef.parameter_names.length[ do
429 if mclassdef.parameter_names[i] == name then
430 res = mclassdef.mclass.mclass_type.arguments[i]
431 if ntype.n_kwnullable != null then res = res.as_nullable
432 ntype.mtype = res
433 return res
434 end
435 end
436 abort
437 end
438
439 # Check class
440 var mclass = try_get_mclass_by_name(ntype, mmodule, name)
441 if mclass != null then
442 var arity = ntype.n_types.length
443 if arity != mclass.arity then
444 if arity == 0 then
445 error(ntype, "Type error: '{name}' is a generic class.")
446 else if mclass.arity == 0 then
447 error(ntype, "Type error: '{name}' is not a generic class.")
448 else
449 error(ntype, "Type error: '{name}' has {mclass.arity} parameters ({arity} are provided).")
450 end
451 return null
452 end
453 if arity == 0 then
454 res = mclass.mclass_type
455 if ntype.n_kwnullable != null then res = res.as_nullable
456 ntype.mtype = res
457 return res
458 else
459 var mtypes = new Array[MType]
460 for nt in ntype.n_types do
461 var mt = resolve_mtype_unchecked(mmodule, mclassdef, nt, with_virtual)
462 if mt == null then return null # Forward error
463 mtypes.add(mt)
464 end
465 res = mclass.get_mtype(mtypes)
466 if ntype.n_kwnullable != null then res = res.as_nullable
467 ntype.mtype = res
468 return res
469 end
470 end
471
472 # If everything fail, then give up :(
473 error(ntype, "Type error: class {name} not found in module {mmodule}.")
474 return null
475 end
476
477 # Return the static type associated to the node `ntype`.
478 # `mmodule` and `mclassdef` is the context where the call is made (used to understand formal types)
479 # In case of problem, an error is displayed on `ntype` and null is returned.
480 # FIXME: the name "resolve_mtype" is awful
481 fun resolve_mtype(mmodule: MModule, mclassdef: nullable MClassDef, ntype: AType): nullable MType
482 do
483 var mtype = ntype.mtype
484 if mtype == null then mtype = resolve_mtype_unchecked(mmodule, mclassdef, ntype, true)
485 if mtype == null then return null # Forward error
486
487 if ntype.checked_mtype then return mtype
488 if mtype isa MGenericType then
489 var mclass = mtype.mclass
490 for i in [0..mclass.arity[ do
491 var bound = mclass.intro.bound_mtype.arguments[i]
492 var nt = ntype.n_types[i]
493 var mt = resolve_mtype(mmodule, mclassdef, nt)
494 if mt == null then return null # forward error
495 var anchor
496 if mclassdef != null then anchor = mclassdef.bound_mtype else anchor = null
497 if not mt.is_subtype(mmodule, anchor, bound) then
498 error(nt, "Type error: expected {bound}, got {mt}")
499 return null
500 end
501 end
502 end
503 ntype.checked_mtype = true
504 return mtype
505 end
506
507 end
508
509 redef class AModule
510 # Flag that indicate if the class building is already completed
511 var build_classes_is_done: Bool = false
512 # What is the AClassdef associated to a `MClass`?
513 # Used to check multiple definition of a class.
514 var mclass2nclassdef: Map[MClass, AClassdef] = new HashMap[MClass, AClassdef]
515 end
516
517 redef class AClassdef
518 # The associated MClass once build by a `ModelBuilder`
519 var mclass: nullable MClass
520 # The associated MClassDef once build by a `ModelBuilder`
521 var mclassdef: nullable MClassDef
522 # All (self and other) definitions for the same mclassdef
523 var all_defs: nullable Array[AClassdef]
524 end
525
526 redef class AClasskind
527 # The class kind associated with the AST node class
528 private fun mkind: MClassKind is abstract
529 end
530 redef class AConcreteClasskind
531 redef fun mkind do return concrete_kind
532 end
533 redef class AAbstractClasskind
534 redef fun mkind do return abstract_kind
535 end
536 redef class AInterfaceClasskind
537 redef fun mkind do return interface_kind
538 end
539 redef class AEnumClasskind
540 redef fun mkind do return enum_kind
541 end
542 redef class AExternClasskind
543 redef fun mkind do return extern_kind
544 end
545
546 redef class AFormaldef
547 # The associated parameter type
548 var mtype: nullable MParameterType = null
549
550 # The associated bound
551 var bound: nullable MType = null
552 end
553
554 redef class AType
555 # The mtype associated to the node
556 var mtype: nullable MType = null
557
558 # Is the mtype a valid one?
559 var checked_mtype: Bool = false
560 end