src: remove some warnings and do some cleaning
[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 # No bound, then implicitely bound by nullable Object
172 var bound = objectclass.mclass_type.as_nullable
173 bounds.add(bound)
174 nfd.bound = bound
175 else
176 # Inherit the bound
177 var bound = mclass.intro.bound_mtype.arguments[i]
178 bounds.add(bound)
179 nfd.bound = bound
180 end
181 end
182 end
183
184 var bound_mtype = mclass.get_mtype(bounds)
185 var mclassdef = new MClassDef(mmodule, bound_mtype, nclassdef.location)
186 nclassdef.mclassdef = mclassdef
187 self.mclassdef2nclassdef[mclassdef] = nclassdef
188
189 if nclassdef isa AStdClassdef then
190 var ndoc = nclassdef.n_doc
191 if ndoc != null then
192 var mdoc = ndoc.to_mdoc
193 mclassdef.mdoc = mdoc
194 mdoc.original_mentity = mclassdef
195 else if mclassdef.is_intro and mclass.visibility >= public_visibility then
196 advice(nclassdef, "missing-doc", "Documentation warning: Undocumented public class `{mclass}`")
197 end
198 end
199
200 if mclassdef.is_intro then
201 self.toolcontext.info("{mclassdef} introduces new {mclass.kind} {mclass.full_name}", 3)
202 else
203 self.toolcontext.info("{mclassdef} refine {mclass.kind} {mclass.full_name}", 3)
204 end
205 end
206
207 # Visit the AST and set the super-types of the `MClassDef` objects
208 private fun collect_a_mclassdef_inheritance(nmodule: AModule, nclassdef: AClassdef)
209 do
210 var mmodule = nmodule.mmodule.as(not null)
211 var objectclass = try_get_mclass_by_name(nmodule, mmodule, "Object")
212 var pointerclass = try_get_mclass_by_name(nmodule, mmodule, "Pointer")
213 var mclass = nclassdef.mclass.as(not null)
214 var mclassdef = nclassdef.mclassdef.as(not null)
215
216 # Do we need to specify Object as a super class?
217 var specobject = true
218
219 # Do we need to specify Pointer as a super class? (is only valid
220 # if `nclassdef` is an extern class)
221 var specpointer = true
222
223 var supertypes = new Array[MClassType]
224 if nclassdef isa AStdClassdef then
225 for nsc in nclassdef.n_superclasses do
226 specobject = false
227 var ntype = nsc.n_type
228 var mtype = resolve_mtype_unchecked(mmodule, mclassdef, ntype, false)
229 if mtype == null then continue # Skip because of error
230 if not mtype isa MClassType then
231 error(ntype, "Error: supertypes cannot be a formal type")
232 return
233 end
234 if not mclass.kind.can_specialize(mtype.mclass.kind) then
235 error(ntype, "Error: {mclass.kind} {mclass} cannot specialize {mtype.mclass.kind} {mtype.mclass}")
236 end
237 supertypes.add mtype
238 #print "new super : {mclass} < {mtype}"
239 if mtype.mclass.kind == extern_kind then specpointer = false
240 end
241 end
242
243 if mclassdef.is_intro and objectclass != null then
244 if mclass.kind == extern_kind and mclass.name != "Pointer" then
245 # it is an extern class, but not a Pointer
246 if specpointer then supertypes.add pointerclass.mclass_type
247 else if specobject and mclass.name != "Object" then
248 # it is a standard class without super class (but is not Object)
249 supertypes.add objectclass.mclass_type
250 end
251 end
252
253 mclassdef.set_supertypes(supertypes)
254 if not supertypes.is_empty then self.toolcontext.info("{mclassdef} new super-types: {supertypes.join(", ")}", 3)
255 end
256
257 # Check the validity of the specialization heirarchy
258 private fun check_supertypes(nmodule: AModule, nclassdef: AClassdef)
259 do
260 var mmodule = nmodule.mmodule.as(not null)
261 var mclass = nclassdef.mclass.as(not null)
262 var mclassdef = nclassdef.mclassdef.as(not null)
263
264 for s in mclassdef.supertypes do
265 if s.is_subtype(mmodule, mclassdef.bound_mtype, mclassdef.bound_mtype) then
266 error(nclassdef, "Error: Inheritance loop for class {mclass} with type {s}")
267 end
268 end
269 end
270
271 # Build the classes of the module `nmodule`.
272 # REQUIRE: classes of imported modules are already build. (let `phase` do the job)
273 private fun build_classes(nmodule: AModule)
274 do
275 var errcount = toolcontext.error_count
276 # Force building recursively
277 if nmodule.build_classes_is_done then return
278 nmodule.build_classes_is_done = true
279 var mmodule = nmodule.mmodule.as(not null)
280 for imp in mmodule.in_importation.direct_greaters do
281
282 if not mmodule2nmodule.has_key(imp) then continue
283 build_classes(mmodule2nmodule[imp])
284 end
285
286 if errcount != toolcontext.error_count then return
287
288 # Create all classes
289 for nclassdef in nmodule.n_classdefs do
290 self.build_a_mclass(nmodule, nclassdef)
291 end
292
293 if errcount != toolcontext.error_count then return
294
295 # Create all classdefs
296 for nclassdef in nmodule.n_classdefs do
297 self.build_a_mclassdef(nmodule, nclassdef)
298 end
299
300 if errcount != toolcontext.error_count then return
301
302 # Create inheritance on all classdefs
303 for nclassdef in nmodule.n_classdefs do
304 self.collect_a_mclassdef_inheritance(nmodule, nclassdef)
305 end
306
307 if errcount != toolcontext.error_count then return
308
309 # Create the mclassdef hierarchy
310 for mclassdef in mmodule.mclassdefs do
311 mclassdef.add_in_hierarchy
312 end
313
314 if errcount != toolcontext.error_count then return
315
316 # Check inheritance
317 for nclassdef in nmodule.n_classdefs do
318 self.check_supertypes(nmodule, nclassdef)
319 end
320
321 if errcount != toolcontext.error_count then return
322
323 # Check unchecked ntypes
324 for nclassdef in nmodule.n_classdefs do
325 if nclassdef isa AStdClassdef then
326 var mclassdef = nclassdef.mclassdef
327 # check bound of formal parameter
328 for nfd in nclassdef.n_formaldefs do
329 var nfdt = nfd.n_type
330 if nfdt != null and nfdt.mtype != null then
331 var bound = resolve_mtype(mmodule, mclassdef, nfdt)
332 if bound == null then return # Forward error
333 end
334 end
335 # check declared super types
336 for nsc in nclassdef.n_superclasses do
337 var ntype = nsc.n_type
338 if ntype.mtype != null then
339 var mtype = resolve_mtype(mmodule, mclassdef, ntype)
340 if mtype == null then return # Forward error
341 end
342 end
343 end
344 end
345
346 if errcount != toolcontext.error_count then return
347
348 # Check clash of ancestors
349 for nclassdef in nmodule.n_classdefs do
350 var mclassdef = nclassdef.mclassdef.as(not null)
351 var superclasses = new HashMap[MClass, MClassType]
352 for scd in mclassdef.in_hierarchy.greaters do
353 for st in scd.supertypes do
354 if not superclasses.has_key(st.mclass) then
355 superclasses[st.mclass] = st
356 else if superclasses[st.mclass] != st then
357 var st1 = superclasses[st.mclass].resolve_for(mclassdef.mclass.mclass_type, mclassdef.bound_mtype, mmodule, false)
358 var st2 = st.resolve_for(mclassdef.mclass.mclass_type, mclassdef.bound_mtype, mmodule, false)
359 if st1 != st2 then
360 error(nclassdef, "Error: Incompatibles ancestors for {mclassdef.mclass}: {st1}, {st2}")
361 end
362 end
363 end
364 end
365 end
366
367 if errcount != toolcontext.error_count then return
368
369 # TODO: Check that the super-class is not intrusive
370
371 # Check that the superclasses are not already known (by transitivity)
372 for nclassdef in nmodule.n_classdefs do
373 if not nclassdef isa AStdClassdef then continue
374 var mclassdef = nclassdef.mclassdef.as(not null)
375
376 # Get the direct superclasses
377 # Since we are a mclassdef, just look at the mclassdef hierarchy
378 var parents = new Array[MClass]
379 for sup in mclassdef.in_hierarchy.direct_greaters do
380 parents.add(sup.mclass)
381 end
382
383 # Used to track duplicates of superclasses
384 var seen_parents = new ArrayMap[MClass, AType]
385
386 # The Object class
387 var objectclass = try_get_mclass_by_name(nmodule, mmodule, "Object")
388
389 # Check each declared superclass to see if it belong to the direct superclass
390 for nsc in nclassdef.n_superclasses do
391 var ntype = nsc.n_type
392 var mtype = ntype.mtype
393 if mtype == null then continue
394 assert mtype isa MClassType
395 var sc = mtype.mclass
396 if not parents.has(sc) or sc == objectclass then
397 # Skip the warning on generated code
398 if ntype.location.file != null and not ntype.location.file.filename.is_empty then
399 warning(ntype, "useless-superclass", "Warning: superfluous super-class {mtype} in class {mclassdef.mclass}.")
400 end
401 else if not seen_parents.has_key(sc) then
402 seen_parents[sc] = ntype
403 else
404 warning(ntype, "useless-superclass", "Warning: duplicated super-class {mtype} in class {mclassdef.mclass}.")
405 end
406 end
407 end
408 end
409
410 # Register the nclassdef associated to each mclassdef
411 # FIXME: why not refine the `MClassDef` class with a nullable attribute?
412 var mclassdef2nclassdef = new HashMap[MClassDef, AClassdef]
413
414 # Return the static type associated to the node `ntype`.
415 # `mmodule` and `mclassdef` is the context where the call is made (used to understand formal types)
416 # In case of problem, an error is displayed on `ntype` and null is returned.
417 # FIXME: the name "resolve_mtype" is awful
418 fun resolve_mtype_unchecked(mmodule: MModule, mclassdef: nullable MClassDef, ntype: AType, with_virtual: Bool): nullable MType
419 do
420 var name = ntype.n_id.text
421 var res: MType
422
423 # Check virtual type
424 if mclassdef != null and with_virtual then
425 var prop = try_get_mproperty_by_name(ntype, mclassdef, name).as(nullable MVirtualTypeProp)
426 if prop != null then
427 if not ntype.n_types.is_empty then
428 error(ntype, "Type error: formal type {name} cannot have formal parameters.")
429 end
430 res = prop.mvirtualtype
431 if ntype.n_kwnullable != null then res = res.as_nullable
432 ntype.mtype = res
433 return res
434 end
435 end
436
437 # Check parameter type
438 if mclassdef != null then
439 for p in mclassdef.mclass.mparameters do
440 if p.name != name then continue
441
442 if not ntype.n_types.is_empty then
443 error(ntype, "Type error: formal type {name} cannot have formal parameters.")
444 end
445
446 res = p
447 if ntype.n_kwnullable != null then res = res.as_nullable
448 ntype.mtype = res
449 return res
450 end
451 end
452
453 # Check class
454 var mclass = try_get_mclass_by_name(ntype, mmodule, name)
455 if mclass != null then
456 var arity = ntype.n_types.length
457 if arity != mclass.arity then
458 if arity == 0 then
459 error(ntype, "Type error: '{name}' is a generic class.")
460 else if mclass.arity == 0 then
461 error(ntype, "Type error: '{name}' is not a generic class.")
462 else
463 error(ntype, "Type error: '{name}' has {mclass.arity} parameters ({arity} are provided).")
464 end
465 return null
466 end
467 if arity == 0 then
468 res = mclass.mclass_type
469 if ntype.n_kwnullable != null then res = res.as_nullable
470 ntype.mtype = res
471 return res
472 else
473 var mtypes = new Array[MType]
474 for nt in ntype.n_types do
475 var mt = resolve_mtype_unchecked(mmodule, mclassdef, nt, with_virtual)
476 if mt == null then return null # Forward error
477 mtypes.add(mt)
478 end
479 res = mclass.get_mtype(mtypes)
480 if ntype.n_kwnullable != null then res = res.as_nullable
481 ntype.mtype = res
482 return res
483 end
484 end
485
486 # If everything fail, then give up :(
487 error(ntype, "Type error: class {name} not found in module {mmodule}.")
488 return null
489 end
490
491 # Return the static type associated to the node `ntype`.
492 # `mmodule` and `mclassdef` is the context where the call is made (used to understand formal types)
493 # In case of problem, an error is displayed on `ntype` and null is returned.
494 # FIXME: the name "resolve_mtype" is awful
495 fun resolve_mtype(mmodule: MModule, mclassdef: nullable MClassDef, ntype: AType): nullable MType
496 do
497 var mtype = ntype.mtype
498 if mtype == null then mtype = resolve_mtype_unchecked(mmodule, mclassdef, ntype, true)
499 if mtype == null then return null # Forward error
500
501 if ntype.checked_mtype then return mtype
502 if mtype isa MGenericType then
503 var mclass = mtype.mclass
504 for i in [0..mclass.arity[ do
505 var bound = mclass.intro.bound_mtype.arguments[i]
506 var nt = ntype.n_types[i]
507 var mt = resolve_mtype(mmodule, mclassdef, nt)
508 if mt == null then return null # forward error
509 var anchor
510 if mclassdef != null then anchor = mclassdef.bound_mtype else anchor = null
511 if not mt.is_subtype(mmodule, anchor, bound) then
512 error(nt, "Type error: expected {bound}, got {mt}")
513 return null
514 end
515 end
516 end
517 ntype.checked_mtype = true
518 return mtype
519 end
520
521 end
522
523 redef class AModule
524 # Flag that indicate if the class building is already completed
525 var build_classes_is_done: Bool = false
526 # What is the AClassdef associated to a `MClass`?
527 # Used to check multiple definition of a class.
528 var mclass2nclassdef: Map[MClass, AClassdef] = new HashMap[MClass, AClassdef]
529 end
530
531 redef class AClassdef
532 # The associated MClass once build by a `ModelBuilder`
533 var mclass: nullable MClass
534 # The associated MClassDef once build by a `ModelBuilder`
535 var mclassdef: nullable MClassDef
536 # All (self and other) definitions for the same mclassdef
537 var all_defs: nullable Array[AClassdef]
538 end
539
540 redef class AClasskind
541 # The class kind associated with the AST node class
542 private fun mkind: MClassKind is abstract
543 end
544 redef class AConcreteClasskind
545 redef fun mkind do return concrete_kind
546 end
547 redef class AAbstractClasskind
548 redef fun mkind do return abstract_kind
549 end
550 redef class AInterfaceClasskind
551 redef fun mkind do return interface_kind
552 end
553 redef class AEnumClasskind
554 redef fun mkind do return enum_kind
555 end
556 redef class AExternClasskind
557 redef fun mkind do return extern_kind
558 end
559
560 redef class AFormaldef
561 # The associated parameter type
562 var mtype: nullable MParameterType = null
563
564 # The associated bound
565 var bound: nullable MType = null
566 end
567
568 redef class AType
569 # The mtype associated to the node
570 var mtype: nullable MType = null
571
572 # Is the mtype a valid one?
573 var checked_mtype: Bool = false
574 end