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