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