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