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