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