syntax: Update check_conform_multiexpr with nullables
[nit.git] / src / syntax / syntax_base.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2008 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 # Common syntax structures for syntax analysis of NIT AST.
18 package syntax_base
19
20 import parser
21 import mmloader
22
23 # Concrete NIT source module
24 class MMSrcModule
25 special MMModule
26 # The related AST node
27 readable attr _node: AModule
28
29 # Concrete NIT source local classs by name
30 readable attr _src_local_classes: Map[Symbol, MMSrcLocalClass]
31
32 init(c: MMContext, source: AModule, dir: MMDirectory, name: Symbol, filename: String)
33 do
34 super(name, dir, c, filename)
35 _node = source
36 _src_local_classes = new HashMap[Symbol, MMSrcLocalClass]
37 end
38 end
39
40 redef class MMGlobalClass
41 # Check that a module can access a class
42 meth check_visibility(v: AbsSyntaxVisitor, n: PNode, cm: MMSrcModule): Bool do
43 var pm = intro.module
44 assert pm isa MMSrcModule
45 var vpm = cm.visibility_for(pm)
46 if vpm == 3 then
47 return true
48 else if vpm == 0 then
49 v.error(n, "Visibility error: Class {self} comes from the hidden module {cm}.") # TODO: should not occur
50 return false
51 else if visibility_level >= 3 then
52 v.error(n, "Visibility error: Class {self} is private.")
53 return false
54 end
55 return true
56 end
57 end
58
59 # Concrete NIT source local classes
60 class MMSrcLocalClass
61 special MMConcreteClass
62 # The related AST nodes
63 readable attr _nodes: Array[PClassdef]
64
65 # Concrete NIT source generic formal parameter by name
66 readable writable attr _formal_dict: Map[Symbol, MMTypeFormalParameter]
67
68 # Concrete NIT source properties by name
69 readable attr _src_local_properties: Map[Symbol, MMLocalProperty]
70
71 init(mod: MMSrcModule, n: Symbol, cla: PClassdef, a: Int)
72 do
73 super(mod, n, a)
74 _nodes = [cla]
75 _src_local_properties = new HashMap[Symbol, MMLocalProperty]
76 end
77 end
78
79 redef class MMGlobalProperty
80 # Check that a module can access a property
81 meth check_visibility(v: AbsSyntaxVisitor, n: PNode, cm: MMSrcModule, allows_protected: Bool): Bool do
82 var pm = local_class.module
83 assert pm isa MMSrcModule
84 var vpm = cm.visibility_for(pm)
85 if vpm == 3 then
86 return true
87 else if vpm == 0 then
88 # TODO: should not occurs
89 v.error(n, "Visibility error: Property {self} comes from the hidden module {cm}.")
90 return false
91 else if visibility_level >= 3 then
92 v.error(n, "Visibility error: Property {self} is private.")
93 return false
94 else if visibility_level >= 2 and not allows_protected then
95 v.error(n, "Visibility error: Property {self} is protected and can only acceded by self.")
96 return false
97 end
98 return true
99 end
100 end
101
102 redef class MMLocalProperty
103 # The attached node (if any)
104 meth node: PNode do return null
105
106 # Is the concrete method defined as init
107 meth is_init: Bool do return false
108 end
109
110 # Concrete NIT source attribute
111 class MMSrcAttribute
112 special MMAttribute
113 redef readable attr _node: AAttrPropdef
114 init(name: Symbol, cla: MMLocalClass, n: AAttrPropdef)
115 do
116 super(name, cla)
117 _node = n
118 end
119 end
120
121 # Concrete NIT source method
122 class MMSrcMethod
123 special MMMethod
124 end
125
126 # Concrete NIT source method for an automatic accesor
127 class MMAttrImplementationMethod
128 special MMSrcMethod
129 redef readable attr _node: AAttrPropdef
130 init(name: Symbol, cla: MMLocalClass, n: AAttrPropdef)
131 do
132 super(name, cla)
133 _node = n
134 end
135 end
136
137 # Concrete NIT source method for an automatic read accesor
138 class MMReadImplementationMethod
139 special MMAttrImplementationMethod
140 init(name: Symbol, cla: MMLocalClass, n: AAttrPropdef)
141 do
142 super(name, cla, n)
143 end
144 end
145
146 # Concrete NIT source method for an automatic write accesor
147 class MMWriteImplementationMethod
148 special MMAttrImplementationMethod
149 init(name: Symbol, cla: MMLocalClass, n: AAttrPropdef)
150 do
151 super(name, cla, n)
152 end
153 end
154
155 # Concrete NIT source method for an explicit method
156 class MMMethSrcMethod
157 special MMSrcMethod
158 redef meth is_init do return _node isa AConcreteInitPropdef
159 redef readable attr _node: AMethPropdef
160 init(name: Symbol, cla: MMLocalClass, n: AMethPropdef)
161 do
162 super(name, cla)
163 _node = n
164 end
165 end
166
167 # Concrete NIT source virtual type
168 class MMSrcTypeProperty
169 special MMLocalProperty
170 special MMTypeProperty
171 redef readable attr _node: ATypePropdef
172 init(name: Symbol, cla: MMLocalClass, n: ATypePropdef)
173 do
174 super(name, cla)
175 _node = n
176 end
177 end
178
179 # Concrete NIT implicit constructor
180 class MMImplicitInit
181 special MMMethSrcMethod
182 redef meth is_init do return true
183 readable attr _unassigned_attributes: Array[MMSrcAttribute]
184 readable attr _super_inits: Array[MMLocalProperty]
185 init(cla: MMLocalClass, unassigned_attributes: Array[MMSrcAttribute], super_inits: Array[MMLocalProperty])
186 do
187 super(once "init".to_symbol, cla, null)
188 _unassigned_attributes = unassigned_attributes
189 _super_inits = super_inits
190 end
191 end
192
193 # Local variables
194 abstract class Variable
195 # Name of the variable
196 readable attr _name: Symbol
197
198 # Declaration AST node
199 readable attr _decl: PNode
200
201 # Static type
202 readable writable attr _stype: MMType
203
204 redef meth to_s do return _name.to_s
205
206 meth kind: String is abstract
207
208 init(n: Symbol, d: PNode)
209 do
210 #assert n != null
211 #assert d != null
212 _name = n
213 _decl = d
214 end
215 end
216
217 # Variable declared with 'var'
218 class VarVariable
219 special Variable
220 redef meth kind do return once "variable"
221 init(n: Symbol, d: PNode) do super
222 end
223
224 # Parameter of method (declared in signature)
225 class ParamVariable
226 special Variable
227 redef meth kind do return once "parameter"
228 init(n: Symbol, d: PNode) do super
229 end
230
231 # Automatic variable (like in the 'for' statement)
232 class AutoVariable
233 special Variable
234 redef meth kind do return once "automatic variable"
235 init(n: Symbol, d: PNode) do super
236 end
237
238 # False variable corresponding to closures declared in signatures
239 # Lives in the same namespace than variables
240 class ClosureVariable
241 special Variable
242 redef meth kind do return once "closure"
243
244 # The signature of the closure
245 readable attr _closure: MMClosure
246
247 init(n: Symbol, d: PNode, c: MMClosure)
248 do
249 super(n, d)
250 _closure = c
251 end
252 end
253
254 ###############################################################################
255
256 # Visitor used during the syntax analysis
257 class AbsSyntaxVisitor
258 special Visitor
259 # The root type Object
260 meth type_object: MMType
261 do
262 return _module.class_by_name(once ("Object".to_symbol)).get_type
263 end
264
265 # The primitive type Bool
266 meth type_bool: MMType
267 do
268 return _module.class_by_name(once ("Bool".to_symbol)).get_type
269 end
270
271 # The primitive type Int
272 meth type_int: MMType
273 do
274 return _module.class_by_name(once ("Int".to_symbol)).get_type
275 end
276
277 # The primitive type Float
278 meth type_float: MMType
279 do
280 return _module.class_by_name(once ("Float".to_symbol)).get_type
281 end
282
283 # The primitive type Char
284 meth type_char: MMType
285 do
286 return _module.class_by_name(once ("Char".to_symbol)).get_type
287 end
288
289 # The primitive type String
290 meth type_string: MMType
291 do
292 return _module.class_by_name(once ("String".to_symbol)).get_type
293 end
294
295 # The primitive type Collection[Object]
296 meth type_collection: MMType
297 do
298 return _module.class_by_name(once ("Collection".to_symbol)).get_type
299 end
300
301 # The primitive type Array[?]
302 meth type_array(stype: MMType): MMType
303 do
304 return _module.class_by_name(once ("Array".to_symbol)).get_instantiate_type([stype])
305 end
306
307 # The primitive type Discrete
308 meth type_discrete: MMType
309 do
310 return _module.class_by_name(once ("Discrete".to_symbol)).get_type
311 end
312
313 # The primitive type Range[?]
314 meth type_range(stype: MMType): MMType
315 do
316 return _module.class_by_name(once ("Range".to_symbol)).get_instantiate_type([stype])
317 end
318
319 # The primitive type of null
320 meth type_none: MMType
321 do
322 return _module.type_none
323 end
324
325 # The current module
326 readable writable attr _module: MMSrcModule
327
328 # The current class
329 readable writable attr _local_class: MMSrcLocalClass
330
331 # The current property
332 readable writable attr _local_property: MMLocalProperty
333
334 # The current tool configuration/status
335 readable attr _tc: ToolContext
336
337 # Display an error for a given syntax node
338 meth error(n: PNode, s: String)
339 do
340 _tc.error("{locate(n)}: {s}")
341 end
342
343 # Display a warning for a given syntax node
344 meth warning(n: PNode, s: String)
345 do
346 _tc.warning("{locate(n)}: {s}")
347 end
348
349 #
350 meth locate(n: PNode): String
351 do
352 if n != null then return n.locate
353 return _module.filename
354 end
355
356 # Check conformity and display error
357 meth check_conform(n: PNode, subtype: MMType, stype: MMType): Bool
358 do
359 if stype == null or subtype == null then
360 return false
361 end
362 if subtype < stype then
363 return true
364 end
365 # Do not enforce nullable subtype rules yet
366 if subtype isa MMTypeNone or subtype.as_notnull < stype.as_notnull then
367 warning(n, "Nullable type warning: expected {stype}, got {subtype}")
368 return true
369 end
370 error(n, "Type error: expected {stype}, got {subtype}")
371 return false
372 end
373
374 # Check that an expression has a static type and that
375 # Display an error and return false if n is a statement
376 # Require that the static type of n is known
377 meth check_expr(n: PExpr): Bool
378 do
379 if not n.is_typed then
380 if tc.error_count == 0 then
381 print("{n.locate} not typed but not error")
382 abort
383 end
384 # An error occured in a sub node,
385 # sillently cascade fail
386 return false
387 else if n.is_statement then
388 error(n, "Type error: expected expression.")
389 return false
390 end
391 return true
392 end
393
394 # Combine check_conform and check_expr
395 meth check_conform_expr(n: PExpr, stype: MMType): Bool
396 do
397 if check_expr(n) then return check_conform(n, n.stype, stype) else return false
398 end
399
400 # Check conformance between multiple expressions and a static type
401 # Conformance is granted if among them there is a most general type
402 # Return the most general type if a conformance is found
403 # Display an error and return null if no conformance is found
404 # The only allowed combinaison is with the nullable marker
405 # @param stype is a possible additional type (without node)
406 # Examples:
407 # Int, Int, Object => return Object
408 # Int, Float => display error, return null
409 # nullable Int, Object => return nullable Object
410 meth check_conform_multiexpr(stype: MMType, nodes: Collection[PExpr]): MMType
411 do
412 var node: PExpr = null # candidate node
413 for n in nodes do
414 if not check_expr(n) then return null
415 var ntype = n.stype
416 if stype != null and stype.is_nullable != ntype.is_nullable then
417 # nullable combinaison: if one of them is nulable, considers that both are
418 stype = stype.as_nullable
419 ntype = ntype.as_nullable
420 end
421 if stype == null or (ntype != null and stype < ntype) then
422 stype = ntype
423 node = n
424 end
425 end
426 for n in nodes do
427 if not n.stype < stype then
428 if node == null then
429 error(n, "Type error: no most general type. Got {n.stype} and {stype}.")
430 else
431 error(n, "Type error: no most general type. Got {n.stype} and {stype} at {node.locate}.")
432 end
433 return null
434 end
435 end
436 return stype
437 end
438
439 protected init(tc: ToolContext, module: MMSrcModule)
440 do
441 _tc = tc
442 _module = module
443 end
444 end
445
446 ###############################################################################
447
448 redef class PNode
449 protected meth accept_abs_syntax_visitor(v: AbsSyntaxVisitor) do visit_all(v)
450 end
451
452 redef class Token
453 attr _symbol: Symbol
454
455 # Symbol associated with the text
456 # Lazily computed
457 meth to_symbol: Symbol
458 do
459 var s = _symbol
460 if s == null then
461 s = text.to_symbol
462 _symbol = s
463 end
464 return s
465 end
466 end
467
468 redef class PClassdef
469 # Associated class (MM entity)
470 meth local_class: MMSrcLocalClass is abstract
471 end
472
473 redef class AAttrPropdef
474 # Associated attribute (MM entity)
475 meth prop: MMSrcAttribute is abstract
476
477 # Associated read accessor (MM entity)
478 meth readmethod: MMSrcMethod is abstract
479
480 # Associated write accessor (MM entity)
481 meth writemethod: MMSrcMethod is abstract
482 end
483
484 redef class AMethPropdef
485 # Associated method (MM entity)
486 meth method: MMMethSrcMethod is abstract
487
488 # Associated 'self' variable
489 meth self_var: ParamVariable is abstract
490 end
491
492 redef class ATypePropdef
493 # Associated formal type (MM entity)
494 meth prop: MMSrcTypeProperty is abstract
495 end
496
497 redef class PParam
498 # Position in the signature
499 meth position: Int is abstract
500
501 # Associated local variable
502 meth variable: ParamVariable is abstract
503 end
504
505 redef class PClosureDecl
506 # Associated closure variable
507 meth variable: ClosureVariable is abstract
508 end
509
510 redef class PType
511 # Retrieve the local class corresponding to the type.
512 # Display an error and return null if there is no class
513 # Display an error and return null if the type is not class based (formal one)
514 meth get_local_class(v: AbsSyntaxVisitor): MMLocalClass is abstract
515
516 # Retrieve corresponding static type.
517 # Display an error and return null if there is a problem
518 meth get_stype(v: AbsSyntaxVisitor): MMType is abstract
519
520 # Retrieve corresponding static type.
521 # Display an error and return null if there is a problem
522 # But do not performs any subtype check.
523 # get_unchecked_stype should be called to check that the static type is fully valid
524 meth get_unchecked_stype(v: AbsSyntaxVisitor): MMType is abstract
525
526 # Check that a static definition type is conform with regard to formal types
527 # Useful with get_unchecked_stype
528 # Remember that conformance check need that ancestors are totaly computed
529 meth check_conform(v: AbsSyntaxVisitor) is abstract
530 end
531
532 redef class AType
533 attr _stype_cache: MMType
534 attr _stype_cached: Bool = false
535
536 redef meth get_local_class(v)
537 do
538 var name = n_id.to_symbol
539 var mod = v.module
540 var cla = v.local_class
541
542 if (cla.formal_dict != null and cla.formal_dict.has_key(name)) or (cla.global_properties != null and cla.has_global_property_by_name(name)) then
543 v.error(n_id, "Type error: {name} is a formal type")
544 _stype_cached = true
545 return null
546 end
547
548 if not mod.has_global_class_named(name) then
549 v.error(n_id, "Type error: class {name} not found in module {mod}.")
550 _stype_cached = true
551 return null
552 end
553
554 var local_class = mod.class_by_name(name)
555 local_class.global.check_visibility(v, self, mod)
556 return local_class
557 end
558
559 redef meth get_unchecked_stype(v)
560 do
561 if _stype_cached then return _stype_cache
562 _stype_cached = true
563
564 var name = n_id.to_symbol
565 var mod = v.module
566 var cla = v.local_class
567 var t: MMType
568
569 if cla.formal_dict.has_key(name) then
570 if n_types.length > 0 then
571 v.error(self, "Type error: formal type {name} cannot have formal parameters.")
572 return null
573 end
574 t = cla.formal_dict[name]
575 if n_kwnullable != null then t = t.as_nullable
576 _stype_cache = t
577 return t
578 end
579
580 if cla.global_properties != null and cla.has_global_property_by_name(name) then
581 if n_types.length > 0 then
582 v.error(self, "Type error: formal type {name} cannot have formal parameters.")
583 return null
584 end
585 t = cla.get_type.local_class.select_virtual_type(name).stype_for(cla.get_type)
586 if t == null then
587 v.error(self, "Type error: circular definition in formal type {name}.")
588 return null
589 end
590 if n_kwnullable != null then t = t.as_nullable
591 _stype_cache = t
592 return t
593 end
594
595 var local_class = get_local_class(v)
596 if local_class == null then return null
597
598 var arity = n_types.length
599 if local_class.arity != arity then
600 v.error(self, "Type error: '{local_class}' has {local_class.arity} parameters which differs from the {arity} params.")
601 return null
602 end
603
604 if arity > 0 then
605 var tab = new Array[MMType]
606 for p in n_types do
607 tab.add(p.get_unchecked_stype(v))
608 end
609 t = local_class.get_instantiate_type(tab)
610 else
611 t = local_class.get_type
612 end
613 if n_kwnullable != null then t = t.as_nullable
614 _stype_cache = t
615 return t
616 end
617
618 redef meth get_stype(v)
619 do
620 var t = get_unchecked_stype(v)
621 if t == null then return null
622 if not t.is_valid then return null
623 check_conform(v)
624 return t
625 end
626
627 redef meth check_conform(v)
628 do
629 var st = get_unchecked_stype(v)
630 if st == null then return
631 var local_class = st.local_class
632 var arity = n_types.length
633 if arity > 0 then
634 for i in [0..arity[ do
635 var p = n_types[i]
636 var pt = p.get_stype(v)
637 var b = local_class.get_formal(i)
638 if not b.is_valid then return
639 var bt = b.bound
640 bt = bt.adapt_to(st) # We need to abapt because of F-genericity
641 v.check_conform(p, pt, bt)
642 end
643 end
644 end
645 end
646
647 redef class PExpr
648 # Is the expression node correcly typed
649 # Return false if typed was not yet computed or
650 # if an error occured during the typing computation
651 meth is_typed: Bool is abstract
652
653 # Is the expression node a statement? (ie has no return value)
654 # require: is_typed
655 meth is_statement: Bool is abstract
656
657 # The static type of the expression
658 # require: is_typed and not is_statement
659 meth stype: MMType is abstract
660 end
661
662 redef class AVardeclExpr
663 # Assiociated local variable
664 readable writable attr _variable: VarVariable
665 end
666
667 redef class AForExpr
668 # Associated automatic local variable
669 readable writable attr _variable: AutoVariable
670 end
671
672 redef class ASelfExpr
673 # Associated local variable
674 readable writable attr _variable: ParamVariable
675 end
676
677 redef class AVarFormExpr
678 # Associated local variable
679 readable writable attr _variable: Variable
680 end
681
682 redef class AClosureCallExpr
683 # Associated closure variable
684 readable writable attr _variable: ClosureVariable
685 end
686
687 redef class PClosureDef
688 # Associated closure
689 readable writable attr _closure: MMClosure
690
691 # Automatic variables
692 readable writable attr _variables: Array[AutoVariable]
693 end