modelize_property: Add `unsafe_add_mclassdef2nclassdef`
[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 intrude import modelize_class
21 private import annotation
22
23 redef class ToolContext
24 # Run `AClassdef::build_property` on the classdefs of each module
25 var modelize_property_phase: Phase = new ModelizePropertyPhase(self, [modelize_class_phase])
26 end
27
28 private class ModelizePropertyPhase
29 super Phase
30 redef fun process_nmodule(nmodule)
31 do
32 for nclassdef in nmodule.n_classdefs do
33 if nclassdef.all_defs == null then continue # skip non principal classdef
34 toolcontext.modelbuilder.build_properties(nclassdef)
35 end
36 end
37 end
38
39 redef class ModelBuilder
40 # Registration of the npropdef associated to each mpropdef.
41 #
42 # Public clients need to use `mpropdef2node` to access stuff.
43 private var mpropdef2npropdef = new HashMap[MPropDef, APropdef]
44
45 # Associate a `npropdef` with its `mpropdef`
46 #
47 # Be careful, this method is unsafe, no checking is done when it's used.
48 # The safe way to add method it's to use the `build_property`
49 #
50 # See `mpropdef2npropdef`
51 fun unsafe_add_mpropdef2npropdef(mpropdef: MPropDef,npropdef: APropdef)
52 do
53 mpropdef2npropdef[mpropdef] = npropdef
54 end
55
56 # Associate a `nclassdef` with its `mclassdef`
57 #
58 # Be careful, this method is unsafe, no checking is done when it's used.
59 # The safe way to add mclass it's to use the `build_property`
60 #
61 # See `mclassdef2nclassdef`
62 fun unsafe_add_mclassdef2nclassdef(mclassdef: MClassDef, nclassdef: AClassdef)
63 do
64 mclassdef2nclassdef[mclassdef] = nclassdef
65 end
66
67 # Retrieve the associated AST node of a mpropertydef.
68 # This method is used to associate model entity with syntactic entities.
69 #
70 # If the property definition is not associated with a node, returns `null`.
71 fun mpropdef2node(mpropdef: MPropDef): nullable ANode
72 do
73 var res
74 res = mpropdef2npropdef.get_or_null(mpropdef)
75 if res != null then
76 # Run the phases on it
77 toolcontext.run_phases_on_npropdef(res)
78 return res
79 end
80 # Fall back to the class node if any.
81 res = mclassdef2nclassdef.get_or_null(mpropdef.mclassdef)
82 if res != null then return res
83 return null
84 end
85
86 # Retrieve all the attributes nodes localy definied
87 # FIXME think more about this method and how the separations separate/global and ast/model should be done.
88 fun collect_attr_propdef(mclassdef: MClassDef): Array[AAttrPropdef]
89 do
90 var res = new Array[AAttrPropdef]
91 var n = mclassdef2nclassdef.get_or_null(mclassdef)
92 if n == null then return res
93 for npropdef in n.n_propdefs do
94 if npropdef isa AAttrPropdef then
95 # Run the phases on it
96 toolcontext.run_phases_on_npropdef(npropdef)
97 res.add(npropdef)
98 end
99 end
100 return res
101 end
102
103 # Build the properties of `nclassdef`.
104 private fun build_properties(nclassdef: AClassdef)
105 do
106 # Force building recursively
107 if nclassdef.build_properties_is_done then return
108 nclassdef.build_properties_is_done = true
109 var mclassdef = nclassdef.mclassdef
110 if mclassdef == null then return # skip error
111 if mclassdef.in_hierarchy == null then return # Skip error
112 for superclassdef in mclassdef.in_hierarchy.direct_greaters do
113 if not mclassdef2nclassdef.has_key(superclassdef) then continue
114 build_properties(mclassdef2nclassdef[superclassdef])
115 end
116
117 mclassdef.build_self_type(self, nclassdef)
118 for nclassdef2 in nclassdef.all_defs do
119 for npropdef in nclassdef2.n_propdefs do
120 npropdef.build_property(self, mclassdef)
121 end
122 for npropdef in nclassdef2.n_propdefs do
123 npropdef.build_signature(self)
124 end
125 for npropdef in nclassdef2.n_propdefs do
126 if not npropdef isa ATypePropdef then continue
127 # Check circularity
128 var mpropdef = npropdef.mpropdef
129 if mpropdef == null then continue
130 if mpropdef.bound == null then continue
131 if not check_virtual_types_circularity(npropdef, mpropdef.mproperty, mclassdef.bound_mtype, mclassdef.mmodule) then
132 # Invalidate the bound
133 mpropdef.is_broken = true
134 mpropdef.bound = new MErrorType(mclassdef.mmodule.model)
135 end
136 end
137 for npropdef in nclassdef2.n_propdefs do
138 # Check ATypePropdef first since they may be required for the other properties
139 if not npropdef isa ATypePropdef then continue
140 npropdef.check_signature(self)
141 end
142
143 for npropdef in nclassdef2.n_propdefs do
144 if npropdef isa ATypePropdef then continue
145 npropdef.check_signature(self)
146 end
147 end
148 process_default_constructors(nclassdef)
149 end
150
151 # the root init of the Object class
152 # Is usually implicitly defined
153 # Then explicit or implicit definitions of root-init are attached to it
154 var the_root_init_mmethod: nullable MMethod
155
156 # Introduce or inherit default constructor
157 # This is the last part of `build_properties`.
158 private fun process_default_constructors(nclassdef: AClassdef)
159 do
160 var mclassdef = nclassdef.mclassdef.as(not null)
161
162 # Are we a refinement
163 if not mclassdef.is_intro then
164 # Set the default_init of the mclassdef with the intro default_init
165 mclassdef.default_init = mclassdef.mclass.intro.default_init
166 return
167 end
168
169 # Look for the init in Object, or create it
170 if mclassdef.mclass.name == "Object" and the_root_init_mmethod == null then
171 # Create the implicit root-init method
172 var mprop = new MMethod(mclassdef, "init", nclassdef.location, mclassdef.mclass.visibility)
173 mprop.is_root_init = true
174 var mpropdef = new MMethodDef(mclassdef, mprop, nclassdef.location)
175 var mparameters = new Array[MParameter]
176 var msignature = new MSignature(mparameters, null)
177 mpropdef.msignature = msignature
178 mprop.is_init = true
179 self.toolcontext.info("{mclassdef} gets a free empty constructor {mpropdef}{msignature}", 3)
180 the_root_init_mmethod = mprop
181 end
182
183 # Is there already a constructor defined?
184 var defined_init: nullable MMethodDef = null
185 for mpropdef in mclassdef.mpropdefs do
186 if not mpropdef isa MMethodDef then continue
187 if not mpropdef.mproperty.is_init then continue
188 if mpropdef.mproperty.is_root_init then
189 assert defined_init == null
190 defined_init = mpropdef
191 else if mpropdef.name == "defaultinit" then
192 return
193 end
194 end
195
196 if mclassdef.default_init != null then return
197
198 # If the class is not AStdClassdef or it's an enum just return. No defaultinit is need.
199 if not nclassdef isa AStdClassdef or nclassdef.n_classkind isa AEnumClasskind then return
200
201 # Collect undefined attributes
202 var mparameters = new Array[MParameter]
203 var initializers = new Array[MProperty]
204 for npropdef in nclassdef.n_propdefs do
205 if npropdef isa AMethPropdef then
206 if not npropdef.is_autoinit then continue # Skip non tagged autoinit
207 var mpropdef = npropdef.mpropdef
208 if mpropdef == null then return # Skip broken method
209 var sig = mpropdef.msignature
210 if sig == null then continue # Skip broken method
211 mparameters.add_all sig.mparameters
212 initializers.add(mpropdef.mproperty)
213 mpropdef.mproperty.is_autoinit = true
214 end
215 if npropdef isa AAttrPropdef then
216 var mreadpropdef = npropdef.mreadpropdef
217 if mreadpropdef == null then return # Skip broken attribute
218 var msignature = mreadpropdef.msignature
219 if msignature == null then return # Skip broken attribute
220 if npropdef.noinit then continue # Skip noinit attribute
221 var atlateinit = npropdef.get_single_annotation("lateinit", self)
222 if atlateinit != null then
223 # For lateinit attributes, call the reader to force
224 # the lazy initialization of the attribute.
225 initializers.add(mreadpropdef.mproperty)
226 mreadpropdef.mproperty.is_autoinit = true
227 continue
228 end
229 if npropdef.has_value and not npropdef.is_optional then continue
230 var msetter = npropdef.mwritepropdef
231 if msetter == null then
232 # No setter, it is a readonly attribute, so just add it
233 var paramname = mreadpropdef.mproperty.name
234 var ret_type = msignature.return_mtype
235 if ret_type == null then return
236 var mparameter = new MParameter(paramname, ret_type, false)
237 mparameters.add(mparameter)
238
239 initializers.add(npropdef.mpropdef.mproperty)
240 npropdef.mpropdef.mproperty.is_autoinit = true
241 else
242 # Add the setter to the list
243 mparameters.add_all msetter.msignature.mparameters
244 initializers.add(msetter.mproperty)
245 msetter.mproperty.is_autoinit = true
246 end
247 end
248 end
249
250 var the_root_init_mmethod = self.the_root_init_mmethod
251 if the_root_init_mmethod == null then return
252
253 # Look for most-specific new-stype init definitions
254 var spropdefs = new ArraySet[MMethodDef]
255
256 for x in mclassdef.get_direct_supermtype do
257 var y = x.mclass.intro.default_init
258 if y == null then continue
259 if y.is_broken or y.msignature == null then return
260 spropdefs.add y
261 end
262
263 # Look at the autoinit class-annotation
264 var autoinit = nclassdef.get_single_annotation("autoinit", self)
265 var noautoinit = nclassdef.get_single_annotation("noautoinit", self)
266 if autoinit != null then
267 # Just throws the collected initializers
268 mparameters.clear
269 initializers.clear
270
271 if noautoinit != null then
272 error(autoinit, "Error: `autoinit` and `noautoinit` are incompatible.")
273 end
274
275 if autoinit.n_args.is_empty then
276 error(autoinit, "Syntax Error: `autoinit` expects method identifiers, use `noautoinit` to clear all autoinits.")
277 end
278
279 # Get and check each argument
280 for narg in autoinit.n_args do
281 var id = narg.as_id
282 if id == null then
283 error(narg, "Syntax Error: `autoinit` expects method identifiers.")
284 return
285 end
286
287 # Search the property.
288 # To avoid bad surprises, try to get the setter first.
289 var p = try_get_mproperty_by_name(narg, mclassdef, id + "=")
290 if p == null then
291 p = try_get_mproperty_by_name(narg, mclassdef, id)
292 end
293 if p == null then
294 error(narg, "Error: unknown method `{id}`")
295 return
296 end
297 if not p.is_autoinit then
298 error(narg, "Error: `{p}` is not an autoinit method")
299 return
300 end
301
302 # Register the initializer and the parameters
303 initializers.add(p)
304 var pd = p.intro
305 if pd isa MMethodDef then
306 # Get the signature resolved for the current receiver
307 var sig = pd.msignature.resolve_for(mclassdef.mclass.mclass_type, mclassdef.bound_mtype, mclassdef.mmodule, false)
308 mparameters.add_all(sig.mparameters)
309 else
310 # TODO attributes?
311 abort
312 end
313 end
314 else if spropdefs.not_empty then
315 # Search for inherited manual defaultinit
316 var manual = null
317 for s in spropdefs do
318 if mpropdef2npropdef.has_key(s) then
319 self.toolcontext.info("{mclassdef} inherits a manual defaultinit {s}", 3)
320 manual = s
321 end
322 end
323 # Search the longest-one and checks for conflict
324 var longest = spropdefs.first
325 if spropdefs.length > 1 then
326 # part 1. find the longest list
327 for spd in spropdefs do
328 if spd.initializers.length > longest.initializers.length then longest = spd
329
330 if spd != manual and manual != null then
331 self.toolcontext.info("{mclassdef} conflict between manual defaultinit {manual} and automatic defaultinit {spd}.", 3)
332 end
333 end
334 # conflict with manual autoinit?
335 if longest != manual and manual != null then
336 self.error(nclassdef, "Error: conflict between manual defaultinit {manual} and automatic defaultinit {longest}.")
337 end
338 # part 2. compare
339 # Check for conflict in the order of initializers
340 # Each initializer list must me a prefix of the longest list
341 # If `noautoinit` is set, just ignore conflicts
342 if noautoinit == null then for spd in spropdefs do
343 var i = 0
344 for p in spd.initializers do
345 if p != longest.initializers[i] then
346 var proposal = new ArraySet[MProperty]
347 for spd2 in spropdefs do
348 proposal.add_all spd2.initializers
349 end
350 proposal.add_all initializers
351 self.error(nclassdef, "Error: cannot generate automatic init for class {mclassdef.mclass}. Conflict in the order in inherited initializers {spd}({spd.initializers.join(", ")}) and {longest}({longest.initializers.join(", ")}). Use `autoinit` to order initializers. eg `autoinit {proposal.join(", ")}`")
352 # TODO: invalidate the initializer to avoid more errors
353 return
354 end
355 i += 1
356 end
357 end
358 end
359
360 if noautoinit != null then
361 # If there is local or inherited initializers, then complain.
362 if initializers.is_empty and longest.initializers.is_empty then
363 warning(noautoinit, "useless-noautoinit", "Warning: the list of autoinit is already empty.")
364 end
365 # Just clear initializers
366 mparameters.clear
367 initializers.clear
368 else
369 # Combine the inherited list to what is collected
370 if longest.initializers.length > 0 then
371 mparameters.prepend longest.msignature.mparameters
372 initializers.prepend longest.initializers
373 end
374 end
375 end
376
377 # Create a specific new autoinit constructor
378 do
379 var mprop = new MMethod(mclassdef, "defaultinit", nclassdef.location, public_visibility)
380 mprop.is_init = true
381 var mpropdef = new MMethodDef(mclassdef, mprop, nclassdef.location)
382 mpropdef.initializers.add_all(initializers)
383 var msignature = new MSignature(mparameters, null)
384 mpropdef.msignature = msignature
385 mclassdef.default_init = mpropdef
386 self.toolcontext.info("{mclassdef} gets a free auto constructor `{mpropdef}{msignature}`. {spropdefs}", 3)
387 mclassdef.mclass.the_root_init_mmethod = the_root_init_mmethod
388 end
389 end
390
391 # Check the visibility of `mtype` as an element of the signature of `mpropdef`.
392 fun check_visibility(node: ANode, mtype: MType, mpropdef: MPropDef)
393 do
394 var mmodule = mpropdef.mclassdef.mmodule
395 var mproperty = mpropdef.mproperty
396
397 # Extract visibility information of the main part of `mtype`
398 # It is a case-by case
399 var vis_type: nullable MVisibility = null # The own visibility of the type
400 var mmodule_type: nullable MModule = null # The original module of the type
401 mtype = mtype.undecorate
402 if mtype isa MClassType then
403 vis_type = mtype.mclass.visibility
404 mmodule_type = mtype.mclass.intro_mmodule
405 else if mtype isa MVirtualType then
406 vis_type = mtype.mproperty.visibility
407 mmodule_type = mtype.mproperty.intro_mclassdef.mmodule
408 else if mtype isa MParameterType then
409 # nothing, always visible
410 else if mtype isa MNullType then
411 # nothing to do.
412 else if mtype isa MBottomType then
413 # nothing to do.
414 else if mtype isa MErrorType then
415 # nothing to do.
416 else
417 node.debug "Unexpected type {mtype}"
418 abort
419 end
420
421 if vis_type != null then
422 assert mmodule_type != null
423 var vis_module_type = mmodule.visibility_for(mmodule_type) # the visibility of the original module
424 if mproperty.visibility > vis_type then
425 error(node, "Error: the {mproperty.visibility} property `{mproperty}` cannot contain the {vis_type} type `{mtype}`.")
426 return
427 else if mproperty.visibility > vis_module_type then
428 error(node, "Error: the {mproperty.visibility} property `{mproperty}` cannot contain the type `{mtype}` from the {vis_module_type} module `{mmodule_type}`.")
429 return
430 end
431 end
432
433 # No error, try to go deeper in generic types
434 if node isa AType then
435 for a in node.n_types do
436 var t = a.mtype
437 if t == null then continue # Error, thus skipped
438 check_visibility(a, t, mpropdef)
439 end
440 else if mtype isa MGenericType then
441 for t in mtype.arguments do check_visibility(node, t, mpropdef)
442 end
443 end
444
445 # Detect circularity errors for virtual types.
446 fun check_virtual_types_circularity(node: ANode, mproperty: MVirtualTypeProp, recv: MType, mmodule: MModule): Bool
447 do
448 # Check circularity
449 # Slow case: progress on each resolution until we visit all without getting a loop
450
451 # The graph used to detect loops
452 var mtype = mproperty.mvirtualtype
453 var poset = new POSet[MType]
454
455 # The work-list of types to resolve
456 var todo = new List[MType]
457 todo.add mtype
458
459 while not todo.is_empty do
460 # The visited type
461 var t = todo.pop
462
463 if not t.need_anchor then continue
464
465 # Get the types derived of `t` (subtypes and bounds)
466 var nexts
467 if t isa MNullableType then
468 nexts = [t.mtype]
469 else if t isa MGenericType then
470 nexts = t.arguments
471 else if t isa MVirtualType then
472 var vt = t.mproperty
473 # Because `vt` is possibly unchecked, we have to do the bound-lookup manually
474 var defs = vt.lookup_definitions(mmodule, recv)
475 if defs.is_empty then return false
476 nexts = new Array[MType]
477 for d in defs do
478 var next = defs.first.bound
479 if next == null then return false
480 nexts.add next
481 end
482 else if t isa MClassType then
483 # Basic type, nothing to to
484 continue
485 else if t isa MParameterType then
486 # Parameter types cannot depend on virtual types, so nothing to do
487 continue
488 else
489 abort
490 end
491
492 # For each one
493 for next in nexts do
494 if poset.has_edge(next, t) then
495 if mtype == next then
496 error(node, "Error: circularity of virtual type definition: {next} <-> {t}.")
497 else
498 error(node, "Error: circularity of virtual type definition: {mtype} -> {next} <-> {t}.")
499 end
500 return false
501 else
502 poset.add_edge(t, next)
503 todo.add next
504 end
505 end
506 end
507 return true
508 end
509 end
510
511 redef class MPropDef
512 # Does the MPropDef contains a call to super or a call of a super-constructor?
513 # Subsequent phases of the frontend (esp. typing) set it if required
514 var has_supercall: Bool = false is writable
515 end
516
517 redef class AClassdef
518 # Marker used in `ModelBuilder::build_properties`
519 private var build_properties_is_done = false
520 end
521
522 redef class MClass
523 # The base init of the class.
524 #
525 # TODO: merge with `root_init` and `ModelBuilder::the_root_init_mmethod` if possible
526 var the_root_init_mmethod: nullable MMethod = null
527 end
528
529 redef class MClassDef
530 # What is the `APropdef` associated to a `MProperty`?
531 # Used to check multiple definition of a property.
532 var mprop2npropdef: Map[MProperty, APropdef] = new HashMap[MProperty, APropdef]
533
534 # Build the virtual type `SELF` only for introduction `MClassDef`
535 fun build_self_type(modelbuilder: ModelBuilder, nclassdef: AClassdef)
536 do
537 if not is_intro then return
538
539 var name = "SELF"
540 var mprop = modelbuilder.try_get_mproperty_by_name(nclassdef, self, name)
541
542 # If SELF type is declared nowherer?
543 if mprop == null then return
544
545 # SELF is not a virtual type? it is weird but we ignore it
546 if not mprop isa MVirtualTypeProp then return
547
548 # Is this the intro of SELF in the library?
549 var intro = mprop.intro
550 var intro_mclassdef = intro.mclassdef
551 if intro_mclassdef == self then
552 var nintro = modelbuilder.mpropdef2npropdef[intro]
553
554 # SELF must be declared in Object, otherwise this will create conflicts
555 if intro_mclassdef.mclass.name != "Object" then
556 modelbuilder.error(nintro, "Error: the virtual type `SELF` must be declared in `Object`.")
557 end
558
559 # SELF must be public
560 if mprop.visibility != public_visibility then
561 modelbuilder.error(nintro, "Error: the virtual type `SELF` must be public.")
562 end
563
564 # SELF must not be fixed
565 if intro.is_fixed then
566 modelbuilder.error(nintro, "Error: the virtual type `SELF` cannot be fixed.")
567 end
568
569 return
570 end
571
572 # This class introduction inherits a SELF
573 # We insert an artificial property to update it
574 var mpropdef = new MVirtualTypeDef(self, mprop, self.location)
575 mpropdef.bound = mclass.mclass_type
576 end
577 end
578
579 redef class APropdef
580 # The associated main model entity
581 type MPROPDEF: MPropDef
582
583 # The associated propdef once build by a `ModelBuilder`
584 var mpropdef: nullable MPROPDEF is writable
585
586 private fun build_property(modelbuilder: ModelBuilder, mclassdef: MClassDef) do end
587 private fun build_signature(modelbuilder: ModelBuilder) do end
588 private fun check_signature(modelbuilder: ModelBuilder) do end
589 private fun new_property_visibility(modelbuilder: ModelBuilder, mclassdef: MClassDef, nvisibility: nullable AVisibility): MVisibility
590 do
591 var mvisibility = public_visibility
592 if nvisibility != null then
593 mvisibility = nvisibility.mvisibility
594 if mvisibility == intrude_visibility then
595 modelbuilder.error(nvisibility, "Error: `intrude` is not a legal visibility for properties.")
596 mvisibility = public_visibility
597 end
598 end
599 if mclassdef.mclass.visibility == private_visibility then
600 if mvisibility == protected_visibility then
601 assert nvisibility != null
602 modelbuilder.error(nvisibility, "Error: `private` is the only legal visibility for properties in a private class.")
603 else if mvisibility == private_visibility then
604 assert nvisibility != null
605 modelbuilder.advice(nvisibility, "useless-visibility", "Warning: `private` is superfluous since the only legal visibility for properties in a private class is private.")
606 end
607 mvisibility = private_visibility
608 end
609 return mvisibility
610 end
611
612 private fun set_doc(mpropdef: MPropDef, modelbuilder: ModelBuilder)
613 do
614 var ndoc = self.n_doc
615 if ndoc != null then
616 var mdoc = ndoc.to_mdoc
617 mpropdef.mdoc = mdoc
618 mdoc.original_mentity = mpropdef
619 else if mpropdef.is_intro and mpropdef.mproperty.visibility >= protected_visibility and mpropdef.name != "new" then
620 modelbuilder.advice(self, "missing-doc", "Documentation warning: Undocumented property `{mpropdef.mproperty}`")
621 end
622
623 var at_deprecated = get_single_annotation("deprecated", modelbuilder)
624 if at_deprecated != null then
625 if not mpropdef.is_intro then
626 modelbuilder.error(self, "Error: method redefinition cannot be deprecated.")
627 else
628 var info = new MDeprecationInfo
629 ndoc = at_deprecated.n_doc
630 if ndoc != null then info.mdoc = ndoc.to_mdoc
631 mpropdef.mproperty.deprecation = info
632 end
633 end
634 end
635
636 private fun check_redef_property_visibility(modelbuilder: ModelBuilder, nvisibility: nullable AVisibility, mprop: MProperty)
637 do
638 if nvisibility == null then return
639 var mvisibility = nvisibility.mvisibility
640 if mvisibility != mprop.visibility and mvisibility != public_visibility then
641 modelbuilder.error(nvisibility, "Error: redefinition changed the visibility from `{mprop.visibility}` to `{mvisibility}`.")
642 end
643 end
644
645 private fun check_redef_keyword(modelbuilder: ModelBuilder, mclassdef: MClassDef, kwredef: nullable Token, need_redef: Bool, mprop: MProperty): Bool
646 do
647 if mclassdef.mprop2npropdef.has_key(mprop) then
648 modelbuilder.error(self, "Error: a property `{mprop}` is already defined in class `{mclassdef.mclass}` at line {mclassdef.mprop2npropdef[mprop].location.line_start}.")
649 return false
650 end
651 if mprop isa MMethod and mprop.is_root_init then return true
652 if kwredef == null then
653 if need_redef then
654 modelbuilder.error(self, "Redef Error: `{mclassdef.mclass}::{mprop.name}` is an inherited property. To redefine it, add the `redef` keyword.")
655 return false
656 end
657
658 # Check for full-name conflicts in the package.
659 # A public property should have a unique qualified name `package::class::prop`.
660 if mprop.intro_mclassdef.mmodule.mgroup != null and mprop.visibility >= protected_visibility then
661 var others = modelbuilder.model.get_mproperties_by_name(mprop.name)
662 if others != null then for other in others do
663 if other != mprop and other.intro_mclassdef.mmodule.mgroup != null and other.intro_mclassdef.mmodule.mgroup.mpackage == mprop.intro_mclassdef.mmodule.mgroup.mpackage and other.intro_mclassdef.mclass.name == mprop.intro_mclassdef.mclass.name and other.visibility >= protected_visibility then
664 modelbuilder.advice(self, "full-name-conflict", "Warning: A property named `{other.full_name}` is already defined in module `{other.intro_mclassdef.mmodule}` for the class `{other.intro_mclassdef.mclass.name}`.")
665 break
666 end
667 end
668 end
669 else
670 if not need_redef then
671 modelbuilder.error(self, "Error: no property `{mclassdef.mclass}::{mprop.name}` is inherited. Remove the `redef` keyword to define a new property.")
672 return false
673 end
674 end
675 return true
676 end
677
678 # Checks for useless type in redef signatures.
679 private fun check_repeated_types(modelbuilder: ModelBuilder) do end
680 end
681
682 redef class ASignature
683 # Is the model builder has correctly visited the signature
684 var is_visited = false
685 # Names of parameters from the AST
686 # REQUIRE: is_visited
687 var param_names = new Array[String]
688 # Types of parameters from the AST
689 # REQUIRE: is_visited
690 var param_types = new Array[MType]
691 # Rank of the vararg (of -1 if none)
692 # REQUIRE: is_visited
693 var vararg_rank: Int = -1
694 # Return type
695 var ret_type: nullable MType = null
696
697 # Visit and fill information about a signature
698 private fun visit_signature(modelbuilder: ModelBuilder, mclassdef: MClassDef): Bool
699 do
700 var param_names = self.param_names
701 var param_types = self.param_types
702 for np in self.n_params do
703 param_names.add(np.n_id.text)
704 var ntype = np.n_type
705 if ntype != null then
706 var mtype = modelbuilder.resolve_mtype_unchecked(mclassdef, ntype, true)
707 if mtype == null then return false # Skip error
708 for i in [0..param_names.length-param_types.length[ do
709 param_types.add(mtype)
710 end
711 if np.n_dotdotdot != null then
712 if self.vararg_rank != -1 then
713 modelbuilder.error(np, "Error: `{param_names[self.vararg_rank]}` is already a vararg")
714 return false
715 else
716 self.vararg_rank = param_names.length - 1
717 end
718 end
719 end
720 end
721 var ntype = self.n_type
722 if ntype != null then
723 self.ret_type = modelbuilder.resolve_mtype_unchecked(mclassdef, ntype, true)
724 if self.ret_type == null then return false # Skip error
725 end
726
727 self.is_visited = true
728 return true
729 end
730
731 private fun check_signature(modelbuilder: ModelBuilder, mclassdef: MClassDef): Bool
732 do
733 var res = true
734 for np in self.n_params do
735 var ntype = np.n_type
736 if ntype != null then
737 if modelbuilder.resolve_mtype(mclassdef, ntype) == null then
738 res = false
739 end
740 end
741 end
742 var ntype = self.n_type
743 if ntype != null then
744 if modelbuilder.resolve_mtype(mclassdef, ntype) == null then
745 res = false
746 end
747 end
748 if not res then is_broken = true
749 return res
750 end
751 end
752
753 redef class AParam
754 # The associated mparameter if any
755 var mparameter: nullable MParameter = null
756 end
757
758 redef class AMethPropdef
759 redef type MPROPDEF: MMethodDef
760
761 # Is the method annotated `autoinit`?
762 var is_autoinit = false
763
764 # Can self be used as a root init?
765 private fun look_like_a_root_init(modelbuilder: ModelBuilder, mclassdef: MClassDef): Bool
766 do
767 # Need the `init` keyword
768 if n_kwinit == null then return false
769 # Need to by anonymous
770 if self.n_methid != null then return false
771 # No annotation on itself
772 if get_single_annotation("old_style_init", modelbuilder) != null then return false
773 # Nor on its module
774 var amod = self.parent.parent.as(AModule)
775 var amoddecl = amod.n_moduledecl
776 if amoddecl != null then
777 var old = amoddecl.get_single_annotation("old_style_init", modelbuilder)
778 if old != null then return false
779 end
780 # No parameters
781 if self.n_signature.n_params.length > 0 then
782 modelbuilder.advice(self, "old-init", "Warning: init with signature in {mclassdef}")
783 return false
784 end
785 # Cannot be private or something
786 if not self.n_visibility isa APublicVisibility then
787 modelbuilder.advice(self, "old-init", "Warning: non-public init in {mclassdef}")
788 return false
789 end
790
791 return true
792 end
793
794 redef fun build_property(modelbuilder, mclassdef)
795 do
796 var n_kwinit = n_kwinit
797 var n_kwnew = n_kwnew
798 var is_new = n_kwnew != null
799 var is_init = n_kwinit != null or is_new
800 var name: String
801 var amethodid = self.n_methid
802 var name_node: ANode
803 var is_old_style_init = false
804 if amethodid == null then
805 if n_kwinit != null then
806 name = "init"
807 name_node = n_kwinit
808 var old_style_annot = get_single_annotation("old_style_init", modelbuilder)
809 if old_style_annot != null or self.n_signature.n_params.not_empty then
810 name = "defaultinit"
811 if old_style_annot != null then is_old_style_init = true
812 end
813 else if n_kwnew != null then
814 name = "new"
815 name_node = n_kwnew
816 else
817 name = "main"
818 name_node = self
819 end
820 else if amethodid isa AIdMethid then
821 name = amethodid.n_id.text
822 name_node = amethodid
823 else
824 # operator, bracket or assign
825 name = amethodid.collect_text
826 name_node = amethodid
827
828 var arity = self.n_signature.n_params.length
829 if name == "+" and arity == 0 then
830 name = "unary +"
831 else if name == "-" and arity == 0 then
832 name = "unary -"
833 else if name == "~" and arity == 0 then
834 name = "unary ~"
835 else
836 if amethodid.is_binary and arity != 1 then
837 modelbuilder.error(self.n_signature, "Syntax Error: binary operator `{name}` requires exactly one parameter; got {arity}.")
838 else if amethodid.min_arity > arity then
839 modelbuilder.error(self.n_signature, "Syntax Error: `{name}` requires at least {amethodid.min_arity} parameter(s); got {arity}.")
840 end
841 end
842 end
843
844 var look_like_a_root_init = look_like_a_root_init(modelbuilder, mclassdef)
845 var mprop: nullable MMethod = null
846 if not is_init or n_kwredef != null or look_like_a_root_init then mprop = modelbuilder.try_get_mproperty_by_name(name_node, mclassdef, name).as(nullable MMethod)
847 if mprop == null and look_like_a_root_init then
848 mprop = modelbuilder.the_root_init_mmethod
849 var nb = n_block
850 if nb isa ABlockExpr and nb.n_expr.is_empty and n_doc == null then
851 modelbuilder.advice(self, "useless-init", "Warning: useless empty init in {mclassdef}")
852 end
853 end
854 if mprop == null then
855 var mvisibility = new_property_visibility(modelbuilder, mclassdef, self.n_visibility)
856 mprop = new MMethod(mclassdef, name, self.location, mvisibility)
857 if look_like_a_root_init and modelbuilder.the_root_init_mmethod == null then
858 modelbuilder.the_root_init_mmethod = mprop
859 mprop.is_root_init = true
860 end
861 mprop.is_init = is_init
862 mprop.is_new = is_new
863 if is_new then mclassdef.mclass.has_new_factory = true
864 if name == "sys" then mprop.is_toplevel = true # special case for sys allowed in `new` factories
865 if not self.check_redef_keyword(modelbuilder, mclassdef, n_kwredef, false, mprop) then
866 mprop.is_broken = true
867 return
868 end
869 else
870 if mprop.is_broken then return
871 if not self.check_redef_keyword(modelbuilder, mclassdef, n_kwredef, not self isa AMainMethPropdef, mprop) then return
872 check_redef_property_visibility(modelbuilder, self.n_visibility, mprop)
873 end
874
875 # Check name conflicts in the local class for constructors.
876 if is_init then
877 for p, n in mclassdef.mprop2npropdef do
878 if p != mprop and p isa MMethod and p.name == name then
879 if not check_redef_keyword(modelbuilder, mclassdef, n_kwredef, false, p) then
880 mprop.is_broken = true
881 return
882 end
883 break
884 end
885 end
886 end
887
888 mclassdef.mprop2npropdef[mprop] = self
889
890 var mpropdef = new MMethodDef(mclassdef, mprop, self.location)
891 if mpropdef.name == "defaultinit" and mclassdef.is_intro then
892 assert mclassdef.default_init == null
893 mpropdef.is_old_style_init = is_old_style_init
894 mclassdef.default_init = mpropdef
895 # Set the initializers with the mproperty.
896 # This point is need when a super class define this own default_init and inherited class use the default_init generated automaticlely.
897 mpropdef.initializers.add mprop
898 mpropdef.is_calling_init = true
899 end
900
901 set_doc(mpropdef, modelbuilder)
902
903 self.mpropdef = mpropdef
904 modelbuilder.mpropdef2npropdef[mpropdef] = self
905 if mpropdef.is_intro then
906 modelbuilder.toolcontext.info("{mpropdef} introduces new method {mprop.full_name}", 4)
907 else
908 modelbuilder.toolcontext.info("{mpropdef} redefines method {mprop.full_name}", 4)
909 end
910 end
911
912 redef fun build_signature(modelbuilder)
913 do
914 var mpropdef = self.mpropdef
915 if mpropdef == null then return # Error thus skiped
916 var mproperty = mpropdef.mproperty
917 var mclassdef = mpropdef.mclassdef
918 var mmodule = mclassdef.mmodule
919 var nsig = self.n_signature
920
921 var accept_special_last_parameter = self.n_methid == null or self.n_methid.accept_special_last_parameter
922 var return_is_mandatory = self.n_methid != null and self.n_methid.return_is_mandatory
923
924 # Retrieve info from the signature AST
925 var param_names = new Array[String] # Names of parameters from the AST
926 var param_types = new Array[MType] # Types of parameters from the AST
927 var vararg_rank = -1
928 var ret_type: nullable MType = null # Return type from the AST
929 if nsig != null then
930 if not nsig.visit_signature(modelbuilder, mclassdef) then return
931 param_names = nsig.param_names
932 param_types = nsig.param_types
933 vararg_rank = nsig.vararg_rank
934 ret_type = nsig.ret_type
935 end
936
937 # Look for some signature to inherit
938 # FIXME: do not inherit from the intro, but from the most specific
939 var msignature: nullable MSignature = null
940 if not mpropdef.is_intro then
941 msignature = mproperty.intro.msignature
942 if msignature == null then return # Skip error
943
944 # The local signature is adapted to use the local formal types, if any.
945 msignature = msignature.resolve_for(mclassdef.mclass.mclass_type, mclassdef.bound_mtype, mmodule, false)
946
947 # Check inherited signature arity
948 if param_names.length != msignature.arity then
949 var node: ANode
950 if nsig != null then node = nsig else node = self
951 modelbuilder.error(node, "Redef Error: expected {msignature.arity} parameter(s) for `{mproperty.name}{msignature}`; got {param_names.length}. See introduction at `{mproperty.full_name}`.")
952 return
953 end
954 else if mproperty.is_init and not mproperty.is_new then
955 # FIXME UGLY: inherit signature from a super-constructor
956 for msupertype in mclassdef.supertypes do
957 msupertype = msupertype.anchor_to(mmodule, mclassdef.bound_mtype)
958 var candidate = modelbuilder.try_get_mproperty_by_name2(self, mmodule, msupertype, mproperty.name)
959 if candidate != null then
960 if msignature == null then
961 msignature = candidate.intro.as(MMethodDef).msignature
962 end
963 end
964 end
965 end
966
967
968 # Inherit the signature
969 if msignature != null and param_names.length != param_types.length and param_names.length == msignature.arity and param_types.length == 0 then
970 # Parameters are untyped, thus inherit them
971 param_types = new Array[MType]
972 for mparameter in msignature.mparameters do
973 param_types.add(mparameter.mtype)
974 end
975 vararg_rank = msignature.vararg_rank
976 end
977 if msignature != null and ret_type == null then
978 ret_type = msignature.return_mtype
979 end
980
981 if param_names.length != param_types.length then
982 # Some parameters are typed, other parameters are not typed.
983 modelbuilder.error(nsig.n_params[param_types.length], "Error: untyped parameter `{param_names[param_types.length]}'.")
984 return
985 end
986
987 var mparameters = new Array[MParameter]
988 for i in [0..param_names.length[ do
989 var mparameter = new MParameter(param_names[i], param_types[i], i == vararg_rank)
990 if nsig != null then nsig.n_params[i].mparameter = mparameter
991 mparameters.add(mparameter)
992 end
993
994 # In `new`-factories, the return type is by default the classtype.
995 if ret_type == null and mproperty.is_new then ret_type = mclassdef.mclass.mclass_type
996
997 # Special checks for operator methods
998 if not accept_special_last_parameter and mparameters.not_empty and mparameters.last.is_vararg then
999 modelbuilder.error(self.n_signature.n_params.last, "Error: illegal variadic parameter `{mparameters.last}` for `{mproperty.name}`.")
1000 end
1001 if ret_type == null and return_is_mandatory then
1002 modelbuilder.error(self.n_methid, "Error: mandatory return type for `{mproperty.name}`.")
1003 end
1004
1005 msignature = new MSignature(mparameters, ret_type)
1006 mpropdef.msignature = msignature
1007 mpropdef.is_abstract = self.get_single_annotation("abstract", modelbuilder) != null
1008 mpropdef.is_intern = self.get_single_annotation("intern", modelbuilder) != null
1009 mpropdef.is_extern = self.n_extern_code_block != null or self.get_single_annotation("extern", modelbuilder) != null
1010
1011 # Check annotations
1012 var at = self.get_single_annotation("lazy", modelbuilder)
1013 if at != null then modelbuilder.error(at, "Syntax Error: `lazy` must be used on attributes.")
1014
1015 var atautoinit = self.get_single_annotation("autoinit", modelbuilder)
1016 if atautoinit != null then
1017 if not mpropdef.is_intro then
1018 modelbuilder.error(atautoinit, "Error: `autoinit` cannot be set on redefinitions.")
1019 else if not mclassdef.is_intro then
1020 modelbuilder.error(atautoinit, "Error: `autoinit` cannot be used in class refinements.")
1021 else
1022 self.is_autoinit = true
1023 end
1024 end
1025 end
1026
1027 redef fun check_signature(modelbuilder)
1028 do
1029 var mpropdef = self.mpropdef
1030 if mpropdef == null then return # Error thus skiped
1031 var mclassdef = mpropdef.mclassdef
1032 var mmodule = mclassdef.mmodule
1033 var nsig = self.n_signature
1034 var mysignature = mpropdef.msignature
1035 if mysignature == null then return # Error thus skiped
1036
1037 # Check
1038 if nsig != null then
1039 if not nsig.check_signature(modelbuilder, mclassdef) then
1040 mpropdef.msignature = null # invalidate
1041 mpropdef.is_broken = true
1042 return # Forward error
1043 end
1044 end
1045
1046 # Lookup for signature in the precursor
1047 # FIXME all precursors should be considered
1048 if not mpropdef.is_intro then
1049 var msignature = mpropdef.mproperty.intro.msignature
1050 if msignature == null then return
1051
1052 var precursor_ret_type = msignature.return_mtype
1053 var ret_type = mysignature.return_mtype
1054 if ret_type != null and precursor_ret_type == null then
1055 modelbuilder.error(nsig.n_type, "Redef Error: `{mpropdef.mproperty}` is a procedure, not a function.")
1056 mpropdef.msignature = null
1057 mpropdef.is_broken = true
1058 return
1059 end
1060
1061 if mysignature.arity > 0 then
1062 # Check parameters types
1063 for i in [0..mysignature.arity[ do
1064 var myt = mysignature.mparameters[i].mtype
1065 var prt = msignature.mparameters[i].mtype
1066 var node = nsig.n_params[i]
1067 if not modelbuilder.check_sametype(node, mmodule, mclassdef.bound_mtype, myt, prt) then
1068 modelbuilder.error(node, "Redef Error: expected `{prt}` for parameter `{mysignature.mparameters[i].name}'; got `{myt}`.")
1069 mpropdef.msignature = null
1070 mpropdef.is_broken = true
1071 end
1072 end
1073 end
1074 if precursor_ret_type != null then
1075 var node: nullable ANode = null
1076 if nsig != null then node = nsig.n_type
1077 if node == null then node = self
1078 if ret_type == null then
1079 # Inherit the return type
1080 ret_type = precursor_ret_type
1081 else if not modelbuilder.check_subtype(node, mmodule, mclassdef.bound_mtype, ret_type, precursor_ret_type) then
1082 modelbuilder.error(node, "Redef Error: expected `{precursor_ret_type}` for return type; got `{ret_type}`.")
1083 mpropdef.msignature = null
1084 mpropdef.is_broken = true
1085 end
1086 end
1087 end
1088
1089 if nsig != null then
1090 # Check parameters visibility
1091 for i in [0..mysignature.arity[ do
1092 var nt = nsig.n_params[i].n_type
1093 if nt != null then modelbuilder.check_visibility(nt, nt.mtype.as(not null), mpropdef)
1094 end
1095 var nt = nsig.n_type
1096 if nt != null then modelbuilder.check_visibility(nt, nt.mtype.as(not null), mpropdef)
1097 end
1098 check_repeated_types(modelbuilder)
1099 end
1100
1101 # For parameters, type is always useless in a redef.
1102 # For return type, type is useless if not covariant with introduction.
1103 redef fun check_repeated_types(modelbuilder) do
1104 var mpropdef = self.mpropdef
1105 if mpropdef == null then return
1106 if mpropdef.is_intro or n_signature == null then return
1107 # check params
1108 for param in n_signature.n_params do
1109 if param.n_type != null then
1110 modelbuilder.advice(param.n_type, "useless-signature", "Warning: useless type repetition on parameter `{param.n_id.text}` for redefined method `{mpropdef.name}`")
1111 end
1112 end
1113 # get intro
1114 var intro = mpropdef.mproperty.intro
1115 var n_intro = modelbuilder.mpropdef2npropdef.get_or_null(intro)
1116 if n_intro == null or not n_intro isa AMethPropdef then return
1117 # check return type
1118 var ret_type = n_signature.ret_type
1119 if ret_type != null and ret_type == n_intro.n_signature.ret_type then
1120 modelbuilder.advice(n_signature.n_type, "useless-signature", "Warning: useless return type repetition for redefined method `{mpropdef.name}`")
1121 end
1122 end
1123 end
1124
1125 redef class AMethid
1126 # Is a return required?
1127 #
1128 # * True for operators and brackets.
1129 # * False for id and assignment.
1130 fun return_is_mandatory: Bool do return true
1131
1132 # Can the last parameter be special like a vararg?
1133 #
1134 # * False for operators: the last one is in fact the only one.
1135 # * False for assignments: it is the right part of the assignment.
1136 # * True for ids and brackets.
1137 fun accept_special_last_parameter: Bool do return false
1138
1139 # The minimum required number of parameters.
1140 #
1141 # * 1 for binary operators
1142 # * 1 for brackets
1143 # * 1 for assignments
1144 # * 2 for bracket assignments
1145 # * 0 for ids
1146 fun min_arity: Int do return 1
1147
1148 # Is the `self` a binary operator?
1149 fun is_binary: Bool do return true
1150 end
1151
1152 redef class AIdMethid
1153 redef fun return_is_mandatory do return false
1154 redef fun accept_special_last_parameter do return true
1155 redef fun min_arity do return 0
1156 redef fun is_binary do return false
1157 end
1158
1159 redef class ABraMethid
1160 redef fun accept_special_last_parameter do return true
1161 redef fun is_binary do return false
1162 end
1163
1164 redef class ABraassignMethid
1165 redef fun return_is_mandatory do return false
1166 redef fun min_arity do return 2
1167 redef fun is_binary do return false
1168 end
1169
1170 redef class AAssignMethid
1171 redef fun return_is_mandatory do return false
1172 redef fun is_binary do return false
1173 end
1174
1175 redef class AAttrPropdef
1176 redef type MPROPDEF: MAttributeDef
1177
1178 # The static type of the property (declared, inferred or inherited)
1179 # This attribute is also used to check if the property was analyzed and is valid.
1180 var mtype: nullable MType
1181
1182 # Is the node tagged `noinit`?
1183 var noinit = false
1184
1185 # Is the node tagged lazy?
1186 var is_lazy = false
1187
1188 # Is the node tagged optional?
1189 var is_optional = false
1190
1191 # Does the node have a default value?
1192 # Could be through `n_expr`, `n_block` or `is_lazy`
1193 var has_value = false
1194
1195 # The name of the attribute
1196 # Note: The name of the attribute is in reality the name of the mreadpropdef
1197 var name: String = n_id2.text is lazy
1198
1199 # The guard associated to a lazy attribute.
1200 # Because some engines does not have a working `isset`,
1201 # this additional attribute is used to guard the lazy initialization.
1202 # TODO: to remove once isset is correctly implemented
1203 var mlazypropdef: nullable MAttributeDef
1204
1205 # The associated getter (read accessor) if any
1206 var mreadpropdef: nullable MMethodDef is writable
1207 # The associated setter (write accessor) if any
1208 var mwritepropdef: nullable MMethodDef is writable
1209
1210 redef fun build_property(modelbuilder, mclassdef)
1211 do
1212 var mclass = mclassdef.mclass
1213
1214 var atabstract = self.get_single_annotation("abstract", modelbuilder)
1215
1216 if atabstract == null then build_attribute_property(modelbuilder, mclassdef)
1217
1218 # Construction of the read property. If it's not correctly built just return.
1219 if not build_read_property(modelbuilder, mclassdef) then return
1220
1221 if atabstract != null then mreadpropdef.is_abstract = true
1222
1223 has_value = n_expr != null or n_block != null
1224
1225 if atabstract != null and has_value then
1226 modelbuilder.error(atabstract, "Error: `abstract` attributes cannot have an initial value.")
1227 return
1228 end
1229
1230 var atnoinit = self.get_single_annotation("noinit", modelbuilder)
1231 if atnoinit == null then atnoinit = self.get_single_annotation("noautoinit", modelbuilder)
1232 if atnoinit != null then
1233 noinit = true
1234 if has_value then
1235 modelbuilder.error(atnoinit, "Error: `noautoinit` attributes cannot have an initial value.")
1236 return
1237 end
1238 if atabstract != null then
1239 modelbuilder.warning(atnoinit, "useless-noautoinit", "Warning: superfluous `noautoinit` on abstract attribute.")
1240 end
1241 end
1242
1243 # Construction of the read property. If it's not correctly built just return.
1244 if not build_lazy_property(modelbuilder, mclassdef) then return
1245
1246 var atoptional = self.get_single_annotation("optional", modelbuilder)
1247 if atoptional != null then
1248 if not has_value then
1249 modelbuilder.error(atoptional, "Error: `optional` attributes need a default value.")
1250 end
1251 is_optional = true
1252 end
1253
1254 var atreadonly = self.get_single_annotation("readonly", modelbuilder)
1255 if atreadonly != null then
1256 if not has_value then
1257 modelbuilder.error(atreadonly, "Error: `readonly` attributes need a value.")
1258 end
1259 # No setter, so just leave
1260 return
1261 end
1262
1263 if not mclassdef.is_intro and not has_value and not noinit then
1264 modelbuilder.advice(self, "attr-in-refinement", "Warning: attributes in refinement need a value or `noautoinit`.")
1265 end
1266
1267 # Construction of the read property. If it's not correctly built just return.
1268 if not build_write_property(modelbuilder, mclassdef, false) then return
1269
1270 if atabstract != null then mwritepropdef.is_abstract = true
1271
1272 var atautoinit = self.get_single_annotation("autoinit", modelbuilder)
1273 if atautoinit != null then
1274 if has_value then
1275 modelbuilder.error(atautoinit, "Error: `autoinit` attributes cannot have an initial value.")
1276 else if not mwritepropdef.is_intro then
1277 modelbuilder.error(atautoinit, "Error: `autoinit` attributes cannot be set on redefinitions.")
1278 else if not mclassdef.is_intro then
1279 modelbuilder.error(atautoinit, "Error: `autoinit` attributes cannot be used in class refinements.")
1280 else if atabstract == null then
1281 modelbuilder.warning(atautoinit, "useless-autoinit", "Warning: superfluous `autoinit` on attribute.")
1282 end
1283 else if atabstract != null then
1284 # By default, abstract attribute are not autoinit
1285 noinit = true
1286 end
1287 end
1288
1289 # Build the attribute property
1290 fun build_attribute_property(modelbuilder: ModelBuilder, mclassdef: MClassDef)
1291 do
1292 var mclass = mclassdef.mclass
1293 var attribute_name = "_" + name
1294
1295 if not mclass.kind.need_init then
1296 modelbuilder.error(self, "Error: attempt to define attribute `{name}` in the {mclass.kind} `{mclass}`.")
1297 end
1298 var mprop = new MAttribute(mclassdef, "_" + name, self.location, private_visibility)
1299 var mpropdef = new MAttributeDef(mclassdef, mprop, self.location)
1300 self.mpropdef = mpropdef
1301 modelbuilder.mpropdef2npropdef[mpropdef] = self
1302 end
1303
1304 # Build the read method property to get the value of the attribute
1305 # Return `true` if the property was correctly created else return `false`.
1306 # Warning the signature of the property is not set. This step is done by `build_signature`.
1307 fun build_read_property(modelbuilder: ModelBuilder, mclassdef: MClassDef): Bool
1308 do
1309 var mclass = mclassdef.mclass
1310
1311 var readname = name
1312 var mreadprop = modelbuilder.try_get_mproperty_by_name(self, mclassdef, readname).as(nullable MMethod)
1313 if mreadprop == null then
1314 var mvisibility = new_property_visibility(modelbuilder, mclassdef, self.n_visibility)
1315 mreadprop = new MMethod(mclassdef, readname, self.location, mvisibility)
1316 if not self.check_redef_keyword(modelbuilder, mclassdef, n_kwredef, false, mreadprop) then
1317 mreadprop.is_broken = true
1318 return false
1319 end
1320 else
1321 if mreadprop.is_broken then return false
1322 if not self.check_redef_keyword(modelbuilder, mclassdef, n_kwredef, true, mreadprop) then return false
1323 check_redef_property_visibility(modelbuilder, self.n_visibility, mreadprop)
1324 end
1325 mclassdef.mprop2npropdef[mreadprop] = self
1326
1327 var attr_mpropdef = mpropdef
1328 if attr_mpropdef != null then
1329 mreadprop.getter_for = attr_mpropdef.mproperty
1330 attr_mpropdef.mproperty.getter = mreadprop
1331 end
1332
1333 var mreadpropdef = new MMethodDef(mclassdef, mreadprop, self.location)
1334 self.mreadpropdef = mreadpropdef
1335 modelbuilder.mpropdef2npropdef[mreadpropdef] = self
1336 set_doc(mreadpropdef, modelbuilder)
1337 if mpropdef != null then mpropdef.mdoc = mreadpropdef.mdoc
1338
1339 return true
1340 end
1341
1342 # Build the write method property to set the attribute value
1343 # Return `true` if the property was correctly created else return `false`.
1344 # Warning the signature of the property is not set.
1345 fun build_write_property(modelbuilder: ModelBuilder, mclassdef: MClassDef, is_same_visibility: Bool): Bool
1346 do
1347 var mclass = mclassdef.mclass
1348
1349 var writename = name + "="
1350 var atwritable = self.get_single_annotation("writable", modelbuilder)
1351 if atwritable != null then
1352 if not atwritable.n_args.is_empty then
1353 writename = atwritable.arg_as_id(modelbuilder) or else writename
1354 end
1355 end
1356 var mwriteprop = modelbuilder.try_get_mproperty_by_name(self, mclassdef, writename).as(nullable MMethod)
1357 var nwkwredef: nullable Token = null
1358 if atwritable != null then nwkwredef = atwritable.n_kwredef
1359 if mwriteprop == null then
1360 var mvisibility
1361 if atwritable != null then
1362 mvisibility = new_property_visibility(modelbuilder, mclassdef, atwritable.n_visibility)
1363 else
1364 mvisibility = mreadpropdef.mproperty.visibility
1365 # By default, use protected visibility at most
1366 if mvisibility > protected_visibility and not is_same_visibility then mvisibility = protected_visibility
1367 end
1368 mwriteprop = new MMethod(mclassdef, writename, self.location, mvisibility)
1369 if not self.check_redef_keyword(modelbuilder, mclassdef, nwkwredef, false, mwriteprop) then
1370 mwriteprop.is_broken = true
1371 return false
1372 end
1373 mwriteprop.deprecation = mreadpropdef.mproperty.deprecation
1374 else
1375 if mwriteprop.is_broken then return false
1376 if not self.check_redef_keyword(modelbuilder, mclassdef, nwkwredef or else n_kwredef, true, mwriteprop) then return false
1377 if atwritable != null then
1378 check_redef_property_visibility(modelbuilder, atwritable.n_visibility, mwriteprop)
1379 end
1380 end
1381 mclassdef.mprop2npropdef[mwriteprop] = self
1382
1383 var attr_mpropdef = mpropdef
1384 if attr_mpropdef != null then
1385 mwriteprop.setter_for = attr_mpropdef.mproperty
1386 attr_mpropdef.mproperty.setter = mwriteprop
1387 end
1388
1389 var mwritepropdef = new MMethodDef(mclassdef, mwriteprop, self.location)
1390 self.mwritepropdef = mwritepropdef
1391 modelbuilder.mpropdef2npropdef[mwritepropdef] = self
1392 mwritepropdef.mdoc = mreadpropdef.mdoc
1393
1394 return true
1395 end
1396
1397 # Build the lazy attribute property
1398 # Return `true` if the property was correctly created else return `false`.
1399 fun build_lazy_property(modelbuilder: ModelBuilder, mclassdef: MClassDef): Bool
1400 do
1401 var mclass = mclassdef.mclass
1402
1403 var atlazy = self.get_single_annotation("lazy", modelbuilder)
1404 var atlateinit = self.get_single_annotation("lateinit", modelbuilder)
1405 if atlazy != null or atlateinit != null then
1406 if atlazy != null and atlateinit != null then
1407 modelbuilder.error(atlazy, "Error: `lazy` incompatible with `lateinit`.")
1408 return false
1409 end
1410 if not has_value then
1411 if atlazy != null then
1412 modelbuilder.error(atlazy, "Error: `lazy` attributes need a value.")
1413 else if atlateinit != null then
1414 modelbuilder.error(atlateinit, "Error: `lateinit` attributes need a value.")
1415 end
1416 has_value = true
1417 return false
1418 end
1419 is_lazy = true
1420 var mlazyprop = new MAttribute(mclassdef, "lazy _" + name, self.location, none_visibility)
1421 mlazyprop.is_fictive = true
1422 var mlazypropdef = new MAttributeDef(mclassdef, mlazyprop, self.location)
1423 mlazypropdef.is_fictive = true
1424 self.mlazypropdef = mlazypropdef
1425 end
1426 return true
1427 end
1428
1429 redef fun build_signature(modelbuilder)
1430 do
1431 var mreadpropdef = self.mreadpropdef
1432 var mpropdef = self.mpropdef
1433 if mreadpropdef == null then return # Error thus skipped
1434 var mclassdef = mreadpropdef.mclassdef
1435 var mmodule = mclassdef.mmodule
1436 var mtype: nullable MType = null
1437
1438
1439 var ntype = self.n_type
1440 if ntype != null then
1441 mtype = modelbuilder.resolve_mtype_unchecked(mclassdef, ntype, true)
1442 if mtype == null then return
1443 end
1444
1445 var inherited_type: nullable MType = null
1446 # Inherit the type from the getter (usually an abstract getter)
1447 if not mreadpropdef.is_intro then
1448 var msignature = mreadpropdef.mproperty.intro.msignature
1449 if msignature == null then return # Error, thus skipped
1450 inherited_type = msignature.return_mtype
1451 if inherited_type != null then
1452 # The inherited type is adapted to use the local formal types, if any.
1453 inherited_type = inherited_type.resolve_for(mclassdef.mclass.mclass_type, mclassdef.bound_mtype, mmodule, false)
1454 if mtype == null then mtype = inherited_type
1455 end
1456 end
1457
1458 var nexpr = self.n_expr
1459 if mtype == null then
1460 if nexpr != null then
1461 mtype = infer_static_type(modelbuilder, nexpr, mclassdef, mmodule, mreadpropdef)
1462 if mtype == null then return
1463 end
1464 else if ntype != null and inherited_type == mtype then
1465 if nexpr isa ANewExpr then
1466 var xmtype = modelbuilder.resolve_mtype_unchecked(mclassdef, nexpr.n_type, true)
1467 if xmtype == mtype then
1468 modelbuilder.advice(ntype, "useless-type", "Warning: useless type definition")
1469 end
1470 end
1471 end
1472
1473 if mtype == null then
1474 modelbuilder.error(self, "Error: untyped attribute `{mreadpropdef}`.")
1475 return
1476 end
1477
1478 self.mtype = mtype
1479
1480 if mpropdef != null then
1481 mpropdef.static_mtype = mtype
1482 end
1483
1484 build_read_signature
1485
1486 if self.mwritepropdef != null then build_write_signature
1487
1488 var mlazypropdef = self.mlazypropdef
1489 if mlazypropdef != null then
1490 mlazypropdef.static_mtype = mmodule.bool_type
1491 end
1492 check_repeated_types(modelbuilder)
1493 end
1494
1495 # Build the read method signature
1496 # `except`: mreadpropdef != null
1497 # `expect`: mtype != null
1498 fun build_read_signature
1499 is
1500 expect(mreadpropdef != null and mtype != null)
1501 do
1502 var msignature = new MSignature(new Array[MParameter], mtype)
1503 mreadpropdef.msignature = msignature
1504 end
1505
1506 # Build the write method signature
1507 # `except`: mwritepropdef != null
1508 # `expect`: mtype != null
1509 fun build_write_signature
1510 is
1511 expect(mwritepropdef != null and mtype != null)
1512 do
1513 var mwritetype = mtype.as(not null)
1514 if is_optional then
1515 mwritetype = mwritetype.as_nullable
1516 end
1517 var mparameter = new MParameter(name, mwritetype, false)
1518 var msignature = new MSignature([mparameter], null)
1519 mwritepropdef.msignature = msignature
1520 end
1521
1522 # Detect the static type from the value assigned to the attribute `self`
1523 #
1524 # Return the static type if it can be safely inferred.
1525 private fun infer_static_type(modelbuilder: ModelBuilder, nexpr: AExpr,
1526 mclassdef: MClassDef, mmodule: MModule, mreadpropdef: MPropDef): nullable MType
1527 do
1528 var mtype = null
1529 if nexpr isa ANewExpr then
1530 mtype = modelbuilder.resolve_mtype_unchecked(mclassdef, nexpr.n_type, true)
1531 else if nexpr isa AAsCastExpr then
1532 mtype = modelbuilder.resolve_mtype_unchecked(mclassdef, nexpr.n_type, true)
1533 else if nexpr isa AIntegerExpr then
1534 var cla: nullable MClass = null
1535 if nexpr.value isa Int then
1536 cla = modelbuilder.try_get_mclass_by_name(nexpr, mmodule, "Int")
1537 else if nexpr.value isa Byte then
1538 cla = modelbuilder.try_get_mclass_by_name(nexpr, mmodule, "Byte")
1539 else if nexpr.value isa Int8 then
1540 cla = modelbuilder.try_get_mclass_by_name(nexpr, mmodule, "Int8")
1541 else if nexpr.value isa Int16 then
1542 cla = modelbuilder.try_get_mclass_by_name(nexpr, mmodule, "Int16")
1543 else if nexpr.value isa UInt16 then
1544 cla = modelbuilder.try_get_mclass_by_name(nexpr, mmodule, "UInt16")
1545 else if nexpr.value isa Int32 then
1546 cla = modelbuilder.try_get_mclass_by_name(nexpr, mmodule, "Int32")
1547 else if nexpr.value isa UInt32 then
1548 cla = modelbuilder.try_get_mclass_by_name(nexpr, mmodule, "UInt32")
1549 else
1550 # Should not happen, and should be updated as new types are added
1551 abort
1552 end
1553 if cla != null then mtype = cla.mclass_type
1554 else if nexpr isa AFloatExpr then
1555 var cla = modelbuilder.try_get_mclass_by_name(nexpr, mmodule, "Float")
1556 if cla != null then mtype = cla.mclass_type
1557 else if nexpr isa ACharExpr then
1558 var cla: nullable MClass
1559 if nexpr.is_code_point then
1560 cla = modelbuilder.try_get_mclass_by_name(nexpr, mmodule, "Int")
1561 else
1562 cla = modelbuilder.try_get_mclass_by_name(nexpr, mmodule, "Char")
1563 end
1564 if cla != null then mtype = cla.mclass_type
1565 else if nexpr isa ABoolExpr then
1566 var cla = modelbuilder.try_get_mclass_by_name(nexpr, mmodule, "Bool")
1567 if cla != null then mtype = cla.mclass_type
1568 else if nexpr isa ASuperstringExpr then
1569 var cla = modelbuilder.try_get_mclass_by_name(nexpr, mmodule, "String")
1570 if cla != null then mtype = cla.mclass_type
1571 else if nexpr isa AStringFormExpr then
1572 var cla: nullable MClass
1573 if nexpr.is_bytestring then
1574 cla = modelbuilder.try_get_mclass_by_name(nexpr, mmodule, "Bytes")
1575 else if nexpr.is_re then
1576 cla = modelbuilder.try_get_mclass_by_name(nexpr, mmodule, "Regex")
1577 else if nexpr.is_string then
1578 cla = modelbuilder.try_get_mclass_by_name(nexpr, mmodule, "String")
1579 else
1580 abort
1581 end
1582 if cla != null then mtype = cla.mclass_type
1583 else if nexpr isa AArrayExpr and nexpr.n_type == null and nexpr.n_exprs.not_empty then
1584 # Non-empty arrays without an explicit type
1585
1586 var item_mtypes = new Set[MType]
1587 var fails = false
1588 for node in nexpr.n_exprs do
1589 var item_mtype = infer_static_type(modelbuilder, node, mclassdef, mmodule, mreadpropdef)
1590 if item_mtype == null then
1591 fails = true
1592 else
1593 item_mtypes.add item_mtype
1594 end
1595 end
1596
1597 if fails then return null # Failed to infer some types
1598
1599 if item_mtypes.length > 1 then
1600 modelbuilder.error(self, "Type Error: ambiguous array type {item_mtypes.join(" ")}")
1601 end
1602
1603 mtype = mmodule.array_type(item_mtypes.first)
1604 else if nexpr isa AUminusExpr and (nexpr.n_expr isa AIntegerExpr or nexpr.n_expr isa AFloatExpr) then
1605 # The Int and Float unary - is defined in `kernel`, so this may
1606 # result in an invalid behavior when using a custom kernel.
1607 # A workaround is to declare the attribute static type.
1608 # This is still very useful, especially to novice programmers.
1609 mtype = infer_static_type(modelbuilder, nexpr.n_expr, mclassdef, mmodule, mreadpropdef)
1610 else if nexpr isa AOnceExpr then
1611 mtype = infer_static_type(modelbuilder, nexpr.n_expr, mclassdef, mmodule, mreadpropdef)
1612 else
1613 modelbuilder.error(self, "Error: untyped attribute `{mreadpropdef}`. Implicit typing allowed only for literals and new.")
1614 end
1615 return mtype
1616 end
1617
1618 redef fun check_signature(modelbuilder)
1619 do
1620 var mpropdef = self.mpropdef
1621 if mpropdef == null then return # Error thus skipped
1622 var ntype = self.n_type
1623 var mtype = self.mtype
1624 if mtype == null then return # Error thus skipped
1625
1626 var mclassdef = mpropdef.mclassdef
1627 var mmodule = mclassdef.mmodule
1628
1629 # Check types
1630 if ntype != null then
1631 if modelbuilder.resolve_mtype(mclassdef, ntype) == null then return
1632 end
1633 var nexpr = n_expr
1634 if nexpr isa ANewExpr then
1635 if modelbuilder.resolve_mtype(mclassdef, nexpr.n_type) == null then return
1636 end
1637
1638 # Lookup for signature in the precursor
1639 # FIXME all precursors should be considered
1640 if not mpropdef.is_intro then
1641 var precursor_type = mpropdef.mproperty.intro.static_mtype
1642 if precursor_type == null then return
1643
1644 if mtype != precursor_type then
1645 modelbuilder.error(ntype.as(not null), "Redef Error: expected `{precursor_type}` type as a bound; got `{mtype}`.")
1646 return
1647 end
1648 end
1649
1650 # Check getter and setter
1651 var meth = self.mreadpropdef
1652 if meth != null then
1653 self.check_method_signature(modelbuilder, meth)
1654 var node: nullable ANode = ntype
1655 if node == null then node = self
1656 modelbuilder.check_visibility(node, mtype, meth)
1657 end
1658 meth = self.mwritepropdef
1659 if meth != null then
1660 self.check_method_signature(modelbuilder, meth)
1661 var node: nullable ANode = ntype
1662 if node == null then node = self
1663 modelbuilder.check_visibility(node, mtype, meth)
1664 end
1665 end
1666
1667 private fun check_method_signature(modelbuilder: ModelBuilder, mpropdef: MMethodDef)
1668 do
1669 var mclassdef = mpropdef.mclassdef
1670 var mmodule = mclassdef.mmodule
1671 var nsig = self.n_type
1672 var mysignature = mpropdef.msignature
1673 if mysignature == null then return # Error thus skiped
1674
1675 # Lookup for signature in the precursor
1676 # FIXME all precursors should be considered
1677 if not mpropdef.is_intro then
1678 var msignature = mpropdef.mproperty.intro.msignature
1679 if msignature == null then return
1680
1681 if mysignature.arity != msignature.arity then
1682 var node: ANode
1683 if nsig != null then node = nsig else node = self
1684 modelbuilder.error(node, "Redef Error: expected {msignature.arity} parameter(s) for `{mpropdef.mproperty.name}{msignature}`; got {mysignature.arity}. See introduction at `{mpropdef.mproperty.full_name}`.")
1685 return
1686 end
1687 var precursor_ret_type = msignature.return_mtype
1688 var ret_type = mysignature.return_mtype
1689 if ret_type != null and precursor_ret_type == null then
1690 var node: ANode
1691 if nsig != null then node = nsig else node = self
1692 modelbuilder.error(node, "Redef Error: `{mpropdef.mproperty}` is a procedure, not a function.")
1693 return
1694 end
1695
1696 if mysignature.arity > 0 then
1697 # Check parameters types
1698 for i in [0..mysignature.arity[ do
1699 var myt = mysignature.mparameters[i].mtype
1700 var prt = msignature.mparameters[i].mtype
1701 var node: ANode
1702 if nsig != null then node = nsig else node = self
1703 if not modelbuilder.check_sametype(node, mmodule, mclassdef.bound_mtype, myt, prt) then
1704 modelbuilder.error(node, "Redef Error: expected `{prt}` type for parameter `{mysignature.mparameters[i].name}'; got `{myt}`.")
1705 end
1706 end
1707 end
1708 if precursor_ret_type != null then
1709 var node: ANode
1710 if nsig != null then node = nsig else node = self
1711 if ret_type == null then
1712 # Inherit the return type
1713 ret_type = precursor_ret_type
1714 else if not modelbuilder.check_subtype(node, mmodule, mclassdef.bound_mtype, ret_type, precursor_ret_type) then
1715 modelbuilder.error(node, "Redef Error: expected `{precursor_ret_type}` return type; got `{ret_type}`.")
1716 end
1717 end
1718 end
1719 end
1720
1721 # Type is useless if the attribute type is the same thant the intro.
1722 redef fun check_repeated_types(modelbuilder) do
1723 var mreadpropdef = self.mreadpropdef
1724 if mreadpropdef == null then return
1725 if mreadpropdef.is_intro or n_type == null then return
1726 # get intro
1727 var intro = mreadpropdef.mproperty.intro
1728 var n_intro = modelbuilder.mpropdef2npropdef.get_or_null(intro)
1729 if n_intro == null then return
1730 # get intro type
1731 var ntype = null
1732 if n_intro isa AMethPropdef then
1733 ntype = n_intro.n_signature.ret_type
1734 else if n_intro isa AAttrPropdef and n_intro.n_type != null then
1735 ntype = n_intro.n_type.mtype
1736 end
1737 # check
1738 if ntype == null or ntype != n_type.mtype or mpropdef == null then return
1739 modelbuilder.advice(n_type, "useless-signature", "Warning: useless type repetition on redefined attribute `{mpropdef.name}`")
1740 end
1741 end
1742
1743 redef class ATypePropdef
1744 redef type MPROPDEF: MVirtualTypeDef
1745
1746 redef fun build_property(modelbuilder, mclassdef)
1747 do
1748 var name = self.n_qid.n_id.text
1749 var mprop = modelbuilder.try_get_mproperty_by_name(self.n_qid, mclassdef, name)
1750 if mprop == null then
1751 var mvisibility = new_property_visibility(modelbuilder, mclassdef, self.n_visibility)
1752 mprop = new MVirtualTypeProp(mclassdef, name, self.location, mvisibility)
1753 for c in name.chars do if c >= 'a' and c<= 'z' then
1754 modelbuilder.warning(n_qid, "bad-type-name", "Warning: lowercase in the virtual type `{name}`.")
1755 break
1756 end
1757 else
1758 if mprop.is_broken then return
1759 assert mprop isa MVirtualTypeProp
1760 check_redef_property_visibility(modelbuilder, self.n_visibility, mprop)
1761 end
1762
1763 var mpropdef = new MVirtualTypeDef(mclassdef, mprop, self.location)
1764 self.mpropdef = mpropdef
1765 if mpropdef.is_intro then
1766 modelbuilder.toolcontext.info("{mpropdef} introduces new type {mprop.full_name}", 4)
1767 else
1768 modelbuilder.toolcontext.info("{mpropdef} redefines type {mprop.full_name}", 4)
1769 end
1770 if not self.check_redef_keyword(modelbuilder, mclassdef, self.n_kwredef, not mpropdef.is_intro, mprop) then
1771 mpropdef.is_broken =true
1772 end
1773 mclassdef.mprop2npropdef[mprop] = self
1774 modelbuilder.mpropdef2npropdef[mpropdef] = self
1775 set_doc(mpropdef, modelbuilder)
1776
1777 var atfixed = get_single_annotation("fixed", modelbuilder)
1778 if atfixed != null then
1779 mpropdef.is_fixed = true
1780 end
1781 end
1782
1783 redef fun build_signature(modelbuilder)
1784 do
1785 var mpropdef = self.mpropdef
1786 if mpropdef == null then return # Error thus skipped
1787 var mclassdef = mpropdef.mclassdef
1788 var mtype: nullable MType = null
1789
1790 var ntype = self.n_type
1791 mtype = modelbuilder.resolve_mtype_unchecked(mclassdef, ntype, true)
1792 if mtype == null then return
1793
1794 mpropdef.bound = mtype
1795 # print "{mpropdef}: {mtype}"
1796 end
1797
1798 redef fun check_signature(modelbuilder)
1799 do
1800 var mpropdef = self.mpropdef
1801 if mpropdef == null then return # Error thus skipped
1802
1803 var bound = mpropdef.bound
1804 if bound == null then return # Error thus skipped
1805
1806 modelbuilder.check_visibility(n_type, bound, mpropdef)
1807
1808 var mclassdef = mpropdef.mclassdef
1809 var mmodule = mclassdef.mmodule
1810 var anchor = mclassdef.bound_mtype
1811
1812 var ntype = self.n_type
1813 if modelbuilder.resolve_mtype(mclassdef, ntype) == null then
1814 mpropdef.bound = null
1815 return
1816 end
1817
1818 # Check redefinitions
1819 for p in mpropdef.mproperty.lookup_super_definitions(mmodule, anchor) do
1820 var supbound = p.bound
1821 if supbound == null or supbound isa MBottomType or p.is_broken then break # broken super bound, skip error
1822 if p.is_fixed then
1823 modelbuilder.error(self, "Redef Error: virtual type `{mpropdef.mproperty}` is fixed in super-class `{p.mclassdef.mclass}`.")
1824 break
1825 end
1826 if p.mclassdef.mclass == mclassdef.mclass then
1827 modelbuilder.error(n_type, "Redef Error: a virtual type cannot be refined.")
1828 break
1829 end
1830 if not modelbuilder.check_subtype(n_type, mmodule, anchor, bound, supbound) then
1831 modelbuilder.error(n_type, "Redef Error: expected `{supbound}` bound type; got `{bound}`.")
1832 break
1833 end
1834 end
1835 end
1836 end