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