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