model: if Object has a SELF type, redef it in all classes
[nit.git] / src / modelize / modelize_property.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 property definitions to instantiate model element
18 module modelize_property
19
20 import modelize_class
21 private import annotation
22
23 redef class ToolContext
24 var modelize_property_phase: Phase = new ModelizePropertyPhase(self, [modelize_class_phase])
25 end
26
27 private class ModelizePropertyPhase
28 super Phase
29 redef fun process_nmodule(nmodule)
30 do
31 for nclassdef in nmodule.n_classdefs do
32 if nclassdef.all_defs == null then continue # skip non principal classdef
33 toolcontext.modelbuilder.build_properties(nclassdef)
34 end
35 end
36 end
37
38 redef class ModelBuilder
39 # Register the npropdef associated to each mpropdef
40 # FIXME: why not refine the `MPropDef` class with a nullable attribute?
41 var mpropdef2npropdef = new HashMap[MPropDef, APropdef]
42
43 # Build the properties of `nclassdef`.
44 # REQUIRE: all superclasses are built.
45 private fun build_properties(nclassdef: AClassdef)
46 do
47 # Force building recursively
48 if nclassdef.build_properties_is_done then return
49 nclassdef.build_properties_is_done = true
50 var mclassdef = nclassdef.mclassdef.as(not null)
51 if mclassdef.in_hierarchy == null then return # Skip error
52 for superclassdef in mclassdef.in_hierarchy.direct_greaters do
53 if not mclassdef2nclassdef.has_key(superclassdef) then continue
54 build_properties(mclassdef2nclassdef[superclassdef])
55 end
56
57 mclassdef.build_self_type(self, nclassdef)
58 for nclassdef2 in nclassdef.all_defs do
59 for npropdef in nclassdef2.n_propdefs do
60 npropdef.build_property(self, mclassdef)
61 end
62 for npropdef in nclassdef2.n_propdefs do
63 npropdef.build_signature(self)
64 end
65 for npropdef in nclassdef2.n_propdefs do
66 npropdef.check_signature(self)
67 end
68 end
69 process_default_constructors(nclassdef)
70 end
71
72 # the root init of the Object class
73 # Is usually implicitly defined
74 # Then explicit or implicit definitions of root-init are attached to it
75 var the_root_init_mmethod: nullable MMethod
76
77 # Introduce or inherit default constructor
78 # This is the last part of `build_properties`.
79 private fun process_default_constructors(nclassdef: AClassdef)
80 do
81 var mclassdef = nclassdef.mclassdef.as(not null)
82
83 # Are we a refinement
84 if not mclassdef.is_intro then return
85
86 # Look for the init in Object, or create it
87 if mclassdef.mclass.name == "Object" and the_root_init_mmethod == null then
88 # Create the implicit root-init method
89 var mprop = new MMethod(mclassdef, "init", mclassdef.mclass.visibility)
90 mprop.is_root_init = true
91 var mpropdef = new MMethodDef(mclassdef, mprop, nclassdef.location)
92 var mparameters = new Array[MParameter]
93 var msignature = new MSignature(mparameters, null)
94 mpropdef.msignature = msignature
95 mpropdef.new_msignature = msignature
96 mprop.is_init = true
97 nclassdef.mfree_init = mpropdef
98 self.toolcontext.info("{mclassdef} gets a free empty constructor {mpropdef}{msignature}", 3)
99 the_root_init_mmethod = mprop
100 return
101 end
102
103 # Is the class forbid constructors?
104 if not mclassdef.mclass.kind.need_init then return
105
106 # Is there already a constructor defined?
107 var defined_init: nullable MMethodDef = null
108 for mpropdef in mclassdef.mpropdefs do
109 if not mpropdef isa MMethodDef then continue
110 if not mpropdef.mproperty.is_init then continue
111 if mpropdef.mproperty.is_root_init then
112 assert defined_init == null
113 defined_init = mpropdef
114 else if mpropdef.mproperty.name == "init" then
115 # An explicit old-style init named "init", so return
116 return
117 end
118 end
119
120 if not nclassdef isa AStdClassdef then return
121
122 # Collect undefined attributes
123 var mparameters = new Array[MParameter]
124 var initializers = new Array[MProperty]
125 for npropdef in nclassdef.n_propdefs do
126 if npropdef isa AMethPropdef then
127 if npropdef.mpropdef == null then return # Skip broken attribute
128 var at = npropdef.get_single_annotation("autoinit", self)
129 if at == null then continue # Skip non tagged init
130
131 var sig = npropdef.mpropdef.msignature
132 if sig == null then continue # Skip broken method
133
134 if not npropdef.mpropdef.is_intro then
135 self.error(at, "Error: `autoinit` cannot be set on redefinitions")
136 continue
137 end
138
139 for param in sig.mparameters do
140 var ret_type = param.mtype
141 var mparameter = new MParameter(param.name, ret_type, false)
142 mparameters.add(mparameter)
143 end
144 initializers.add(npropdef.mpropdef.mproperty)
145 end
146 if npropdef isa AAttrPropdef then
147 if npropdef.mpropdef == null then return # Skip broken attribute
148 if npropdef.noinit then continue # Skip noinit attribute
149 var atautoinit = npropdef.get_single_annotation("autoinit", self)
150 if atautoinit != null then
151 # For autoinit attributes, call the reader to force
152 # the lazy initialization of the attribute.
153 initializers.add(npropdef.mreadpropdef.mproperty)
154 continue
155 end
156 if npropdef.has_value then continue
157 var paramname = npropdef.mpropdef.mproperty.name.substring_from(1)
158 var ret_type = npropdef.mpropdef.static_mtype
159 if ret_type == null then return
160 var mparameter = new MParameter(paramname, ret_type, false)
161 mparameters.add(mparameter)
162 var msetter = npropdef.mwritepropdef
163 if msetter == null then
164 # No setter, it is a old-style attribute, so just add it
165 initializers.add(npropdef.mpropdef.mproperty)
166 else
167 # Add the setter to the list
168 initializers.add(msetter.mproperty)
169 end
170 end
171 end
172
173 if the_root_init_mmethod == null then return
174
175 # Look for most-specific new-stype init definitions
176 var spropdefs = the_root_init_mmethod.lookup_super_definitions(mclassdef.mmodule, mclassdef.bound_mtype)
177 if spropdefs.is_empty then
178 toolcontext.fatal_error(nclassdef.location, "Fatal error: {mclassdef} does not specialize {the_root_init_mmethod.intro_mclassdef}. Possible duplication of the root class `Object`?")
179 end
180
181 # Search the longest-one and checks for conflict
182 var longest = spropdefs.first
183 if spropdefs.length > 1 then
184 # Check for conflict in the order of initializers
185 # Each initializer list must me a prefix of the longest list
186 # part 1. find the longest list
187 for spd in spropdefs do
188 if spd.initializers.length > longest.initializers.length then longest = spd
189 end
190 # part 2. compare
191 for spd in spropdefs do
192 var i = 0
193 for p in spd.initializers do
194 if p != longest.initializers[i] then
195 self.error(nclassdef, "Error: conflict for inherited inits {spd}({spd.initializers.join(", ")}) and {longest}({longest.initializers.join(", ")})")
196 return
197 end
198 i += 1
199 end
200 end
201 end
202
203 # Can we just inherit?
204 if spropdefs.length == 1 and mparameters.is_empty and defined_init == null then
205 self.toolcontext.info("{mclassdef} inherits the basic constructor {longest}", 3)
206 mclassdef.mclass.root_init = longest
207 return
208 end
209
210 # Combine the inherited list to what is collected
211 if longest.initializers.length > 0 then
212 mparameters.prepend longest.new_msignature.mparameters
213 initializers.prepend longest.initializers
214 end
215
216 # If we already have a basic init definition, then setup its initializers
217 if defined_init != null then
218 defined_init.initializers.add_all(initializers)
219 var msignature = new MSignature(mparameters, null)
220 defined_init.new_msignature = msignature
221 self.toolcontext.info("{mclassdef} extends its basic constructor signature to {defined_init}{msignature}", 3)
222 mclassdef.mclass.root_init = defined_init
223 return
224 end
225
226 # Else create the local implicit basic init definition
227 var mprop = the_root_init_mmethod.as(not null)
228 var mpropdef = new MMethodDef(mclassdef, mprop, nclassdef.location)
229 mpropdef.has_supercall = true
230 mpropdef.initializers.add_all(initializers)
231 var msignature = new MSignature(mparameters, null)
232 mpropdef.new_msignature = msignature
233 mpropdef.msignature = new MSignature(new Array[MParameter], null) # always an empty real signature
234 nclassdef.mfree_init = mpropdef
235 self.toolcontext.info("{mclassdef} gets a free constructor for attributes {mpropdef}{msignature}", 3)
236 mclassdef.mclass.root_init = mpropdef
237 end
238
239 # Check the visibility of `mtype` as an element of the signature of `mpropdef`.
240 fun check_visibility(node: ANode, mtype: MType, mpropdef: MPropDef)
241 do
242 var mmodule = mpropdef.mclassdef.mmodule
243 var mproperty = mpropdef.mproperty
244
245 # Extract visibility information of the main part of `mtype`
246 # It is a case-by case
247 var vis_type: nullable MVisibility = null # The own visibility of the type
248 var mmodule_type: nullable MModule = null # The original module of the type
249 mtype = mtype.as_notnullable
250 if mtype isa MClassType then
251 vis_type = mtype.mclass.visibility
252 mmodule_type = mtype.mclass.intro.mmodule
253 else if mtype isa MVirtualType then
254 vis_type = mtype.mproperty.visibility
255 mmodule_type = mtype.mproperty.intro_mclassdef.mmodule
256 else if mtype isa MParameterType then
257 # nothing, always visible
258 else
259 node.debug "Unexpected type {mtype}"
260 abort
261 end
262
263 if vis_type != null then
264 assert mmodule_type != null
265 var vis_module_type = mmodule.visibility_for(mmodule_type) # the visibility of the original module
266 if mproperty.visibility > vis_type then
267 error(node, "Error: The {mproperty.visibility} property `{mproperty}` cannot contain the {vis_type} type `{mtype}`")
268 return
269 else if mproperty.visibility > vis_module_type then
270 error(node, "Error: The {mproperty.visibility} property `{mproperty}` cannot contain the type `{mtype}` from the {vis_module_type} module `{mmodule_type}`")
271 return
272 end
273 end
274
275 # No error, try to go deeper in generic types
276 if node isa AType then
277 for a in node.n_types do
278 var t = a.mtype
279 if t == null then continue # Error, thus skipped
280 check_visibility(a, t, mpropdef)
281 end
282 else if mtype isa MGenericType then
283 for t in mtype.arguments do check_visibility(node, t, mpropdef)
284 end
285 end
286 end
287
288 redef class MPropDef
289 # Does the MPropDef contains a call to super or a call of a super-constructor?
290 # Subsequent phases of the frontend (esp. typing) set it if required
291 var has_supercall: Bool = false is writable
292 end
293
294 redef class AClassdef
295 var build_properties_is_done = false
296
297 # The free init (implicitely constructed by the class if required)
298 var mfree_init: nullable MMethodDef = null
299 end
300
301 redef class MClass
302 # The base init of the class.
303 # Used to get the common new_msignature and initializers
304 #
305 # TODO: Where to put this information is not clear because unlike other
306 # informations, the initialisers are stable in a same class.
307 var root_init: nullable MMethodDef = null
308 end
309
310 redef class MClassDef
311 # What is the `APropdef` associated to a `MProperty`?
312 # Used to check multiple definition of a property.
313 var mprop2npropdef: Map[MProperty, APropdef] = new HashMap[MProperty, APropdef]
314
315 # Build the virtual type `SELF` only for introduction `MClassDef`
316 fun build_self_type(modelbuilder: ModelBuilder, nclassdef: AClassdef)
317 do
318 if not is_intro then return
319
320 var name = "SELF"
321 var mprop = modelbuilder.try_get_mproperty_by_name(nclassdef, self, name)
322
323 # If SELF type is declared nowherer?
324 if mprop == null then return
325
326 # SELF is not a virtual type? it is weird but we ignore it
327 if not mprop isa MVirtualTypeProp then return
328
329 # Is this the intro of SELF in the library?
330 var intro = mprop.intro
331 var intro_mclassdef = intro.mclassdef
332 if intro_mclassdef == self then
333 var nintro = modelbuilder.mpropdef2npropdef[intro]
334
335 # SELF must be declared in Object, otherwise this will create conflicts
336 if intro_mclassdef.mclass.name != "Object" then
337 modelbuilder.error(nintro, "Error: the virtual type SELF must be declared in Object.")
338 end
339
340 # SELF must be public
341 if mprop.visibility != public_visibility then
342 modelbuilder.error(nintro, "Error: the virtual type SELF must be public.")
343 end
344
345 # SELF must not be fixed
346 if intro.is_fixed then
347 modelbuilder.error(nintro, "Error: the virtual type SELF cannot be fixed.")
348 end
349
350 return
351 end
352
353 # This class introduction inherits a SELF
354 # We insert an artificial property to update it
355 var mpropdef = new MVirtualTypeDef(self, mprop, self.location)
356 mpropdef.bound = mclass.mclass_type
357 end
358 end
359
360 redef class APropdef
361 # The associated main model entity
362 type MPROPDEF: MPropDef
363
364 # The associated propdef once build by a `ModelBuilder`
365 var mpropdef: nullable MPROPDEF is writable
366
367 private fun build_property(modelbuilder: ModelBuilder, mclassdef: MClassDef) is abstract
368 private fun build_signature(modelbuilder: ModelBuilder) is abstract
369 private fun check_signature(modelbuilder: ModelBuilder) is abstract
370 private fun new_property_visibility(modelbuilder: ModelBuilder, mclassdef: MClassDef, nvisibility: nullable AVisibility): MVisibility
371 do
372 var mvisibility = public_visibility
373 if nvisibility != null then
374 mvisibility = nvisibility.mvisibility
375 if mvisibility == intrude_visibility then
376 modelbuilder.error(nvisibility, "Error: intrude is not a legal visibility for properties.")
377 mvisibility = public_visibility
378 end
379 end
380 if mclassdef.mclass.visibility == private_visibility then
381 if mvisibility == protected_visibility then
382 assert nvisibility != null
383 modelbuilder.error(nvisibility, "Error: The only legal visibility for properties in a private class is private.")
384 else if mvisibility == private_visibility then
385 assert nvisibility != null
386 modelbuilder.advice(nvisibility, "useless-visibility", "Warning: private is superfluous since the only legal visibility for properties in a private class is private.")
387 end
388 mvisibility = private_visibility
389 end
390 return mvisibility
391 end
392
393 private fun set_doc(mpropdef: MPropDef, modelbuilder: ModelBuilder)
394 do
395 var ndoc = self.n_doc
396 if ndoc != null then
397 var mdoc = ndoc.to_mdoc
398 mpropdef.mdoc = mdoc
399 mdoc.original_mentity = mpropdef
400 else if mpropdef.is_intro and mpropdef.mproperty.visibility >= protected_visibility then
401 modelbuilder.advice(self, "missing-doc", "Documentation warning: Undocumented property `{mpropdef.mproperty}`")
402 end
403
404 var at_deprecated = get_single_annotation("deprecated", modelbuilder)
405 if at_deprecated != null then
406 if not mpropdef.is_intro then
407 modelbuilder.error(self, "Error: method redefinition cannot be deprecated.")
408 else
409 var info = new MDeprecationInfo
410 ndoc = at_deprecated.n_doc
411 if ndoc != null then info.mdoc = ndoc.to_mdoc
412 mpropdef.mproperty.deprecation = info
413 end
414 end
415 end
416
417 private fun check_redef_property_visibility(modelbuilder: ModelBuilder, nvisibility: nullable AVisibility, mprop: MProperty)
418 do
419 if nvisibility == null then return
420 var mvisibility = nvisibility.mvisibility
421 if mvisibility != mprop.visibility and mvisibility != public_visibility then
422 modelbuilder.error(nvisibility, "Error: redefinition changed the visibility from a {mprop.visibility} to a {mvisibility}")
423 end
424 end
425
426 private fun check_redef_keyword(modelbuilder: ModelBuilder, mclassdef: MClassDef, kwredef: nullable Token, need_redef: Bool, mprop: MProperty): Bool
427 do
428 if mclassdef.mprop2npropdef.has_key(mprop) then
429 modelbuilder.error(self, "Error: A property {mprop} is already defined in class {mclassdef.mclass} at line {mclassdef.mprop2npropdef[mprop].location.line_start}.")
430 return false
431 end
432 if mprop isa MMethod and mprop.is_toplevel != (parent isa ATopClassdef) then
433 if mprop.is_toplevel then
434 modelbuilder.error(self, "Error: {mprop} is a top level method.")
435 else
436 modelbuilder.error(self, "Error: {mprop} is not a top level method.")
437 end
438 return false
439
440 end
441 if kwredef == null then
442 if need_redef then
443 modelbuilder.error(self, "Redef error: {mclassdef.mclass}::{mprop.name} is an inherited property. To redefine it, add the redef keyword.")
444 return false
445 end
446 else
447 if not need_redef then
448 modelbuilder.error(self, "Error: No property {mclassdef.mclass}::{mprop.name} is inherited. Remove the redef keyword to define a new property.")
449 return false
450 end
451 end
452 return true
453 end
454
455 end
456
457 redef class ASignature
458 # Is the model builder has correctly visited the signature
459 var is_visited = false
460 # Names of parameters from the AST
461 # REQUIRE: is_visited
462 var param_names = new Array[String]
463 # Types of parameters from the AST
464 # REQUIRE: is_visited
465 var param_types = new Array[MType]
466 # Rank of the vararg (of -1 if none)
467 # REQUIRE: is_visited
468 var vararg_rank: Int = -1
469 # Return type
470 var ret_type: nullable MType = null
471
472 # Visit and fill information about a signature
473 private fun visit_signature(modelbuilder: ModelBuilder, mclassdef: MClassDef): Bool
474 do
475 var mmodule = mclassdef.mmodule
476 var param_names = self.param_names
477 var param_types = self.param_types
478 for np in self.n_params do
479 param_names.add(np.n_id.text)
480 var ntype = np.n_type
481 if ntype != null then
482 var mtype = modelbuilder.resolve_mtype(mmodule, mclassdef, ntype)
483 if mtype == null then return false # Skip error
484 for i in [0..param_names.length-param_types.length[ do
485 param_types.add(mtype)
486 end
487 if np.n_dotdotdot != null then
488 if self.vararg_rank != -1 then
489 modelbuilder.error(np, "Error: {param_names[self.vararg_rank]} is already a vararg")
490 return false
491 else
492 self.vararg_rank = param_names.length - 1
493 end
494 end
495 end
496 end
497 var ntype = self.n_type
498 if ntype != null then
499 self.ret_type = modelbuilder.resolve_mtype(mmodule, mclassdef, ntype)
500 if self.ret_type == null then return false # Skip error
501 end
502
503 self.is_visited = true
504 return true
505 end
506
507 # Build a visited signature
508 fun build_signature(modelbuilder: ModelBuilder): nullable MSignature
509 do
510 if param_names.length != param_types.length then
511 # Some parameters are typed, other parameters are not typed.
512 modelbuilder.error(self.n_params[param_types.length], "Error: Untyped parameter `{param_names[param_types.length]}'.")
513 return null
514 end
515
516 var mparameters = new Array[MParameter]
517 for i in [0..param_names.length[ do
518 var mparameter = new MParameter(param_names[i], param_types[i], i == vararg_rank)
519 self.n_params[i].mparameter = mparameter
520 mparameters.add(mparameter)
521 end
522
523 var msignature = new MSignature(mparameters, ret_type)
524 return msignature
525 end
526 end
527
528 redef class AParam
529 # The associated mparameter if any
530 var mparameter: nullable MParameter = null
531 end
532
533 redef class AMethPropdef
534 redef type MPROPDEF: MMethodDef
535
536
537 # Can self be used as a root init?
538 private fun look_like_a_root_init(modelbuilder: ModelBuilder, mclassdef: MClassDef): Bool
539 do
540 # Need the `init` keyword
541 if n_kwinit == null then return false
542 # Need to by anonymous
543 if self.n_methid != null then return false
544 # No annotation on itself
545 if get_single_annotation("old_style_init", modelbuilder) != null then return false
546 # Nor on its module
547 var amod = self.parent.parent.as(AModule)
548 var amoddecl = amod.n_moduledecl
549 if amoddecl != null then
550 var old = amoddecl.get_single_annotation("old_style_init", modelbuilder)
551 if old != null then return false
552 end
553 # No parameters
554 if self.n_signature.n_params.length > 0 then
555 modelbuilder.advice(self, "old-init", "Warning: init with signature in {mclassdef}")
556 return false
557 end
558 # Cannot be private or something
559 if not self.n_visibility isa APublicVisibility then
560 modelbuilder.advice(self, "old-init", "Warning: non-public init in {mclassdef}")
561 return false
562 end
563
564 return true
565 end
566
567 redef fun build_property(modelbuilder, mclassdef)
568 do
569 var n_kwinit = n_kwinit
570 var n_kwnew = n_kwnew
571 var is_init = n_kwinit != null or n_kwnew != null
572 var name: String
573 var amethodid = self.n_methid
574 var name_node: ANode
575 if amethodid == null then
576 if not is_init then
577 name = "main"
578 name_node = self
579 else if n_kwinit != null then
580 name = "init"
581 name_node = n_kwinit
582 else if n_kwnew != null then
583 name = "new"
584 name_node = n_kwnew
585 else
586 abort
587 end
588 else if amethodid isa AIdMethid then
589 name = amethodid.n_id.text
590 name_node = amethodid
591 else
592 # operator, bracket or assign
593 name = amethodid.collect_text
594 name_node = amethodid
595
596 if name == "-" and self.n_signature.n_params.length == 0 then
597 name = "unary -"
598 end
599 end
600
601 var look_like_a_root_init = look_like_a_root_init(modelbuilder, mclassdef)
602 var mprop: nullable MMethod = null
603 if not is_init or n_kwredef != null then mprop = modelbuilder.try_get_mproperty_by_name(name_node, mclassdef, name).as(nullable MMethod)
604 if mprop == null and look_like_a_root_init then
605 mprop = modelbuilder.the_root_init_mmethod
606 var nb = n_block
607 if nb isa ABlockExpr and nb.n_expr.is_empty and n_doc == null then
608 modelbuilder.advice(self, "useless-init", "Warning: useless empty init in {mclassdef}")
609 end
610 end
611 if mprop == null then
612 var mvisibility = new_property_visibility(modelbuilder, mclassdef, self.n_visibility)
613 mprop = new MMethod(mclassdef, name, mvisibility)
614 if look_like_a_root_init and modelbuilder.the_root_init_mmethod == null then
615 modelbuilder.the_root_init_mmethod = mprop
616 mprop.is_root_init = true
617 end
618 mprop.is_init = is_init
619 mprop.is_new = n_kwnew != null
620 if parent isa ATopClassdef then mprop.is_toplevel = true
621 if not self.check_redef_keyword(modelbuilder, mclassdef, n_kwredef, false, mprop) then return
622 else
623 if not mprop.is_root_init and not self.check_redef_keyword(modelbuilder, mclassdef, n_kwredef, not self isa AMainMethPropdef, mprop) then return
624 check_redef_property_visibility(modelbuilder, self.n_visibility, mprop)
625 end
626 mclassdef.mprop2npropdef[mprop] = self
627
628 var mpropdef = new MMethodDef(mclassdef, mprop, self.location)
629
630 set_doc(mpropdef, modelbuilder)
631
632 self.mpropdef = mpropdef
633 modelbuilder.mpropdef2npropdef[mpropdef] = self
634 if mpropdef.is_intro then
635 modelbuilder.toolcontext.info("{mpropdef} introduces new method {mprop.full_name}", 4)
636 else
637 modelbuilder.toolcontext.info("{mpropdef} redefines method {mprop.full_name}", 4)
638 end
639 end
640
641 redef fun build_signature(modelbuilder)
642 do
643 var mpropdef = self.mpropdef
644 if mpropdef == null then return # Error thus skiped
645 var mclassdef = mpropdef.mclassdef
646 var mmodule = mclassdef.mmodule
647 var nsig = self.n_signature
648
649 if mpropdef.mproperty.is_root_init and not mclassdef.is_intro then
650 var root_init = mclassdef.mclass.root_init
651 if root_init != null then
652 # Inherit the initializers by refinement
653 mpropdef.new_msignature = root_init.new_msignature
654 assert mpropdef.initializers.is_empty
655 mpropdef.initializers.add_all root_init.initializers
656 end
657 end
658
659 # Retrieve info from the signature AST
660 var param_names = new Array[String] # Names of parameters from the AST
661 var param_types = new Array[MType] # Types of parameters from the AST
662 var vararg_rank = -1
663 var ret_type: nullable MType = null # Return type from the AST
664 if nsig != null then
665 if not nsig.visit_signature(modelbuilder, mclassdef) then return
666 param_names = nsig.param_names
667 param_types = nsig.param_types
668 vararg_rank = nsig.vararg_rank
669 ret_type = nsig.ret_type
670 end
671
672 # Look for some signature to inherit
673 # FIXME: do not inherit from the intro, but from the most specific
674 var msignature: nullable MSignature = null
675 if not mpropdef.is_intro then
676 msignature = mpropdef.mproperty.intro.msignature
677 if msignature == null then return # Skip error
678
679 # Check inherited signature arity
680 if param_names.length != msignature.arity then
681 var node: ANode
682 if nsig != null then node = nsig else node = self
683 modelbuilder.error(node, "Redef error: {mpropdef} redefines {mpropdef.mproperty.intro} with {param_names.length} parameter(s), {msignature.arity} expected. Signature is {mpropdef}{msignature}")
684 return
685 end
686 else if mpropdef.mproperty.is_init and not mpropdef.mproperty.is_new then
687 # FIXME UGLY: inherit signature from a super-constructor
688 for msupertype in mclassdef.supertypes do
689 msupertype = msupertype.anchor_to(mmodule, mclassdef.bound_mtype)
690 var candidate = modelbuilder.try_get_mproperty_by_name2(self, mmodule, msupertype, mpropdef.mproperty.name)
691 if candidate != null then
692 if msignature == null then
693 msignature = candidate.intro.as(MMethodDef).msignature
694 end
695 end
696 end
697 end
698
699
700 # Inherit the signature
701 if msignature != null and param_names.length != param_types.length and param_names.length == msignature.arity and param_types.length == 0 then
702 # Parameters are untyped, thus inherit them
703 param_types = new Array[MType]
704 for mparameter in msignature.mparameters do
705 param_types.add(mparameter.mtype)
706 end
707 vararg_rank = msignature.vararg_rank
708 end
709 if msignature != null and ret_type == null then
710 ret_type = msignature.return_mtype
711 end
712
713 if param_names.length != param_types.length then
714 # Some parameters are typed, other parameters are not typed.
715 modelbuilder.error(nsig.n_params[param_types.length], "Error: Untyped parameter `{param_names[param_types.length]}'.")
716 return
717 end
718
719 var mparameters = new Array[MParameter]
720 for i in [0..param_names.length[ do
721 var mparameter = new MParameter(param_names[i], param_types[i], i == vararg_rank)
722 if nsig != null then nsig.n_params[i].mparameter = mparameter
723 mparameters.add(mparameter)
724 end
725
726 # In `new`-factories, the return type is by default the classtype.
727 if ret_type == null and mpropdef.mproperty.is_new then ret_type = mclassdef.mclass.mclass_type
728
729 msignature = new MSignature(mparameters, ret_type)
730 mpropdef.msignature = msignature
731 mpropdef.is_abstract = self.get_single_annotation("abstract", modelbuilder) != null
732 mpropdef.is_intern = self.get_single_annotation("intern", modelbuilder) != null
733 mpropdef.is_extern = self.n_extern_code_block != null or self.get_single_annotation("extern", modelbuilder) != null
734 end
735
736 redef fun check_signature(modelbuilder)
737 do
738 var mpropdef = self.mpropdef
739 if mpropdef == null then return # Error thus skiped
740 var mclassdef = mpropdef.mclassdef
741 var mmodule = mclassdef.mmodule
742 var nsig = self.n_signature
743 var mysignature = self.mpropdef.msignature
744 if mysignature == null then return # Error thus skiped
745
746 # Lookup for signature in the precursor
747 # FIXME all precursors should be considered
748 if not mpropdef.is_intro then
749 var msignature = mpropdef.mproperty.intro.msignature
750 if msignature == null then return
751
752 var precursor_ret_type = msignature.return_mtype
753 var ret_type = mysignature.return_mtype
754 if ret_type != null and precursor_ret_type == null then
755 modelbuilder.error(nsig.n_type.as(not null), "Redef Error: {mpropdef.mproperty} is a procedure, not a function.")
756 return
757 end
758
759 if mysignature.arity > 0 then
760 # Check parameters types
761 for i in [0..mysignature.arity[ do
762 var myt = mysignature.mparameters[i].mtype
763 var prt = msignature.mparameters[i].mtype
764 if not myt.is_subtype(mmodule, mclassdef.bound_mtype, prt) or
765 not prt.is_subtype(mmodule, mclassdef.bound_mtype, myt) then
766 modelbuilder.error(nsig.n_params[i], "Redef Error: Wrong type for parameter `{mysignature.mparameters[i].name}'. found {myt}, expected {prt} as in {mpropdef.mproperty.intro}.")
767 end
768 end
769 end
770 if precursor_ret_type != null then
771 if ret_type == null then
772 # Inherit the return type
773 ret_type = precursor_ret_type
774 else if not ret_type.is_subtype(mmodule, mclassdef.bound_mtype, precursor_ret_type) then
775 modelbuilder.error(nsig.n_type.as(not null), "Redef Error: Wrong return type. found {ret_type}, expected {precursor_ret_type} as in {mpropdef.mproperty.intro}.")
776 end
777 end
778 end
779
780 if mysignature.arity > 0 then
781 # Check parameters visibility
782 for i in [0..mysignature.arity[ do
783 var nt = nsig.n_params[i].n_type
784 if nt != null then modelbuilder.check_visibility(nt, nt.mtype.as(not null), mpropdef)
785 end
786 var nt = nsig.n_type
787 if nt != null then modelbuilder.check_visibility(nt, nt.mtype.as(not null), mpropdef)
788 end
789 end
790 end
791
792 redef class AAttrPropdef
793 redef type MPROPDEF: MAttributeDef
794
795 # Is the node tagged `noinit`?
796 var noinit = false
797
798 # Is the node tagged lazy?
799 var is_lazy = false
800
801 # Has the node a default value?
802 # Could be through `n_expr` or `n_block`
803 var has_value = false
804
805 # The guard associated to a lazy attribute.
806 # Because some engines does not have a working `isset`,
807 # this additional attribute is used to guard the lazy initialization.
808 # TODO: to remove once isset is correctly implemented
809 var mlazypropdef: nullable MAttributeDef
810
811 # The associated getter (read accessor) if any
812 var mreadpropdef: nullable MMethodDef is writable
813 # The associated setter (write accessor) if any
814 var mwritepropdef: nullable MMethodDef is writable
815
816 redef fun build_property(modelbuilder, mclassdef)
817 do
818 var mclass = mclassdef.mclass
819
820 var name: String
821 name = self.n_id2.text
822
823 if mclass.kind == interface_kind or mclassdef.mclass.kind == enum_kind then
824 modelbuilder.error(self, "Error: Attempt to define attribute {name} in the interface {mclass}.")
825 else if mclass.kind == enum_kind then
826 modelbuilder.error(self, "Error: Attempt to define attribute {name} in the enum class {mclass}.")
827 else if mclass.kind == extern_kind then
828 modelbuilder.error(self, "Error: Attempt to define attribute {name} in the extern class {mclass}.")
829 end
830
831 # New attribute style
832 var nid2 = self.n_id2
833 var mprop = new MAttribute(mclassdef, "_" + name, private_visibility)
834 var mpropdef = new MAttributeDef(mclassdef, mprop, self.location)
835 self.mpropdef = mpropdef
836 modelbuilder.mpropdef2npropdef[mpropdef] = self
837
838 var readname = name
839 var mreadprop = modelbuilder.try_get_mproperty_by_name(nid2, mclassdef, readname).as(nullable MMethod)
840 if mreadprop == null then
841 var mvisibility = new_property_visibility(modelbuilder, mclassdef, self.n_visibility)
842 mreadprop = new MMethod(mclassdef, readname, mvisibility)
843 if not self.check_redef_keyword(modelbuilder, mclassdef, n_kwredef, false, mreadprop) then return
844 mreadprop.deprecation = mprop.deprecation
845 else
846 if not self.check_redef_keyword(modelbuilder, mclassdef, n_kwredef, true, mreadprop) then return
847 check_redef_property_visibility(modelbuilder, self.n_visibility, mreadprop)
848 end
849 mclassdef.mprop2npropdef[mreadprop] = self
850
851 var mreadpropdef = new MMethodDef(mclassdef, mreadprop, self.location)
852 self.mreadpropdef = mreadpropdef
853 modelbuilder.mpropdef2npropdef[mreadpropdef] = self
854 set_doc(mreadpropdef, modelbuilder)
855 mpropdef.mdoc = mreadpropdef.mdoc
856
857 has_value = n_expr != null or n_block != null
858
859 var atnoinit = self.get_single_annotation("noinit", modelbuilder)
860 if atnoinit != null then
861 noinit = true
862 if has_value then
863 modelbuilder.error(atnoinit, "Error: `noinit` attributes cannot have an initial value")
864 return
865 end
866 end
867
868 var atlazy = self.get_single_annotation("lazy", modelbuilder)
869 var atautoinit = self.get_single_annotation("autoinit", modelbuilder)
870 if atlazy != null or atautoinit != null then
871 if atlazy != null and atautoinit != null then
872 modelbuilder.error(atlazy, "Error: lazy incompatible with autoinit")
873 return
874 end
875 if not has_value then
876 if atlazy != null then
877 modelbuilder.error(atlazy, "Error: a lazy attribute needs a value")
878 else if atautoinit != null then
879 modelbuilder.error(atautoinit, "Error: a autoinit attribute needs a value")
880 end
881 return
882 end
883 is_lazy = true
884 var mlazyprop = new MAttribute(mclassdef, "lazy _" + name, none_visibility)
885 var mlazypropdef = new MAttributeDef(mclassdef, mlazyprop, self.location)
886 self.mlazypropdef = mlazypropdef
887 end
888
889 var atreadonly = self.get_single_annotation("readonly", modelbuilder)
890 if atreadonly != null then
891 if not has_value then
892 modelbuilder.error(atreadonly, "Error: a readonly attribute needs a value")
893 end
894 # No setter, so just leave
895 return
896 end
897
898 var writename = name + "="
899 var atwritable = self.get_single_annotation("writable", modelbuilder)
900 if atwritable != null then
901 if not atwritable.n_args.is_empty then
902 writename = atwritable.arg_as_id(modelbuilder) or else writename
903 end
904 end
905 var mwriteprop = modelbuilder.try_get_mproperty_by_name(nid2, mclassdef, writename).as(nullable MMethod)
906 var nwkwredef: nullable Token = null
907 if atwritable != null then nwkwredef = atwritable.n_kwredef
908 if mwriteprop == null then
909 var mvisibility
910 if atwritable != null then
911 mvisibility = new_property_visibility(modelbuilder, mclassdef, atwritable.n_visibility)
912 else
913 mvisibility = private_visibility
914 end
915 mwriteprop = new MMethod(mclassdef, writename, mvisibility)
916 if not self.check_redef_keyword(modelbuilder, mclassdef, nwkwredef, false, mwriteprop) then return
917 mwriteprop.deprecation = mprop.deprecation
918 else
919 if not self.check_redef_keyword(modelbuilder, mclassdef, nwkwredef or else n_kwredef, true, mwriteprop) then return
920 if atwritable != null then
921 check_redef_property_visibility(modelbuilder, atwritable.n_visibility, mwriteprop)
922 end
923 end
924 mclassdef.mprop2npropdef[mwriteprop] = self
925
926 var mwritepropdef = new MMethodDef(mclassdef, mwriteprop, self.location)
927 self.mwritepropdef = mwritepropdef
928 modelbuilder.mpropdef2npropdef[mwritepropdef] = self
929 mwritepropdef.mdoc = mpropdef.mdoc
930 end
931
932 redef fun build_signature(modelbuilder)
933 do
934 var mpropdef = self.mpropdef
935 if mpropdef == null then return # Error thus skipped
936 var mclassdef = mpropdef.mclassdef
937 var mmodule = mclassdef.mmodule
938 var mtype: nullable MType = null
939
940 var mreadpropdef = self.mreadpropdef
941
942 var ntype = self.n_type
943 if ntype != null then
944 mtype = modelbuilder.resolve_mtype(mmodule, mclassdef, ntype)
945 if mtype == null then return
946 end
947
948 # Inherit the type from the getter (usually an abstract getter)
949 if mtype == null and mreadpropdef != null and not mreadpropdef.is_intro then
950 var msignature = mreadpropdef.mproperty.intro.msignature
951 if msignature == null then return # Error, thus skipped
952 mtype = msignature.return_mtype
953 end
954
955 var nexpr = self.n_expr
956 if mtype == null then
957 if nexpr != null then
958 if nexpr isa ANewExpr then
959 mtype = modelbuilder.resolve_mtype(mmodule, mclassdef, nexpr.n_type)
960 else if nexpr isa AIntExpr then
961 var cla = modelbuilder.try_get_mclass_by_name(nexpr, mmodule, "Int")
962 if cla != null then mtype = cla.mclass_type
963 else if nexpr isa AFloatExpr then
964 var cla = modelbuilder.try_get_mclass_by_name(nexpr, mmodule, "Float")
965 if cla != null then mtype = cla.mclass_type
966 else if nexpr isa ACharExpr then
967 var cla = modelbuilder.try_get_mclass_by_name(nexpr, mmodule, "Char")
968 if cla != null then mtype = cla.mclass_type
969 else if nexpr isa ABoolExpr then
970 var cla = modelbuilder.try_get_mclass_by_name(nexpr, mmodule, "Bool")
971 if cla != null then mtype = cla.mclass_type
972 else if nexpr isa ASuperstringExpr then
973 var cla = modelbuilder.try_get_mclass_by_name(nexpr, mmodule, "String")
974 if cla != null then mtype = cla.mclass_type
975 else if nexpr isa AStringFormExpr then
976 var cla = modelbuilder.try_get_mclass_by_name(nexpr, mmodule, "String")
977 if cla != null then mtype = cla.mclass_type
978 else
979 modelbuilder.error(self, "Error: Untyped attribute {mpropdef}. Implicit typing allowed only for literals and new.")
980 end
981
982 if mtype == null then return
983 end
984 else if ntype != null then
985 if nexpr isa ANewExpr then
986 var xmtype = modelbuilder.resolve_mtype(mmodule, mclassdef, nexpr.n_type)
987 if xmtype == mtype then
988 modelbuilder.advice(ntype, "useless-type", "Warning: useless type definition")
989 end
990 end
991 end
992
993 if mtype == null then
994 modelbuilder.error(self, "Error: Untyped attribute {mpropdef}")
995 return
996 end
997
998 mpropdef.static_mtype = mtype
999
1000 if mreadpropdef != null then
1001 var msignature = new MSignature(new Array[MParameter], mtype)
1002 mreadpropdef.msignature = msignature
1003 end
1004
1005 var mwritepropdef = self.mwritepropdef
1006 if mwritepropdef != null then
1007 var name: String
1008 name = n_id2.text
1009 var mparameter = new MParameter(name, mtype, false)
1010 var msignature = new MSignature([mparameter], null)
1011 mwritepropdef.msignature = msignature
1012 end
1013
1014 var mlazypropdef = self.mlazypropdef
1015 if mlazypropdef != null then
1016 mlazypropdef.static_mtype = modelbuilder.model.get_mclasses_by_name("Bool").first.mclass_type
1017 end
1018 end
1019
1020 redef fun check_signature(modelbuilder)
1021 do
1022 var mpropdef = self.mpropdef
1023 if mpropdef == null then return # Error thus skipped
1024 var ntype = self.n_type
1025 var mtype = self.mpropdef.static_mtype
1026 if mtype == null then return # Error thus skipped
1027
1028 # Lookup for signature in the precursor
1029 # FIXME all precursors should be considered
1030 if not mpropdef.is_intro then
1031 var precursor_type = mpropdef.mproperty.intro.static_mtype
1032 if precursor_type == null then return
1033
1034 if mtype != precursor_type then
1035 modelbuilder.error(ntype.as(not null), "Redef Error: Wrong static type. found {mtype}, expected {precursor_type}.")
1036 return
1037 end
1038 end
1039
1040 # Check getter and setter
1041 var meth = self.mreadpropdef
1042 if meth != null then
1043 self.check_method_signature(modelbuilder, meth)
1044 var node: nullable ANode = ntype
1045 if node == null then node = self
1046 modelbuilder.check_visibility(node, mtype, meth)
1047 end
1048 meth = self.mwritepropdef
1049 if meth != null then
1050 self.check_method_signature(modelbuilder, meth)
1051 var node: nullable ANode = ntype
1052 if node == null then node = self
1053 modelbuilder.check_visibility(node, mtype, meth)
1054 end
1055 end
1056
1057 private fun check_method_signature(modelbuilder: ModelBuilder, mpropdef: MMethodDef)
1058 do
1059 var mclassdef = mpropdef.mclassdef
1060 var mmodule = mclassdef.mmodule
1061 var nsig = self.n_type
1062 var mysignature = mpropdef.msignature
1063 if mysignature == null then return # Error thus skiped
1064
1065 # Lookup for signature in the precursor
1066 # FIXME all precursors should be considered
1067 if not mpropdef.is_intro then
1068 var msignature = mpropdef.mproperty.intro.msignature
1069 if msignature == null then return
1070
1071 if mysignature.arity != msignature.arity then
1072 var node: ANode
1073 if nsig != null then node = nsig else node = self
1074 modelbuilder.error(node, "Redef Error: {mysignature.arity} parameters found, {msignature.arity} expected. Signature is {mpropdef}{msignature}")
1075 return
1076 end
1077 var precursor_ret_type = msignature.return_mtype
1078 var ret_type = mysignature.return_mtype
1079 if ret_type != null and precursor_ret_type == null then
1080 var node: ANode
1081 if nsig != null then node = nsig else node = self
1082 modelbuilder.error(node, "Redef Error: {mpropdef.mproperty} is a procedure, not a function.")
1083 return
1084 end
1085
1086 if mysignature.arity > 0 then
1087 # Check parameters types
1088 for i in [0..mysignature.arity[ do
1089 var myt = mysignature.mparameters[i].mtype
1090 var prt = msignature.mparameters[i].mtype
1091 if not myt.is_subtype(mmodule, mclassdef.bound_mtype, prt) or
1092 not prt.is_subtype(mmodule, mclassdef.bound_mtype, myt) then
1093 var node: ANode
1094 if nsig != null then node = nsig else node = self
1095 modelbuilder.error(node, "Redef Error: Wrong type for parameter `{mysignature.mparameters[i].name}'. found {myt}, expected {prt}.")
1096 end
1097 end
1098 end
1099 if precursor_ret_type != null then
1100 if ret_type == null then
1101 # Inherit the return type
1102 ret_type = precursor_ret_type
1103 else if not ret_type.is_subtype(mmodule, mclassdef.bound_mtype, precursor_ret_type) then
1104 var node: ANode
1105 if nsig != null then node = nsig else node = self
1106 modelbuilder.error(node, "Redef Error: Wrong return type. found {ret_type}, expected {precursor_ret_type}.")
1107 end
1108 end
1109 end
1110 end
1111 end
1112
1113 redef class ATypePropdef
1114 redef type MPROPDEF: MVirtualTypeDef
1115
1116 redef fun build_property(modelbuilder, mclassdef)
1117 do
1118 var name = self.n_id.text
1119 var mprop = modelbuilder.try_get_mproperty_by_name(self.n_id, mclassdef, name)
1120 if mprop == null then
1121 var mvisibility = new_property_visibility(modelbuilder, mclassdef, self.n_visibility)
1122 mprop = new MVirtualTypeProp(mclassdef, name, mvisibility)
1123 for c in name.chars do if c >= 'a' and c<= 'z' then
1124 modelbuilder.warning(n_id, "bad-type-name", "Warning: lowercase in the virtual type {name}")
1125 break
1126 end
1127 if not self.check_redef_keyword(modelbuilder, mclassdef, self.n_kwredef, false, mprop) then return
1128 else
1129 if not self.check_redef_keyword(modelbuilder, mclassdef, self.n_kwredef, true, mprop) then return
1130 assert mprop isa MVirtualTypeProp
1131 check_redef_property_visibility(modelbuilder, self.n_visibility, mprop)
1132 end
1133 mclassdef.mprop2npropdef[mprop] = self
1134
1135 var mpropdef = new MVirtualTypeDef(mclassdef, mprop, self.location)
1136 self.mpropdef = mpropdef
1137 modelbuilder.mpropdef2npropdef[mpropdef] = self
1138 set_doc(mpropdef, modelbuilder)
1139
1140 var atfixed = get_single_annotation("fixed", modelbuilder)
1141 if atfixed != null then
1142 mpropdef.is_fixed = true
1143 end
1144 end
1145
1146 redef fun build_signature(modelbuilder)
1147 do
1148 var mpropdef = self.mpropdef
1149 if mpropdef == null then return # Error thus skipped
1150 var mclassdef = mpropdef.mclassdef
1151 var mmodule = mclassdef.mmodule
1152 var mtype: nullable MType = null
1153
1154 var ntype = self.n_type
1155 mtype = modelbuilder.resolve_mtype(mmodule, mclassdef, ntype)
1156 if mtype == null then return
1157
1158 mpropdef.bound = mtype
1159 # print "{mpropdef}: {mtype}"
1160 end
1161
1162 redef fun check_signature(modelbuilder)
1163 do
1164 var mpropdef = self.mpropdef
1165 if mpropdef == null then return # Error thus skipped
1166
1167 var bound = self.mpropdef.bound
1168 if bound == null then return # Error thus skipped
1169
1170 modelbuilder.check_visibility(n_type, bound, mpropdef)
1171
1172 var mclassdef = mpropdef.mclassdef
1173 var mmodule = mclassdef.mmodule
1174 var anchor = mclassdef.bound_mtype
1175
1176 # Check circularity
1177 if bound isa MVirtualType then
1178 # Slow case: progress on each resolution until: (i) we loop, or (ii) we found a non formal type
1179 var seen = [self.mpropdef.mproperty.mvirtualtype]
1180 loop
1181 if seen.has(bound) then
1182 seen.add(bound)
1183 modelbuilder.error(self, "Error: circularity of virtual type definition: {seen.join(" -> ")}")
1184 return
1185 end
1186 seen.add(bound)
1187 var next = bound.lookup_bound(mmodule, anchor)
1188 if not next isa MVirtualType then break
1189 bound = next
1190 end
1191 end
1192
1193 # Check redefinitions
1194 bound = mpropdef.bound.as(not null)
1195 for p in mpropdef.mproperty.lookup_super_definitions(mmodule, anchor) do
1196 var supbound = p.bound.as(not null)
1197 if p.is_fixed then
1198 modelbuilder.error(self, "Redef Error: Virtual type {mpropdef.mproperty} is fixed in super-class {p.mclassdef.mclass}")
1199 break
1200 end
1201 if p.mclassdef.mclass == mclassdef.mclass then
1202 # Still a warning to pass existing bad code
1203 modelbuilder.warning(n_type, "refine-type", "Redef Error: a virtual type cannot be refined.")
1204 break
1205 end
1206 if not bound.is_subtype(mmodule, anchor, supbound) then
1207 modelbuilder.error(n_type, "Redef Error: Wrong bound type. Found {bound}, expected a subtype of {supbound}, as in {p}.")
1208 break
1209 end
1210 end
1211 end
1212 end