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