1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2008 Jean Privat <jean@pryen.org>
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 # Common syntax structures for syntax analysis of NIT AST.
23 # Concrete NIT source module
26 # A source module can locate AST nodes of related MM entities
27 # Once a source module AST is no more needed, _nodes is set to null
28 # See ToolContext::keep_ast property in syntax.nit for details
29 var _nodes
: nullable HashMap[Object, nullable ANode] = new HashMap[Object, nullable ANode]
32 fun clear_ast
do _nodes
= null
34 # The related AST node
35 fun node
: AModule do return nodes
(self).as(AModule)
37 # Concrete NIT source local classs by name
38 readable var _src_local_classes
: Map[Symbol, MMSrcLocalClass]
40 init(c
: MMContext, source
: AModule, dir
: MMDirectory, name
: Symbol, loc
: Location)
42 super(name
, dir
, c
, loc
)
44 _src_local_classes
= new HashMap[Symbol, MMSrcLocalClass]
47 redef fun nodes
(o
: Object): nullable ANode
49 if _nodes
!= null and _nodes
.has_key
(o
) then return _nodes
[o
] else return null
51 redef fun nodes
=(o
: Object, n
: nullable ANode)
53 assert not _nodes
.has_key
(o
)
59 # The AST node of some entity
60 private fun nodes
(o
: Object): nullable ANode do return null
61 # The AST node of some entity
62 private fun nodes
=(o
: Object, n
: nullable ANode) do abort
65 redef class MMGlobalClass
66 # Check that a module can access a class
67 fun check_visibility
(v
: AbsSyntaxVisitor, n
: ANode, cm
: MMSrcModule): Bool do
68 var pm
= intro
.mmmodule
69 assert pm
isa MMSrcModule
70 var vpm
= cm
.visibility_for
(pm
)
74 v
.error
(n
, "Visibility error: Class {self} comes from the hidden module {pm}.") # TODO: should not occur
76 else if visibility_level
>= 3 then
77 v
.error
(n
, "Visibility error: Class {self} is private.")
84 # Concrete NIT source local classes
87 # The first related AST node (if any)
88 fun node
: nullable AClassdef do return mmmodule
.nodes
(self).as(nullable AClassdef)
90 # Concrete NIT source generic formal parameter by name
91 readable var _formal_dict
: Map[Symbol, MMTypeFormalParameter] = new HashMap[Symbol, MMTypeFormalParameter]
93 # Concrete NIT source properties by name
94 readable var _src_local_properties
: Map[Symbol, MMLocalProperty]
96 init(mod
: MMSrcModule, n
: Symbol, cla
: nullable AClassdef, a
: Int)
100 _src_local_properties
= new HashMap[Symbol, MMLocalProperty]
104 redef class MMGlobalProperty
105 # Check that a module can access a property
106 fun check_visibility
(v
: AbsSyntaxVisitor, n
: ANode, cm
: MMSrcModule, allows_protected
: Bool): Bool do
107 var pm
= local_class
.mmmodule
108 assert pm
isa MMSrcModule
109 var vpm
= cm
.visibility_for
(pm
)
112 else if vpm
== 0 then
113 # TODO: should not occurs
114 v
.error
(n
, "Visibility error: Property {self} comes from the hidden module {pm}.")
116 else if visibility_level
>= 3 then
117 v
.error
(n
, "Visibility error: Property {self} is private.")
119 else if visibility_level
>= 2 and not allows_protected
then
120 v
.error
(n
, "Visibility error: Property {self} is protected and can only acceded by self.")
127 redef class MMLocalProperty
128 # The attached node (if any)
129 fun node
: nullable ANode do return null
131 # Is the concrete method defined as init
132 fun is_init
: Bool do return false
135 # Concrete NIT source attribute
138 redef fun node
: nullable AAttrPropdef do return mmmodule
.nodes
(self).as(nullable AAttrPropdef)
139 init(name
: Symbol, cla
: MMLocalClass, n
: AAttrPropdef)
142 cla
.mmmodule
.nodes
(self) = n
146 # Concrete NIT source method
147 abstract class MMSrcMethod
149 redef fun is_intern
do return false
150 redef fun is_extern
do return false
151 redef fun is_abstract
do return false
152 redef fun extern_name
do return null
155 # Concrete NIT source method for an automatic accesor
156 abstract class MMAttrImplementationMethod
158 redef fun node
: nullable AAttrPropdef do return mmmodule
.nodes
(self).as(nullable AAttrPropdef)
159 init(name
: Symbol, cla
: MMLocalClass, n
: AAttrPropdef)
162 cla
.mmmodule
.nodes
(self) = n
166 # Concrete NIT source method for an automatic read accesor
167 class MMReadImplementationMethod
168 super MMAttrImplementationMethod
169 init(name
: Symbol, cla
: MMLocalClass, n
: AAttrPropdef)
175 # Concrete NIT source method for an automatic write accesor
176 class MMWriteImplementationMethod
177 super MMAttrImplementationMethod
178 init(name
: Symbol, cla
: MMLocalClass, n
: AAttrPropdef)
184 # Concrete NIT source method for an explicit method
185 class MMMethSrcMethod
187 redef readable var _is_init
: Bool
188 redef readable var _is_intern
: Bool
189 redef readable var _is_extern
: Bool
190 redef readable var _is_abstract
: Bool
191 redef readable writable var _extern_name
: nullable String # Will be computed during MMBuilder
192 redef readable var _explicit_casts
: Set[MMImportedCast] = new HashSet[MMImportedCast]
193 redef readable var _explicit_imports
: Set[MMExplicitImport] = new HashSet[MMExplicitImport]
194 redef fun node
: nullable AMethPropdef do return mmmodule
.nodes
(self).as(nullable AMethPropdef)
195 init(name
: Symbol, cla
: MMLocalClass, n
: nullable AMethPropdef)
198 cla
.mmmodule
.nodes
(self) = n
199 _is_init
= node
isa AInitPropdef
200 _is_intern
= node
isa AInternMethPropdef
201 _is_extern
= node
isa AExternPropdef
202 _is_abstract
= node
isa ADeferredMethPropdef
206 mmmodule
.is_extern_hybrid
= true
211 # Concrete NIT source virtual type
212 class MMSrcTypeProperty
213 super MMLocalProperty
215 init(name
: Symbol, cla
: MMLocalClass, n
: ATypePropdef)
221 # Concrete NIT implicit constructor
223 super MMMethSrcMethod
224 fun super_init
: nullable MMLocalProperty is abstract
225 redef fun is_init
do return true
226 readable var _unassigned_attributes
: Array[MMSrcAttribute]
227 readable var _super_inits
: Array[MMLocalProperty]
228 init(cla
: MMLocalClass, unassigned_attributes
: Array[MMSrcAttribute], super_inits
: Array[MMLocalProperty])
230 super(once
"init".to_symbol
, cla
, null)
231 _unassigned_attributes
= unassigned_attributes
232 _super_inits
= super_inits
237 abstract class Variable
238 # Name of the variable
239 readable var _name
: Symbol
241 # Declaration AST node
242 readable var _decl
: nullable ANode
245 readable writable var _stype
: nullable MMType
247 redef fun to_s
do return _name
.to_s
249 fun kind
: String is abstract
251 init(n
: Symbol, d
: nullable ANode)
258 # Variable declared with 'var'
261 redef fun kind
do return once
"variable"
262 init(n
: Symbol, d
: ANode) do super
265 # Parameter of method (declared in signature)
268 redef fun kind
do return once
"parameter"
269 init(n
: Symbol, d
: nullable ANode) do super
272 # Automatic variable (like in the 'for' statement)
275 redef fun kind
do return once
"automatic variable"
276 init(n
: Symbol, d
: ANode) do super
279 # False variable corresponding to closures declared in signatures
280 # Lives in the same namespace than variables
281 class ClosureVariable
283 redef fun kind
do return once
"closure"
285 # The signature of the closure
286 readable var _closure
: MMClosure
288 init(n
: Symbol, d
: ANode, c
: MMClosure)
295 ###############################################################################
297 # Visitor used during the syntax analysis
298 abstract class AbsSyntaxVisitor
300 fun get_type_by_name
(clsname
: Symbol): MMType
302 if not _mmmodule
.has_global_class_named
(clsname
) then _tc
.fatal_error
(_mmmodule
.location
, "Missing necessary class: \"{clsname}\
"")
303 var cls
= _mmmodule
.class_by_name
(clsname
)
307 fun get_instantiated_type_by_name
(clsname
: Symbol, vtype
: Array[MMType]): MMType
309 if not _mmmodule
.has_global_class_named
(clsname
) then _tc
.fatal_error
(_mmmodule
.location
, "Missing necessary class: \"{clsname}\
"")
310 var cls
= _mmmodule
.class_by_name
(clsname
)
311 return cls
.get_instantiate_type
(vtype
)
314 # The root type Object
315 fun type_object
: MMType
317 return get_type_by_name
(once
("Object".to_symbol
))
320 # The primitive type Bool
321 fun type_bool
: MMType
323 return get_type_by_name
(once
("Bool".to_symbol
))
326 # The primitive type Int
329 return get_type_by_name
(once
("Int".to_symbol
))
332 # The primitive type Float
333 fun type_float
: MMType
335 return get_type_by_name
(once
("Float".to_symbol
))
338 # The primitive type Char
339 fun type_char
: MMType
341 return get_type_by_name
(once
("Char".to_symbol
))
344 # The primitive type String
345 fun type_string
: MMType
347 return get_type_by_name
(once
("String".to_symbol
))
350 # The primitive type NativeString
351 fun type_nativestring
: MMType
353 return get_type_by_name
(once
("NativeString".to_symbol
))
356 # The primitive type Array[?]
357 fun type_array
(stype
: MMType): MMType
359 return get_instantiated_type_by_name
(once
("Array".to_symbol
), [stype
])
362 # The primitive type Discrete
363 fun type_discrete
: MMType
365 return get_type_by_name
(once
("Discrete".to_symbol
))
368 # The primitive type Range[?]
369 fun type_range
(stype
: MMType): MMType
371 return get_instantiated_type_by_name
(once
("Range".to_symbol
), [stype
])
374 # The primitive type of null
375 fun type_none
: MMType
377 return _mmmodule
.type_none
380 fun get_method
(recv
: MMType, name
: Symbol): MMMethod
382 if not recv
.local_class
.has_global_property_by_name
(name
) then
383 fatal_error
(current_node
, "Fatal Error: {recv} must have a property named {name}.")
385 return recv
.local_class
.select_method
(name
)
389 readable var _mmmodule
: MMSrcModule
392 fun local_class
: MMSrcLocalClass do return _local_class
.as(not null)
393 writable var _local_class
: nullable MMSrcLocalClass
395 # The current property
396 fun local_property
: MMLocalProperty do return _local_property
.as(not null)
397 writable var _local_property
: nullable MMLocalProperty
399 # The current tool configuration/status
400 readable var _tc
: ToolContext
402 # Display an error for a given syntax node
403 fun error
(n
: nullable ANode, s
: String)
405 _tc
.error
(if n
== null then null else n
.hot_location
, s
)
408 # Add an error, show errors and quit
409 fun fatal_error
(n
: nullable ANode, s
: String)
411 _tc
.fatal_error
(if n
== null then null else n
.hot_location
, s
)
414 # Display a warning for a given syntax node
415 fun warning
(n
: nullable ANode, s
: String)
417 _tc
.warning
(if n
== null then null else n
.hot_location
, s
)
420 # Check conformity and display error
421 fun check_conform
(n
: ANode, subtype
: nullable MMType, stype
: nullable MMType): Bool
423 if stype
== null or subtype
== null then
426 if subtype
< stype
then
429 error
(n
, "Type error: expected {stype}, got {subtype}")
433 # Check that an expression has a static type and that
434 # Display an error and return false if n is a statement
435 # Require that the static type of n is known
436 fun check_expr
(n
: AExpr): Bool
438 if not n
.is_typed
then
439 if tc
.error_count
== 0 then
440 print
("{n.location} not typed but not error")
443 # An error occured in a sub node,
444 # sillently cascade fail
446 else if n
.is_statement
then
447 error
(n
, "Type error: expected expression.")
453 # Combine check_conform and check_expr
454 fun check_conform_expr
(n
: AExpr, stype
: nullable MMType): Bool
456 if stype
== null then return false
457 if check_expr
(n
) then return check_conform
(n
, n
.stype
, stype
) else return false
460 # Check conformance between multiple expressions and a static type
461 # Conformance is granted if among them there is a most general type
462 # Return the most general type if a conformance is found
463 # Display an error and return null if no conformance is found
464 # The only allowed combinaison is with the nullable marker
465 # @param stype is a possible additional type (without node)
467 # Int, Int, Object => return Object
468 # Int, Float => display error, return null
469 # nullable Int, Object => return nullable Object
470 fun check_conform_multiexpr
(stype
: nullable MMType, nodes
: Collection[AExpr]): nullable MMType
472 var node
: nullable AExpr = null # candidate node
474 if not check_expr
(n
) then return null
476 if stype
!= null and stype
.is_nullable
!= ntype
.is_nullable
then
477 # nullable combinaison: if one of them is nulable, considers that both are
478 stype
= stype
.as_nullable
479 ntype
= ntype
.as_nullable
481 if stype
== null or stype
< ntype
then
488 if not n
.stype
< stype
then
490 error
(n
, "Type error: no most general type. Got {n.stype} and {stype}.")
492 error
(n
, "Type error: no most general type. Got {n.stype} and {stype} at {node.location.relative_to(n.location)}.")
500 protected init(tc
: ToolContext, mmmodule
: MMSrcModule)
507 ###############################################################################
510 protected fun accept_abs_syntax_visitor
(v
: AbsSyntaxVisitor) do visit_all
(v
)
514 var _symbol_cache
: nullable Symbol
516 # Symbol associated with the text
518 fun to_symbol
: Symbol
520 var s
= _symbol_cache
529 redef class AClassdef
530 # Associated class (MM entity)
531 fun local_class
: MMSrcLocalClass is abstract
533 # Next AClassdef of the same class (if any)
534 readable writable var _next_node
: nullable AClassdef = null
538 # Associated 'self' variable
539 fun self_var
: ParamVariable is abstract
542 redef class AAttrPropdef
543 # Associated attribute (MM entity)
544 fun prop
: MMSrcAttribute is abstract
546 # Associated read accessor (MM entity)
547 fun readmethod
: nullable MMSrcMethod is abstract
549 # Associated write accessor (MM entity)
550 fun writemethod
: nullable MMSrcMethod is abstract
553 redef class AConcreteInitPropdef
554 readable var _super_init_calls
: Array[MMMethod] = new Array[MMMethod]
555 readable var _explicit_super_init_calls
: Array[MMMethod] = new Array[MMMethod]
558 redef class AMethPropdef
559 # Associated method (MM entity)
560 fun method
: MMMethSrcMethod is abstract
563 redef class ATypePropdef
564 # Associated formal type (MM entity)
565 fun prop
: MMSrcTypeProperty is abstract
569 # Position in the signature
570 fun position
: Int is abstract
572 # Associated local variable
573 fun variable
: ParamVariable is abstract
576 redef class AClosureDecl
577 # Position in the signature
578 fun position
: Int is abstract
580 # Associated closure variable
581 fun variable
: ClosureVariable is abstract
585 # Is the node correcly typed
586 # Return false if typed was not yet computed or
587 # if an error occured during the typing computation
588 fun is_typed
: Bool is abstract
590 # Return corresponding static type. (require is_typed)
591 fun stype
: MMType is abstract
593 var _stype_cache
: nullable MMType = null
594 var _stype_cached
: Bool = false
596 # Retrieve the local class corresponding to the type.
597 # Display an error and return null if there is no class
598 # Display an error and return null if the type is not class based (formal one)
599 fun get_local_class
(v
: AbsSyntaxVisitor): nullable MMLocalClass
601 var name
= n_id
.to_symbol
603 var cla
= v
.local_class
605 if cla
.formal_dict
.has_key
(name
) or cla
.has_global_property_by_name
(name
) then
606 v
.error
(n_id
, "Type error: {name} is a formal type")
611 if not mod
.has_global_class_named
(name
) then
612 v
.error
(n_id
, "Type error: class {name} not found in module {mod}.")
617 var local_class
= mod
.class_by_name
(name
)
618 local_class
.global
.check_visibility
(v
, self, mod
)
622 # Retrieve corresponding static type.
623 # Display an error and return null if there is a problem
624 # But do not performs any subtype check.
625 # get_unchecked_stype should be called to check that the static type is fully valid
626 fun get_unchecked_stype
(v
: AbsSyntaxVisitor): nullable MMType
628 if _stype_cached
then return _stype_cache
631 var name
= n_id
.to_symbol
633 var cla
= v
.local_class
634 var t
: nullable MMType
636 if cla
.formal_dict
.has_key
(name
) then
637 if n_types
.length
> 0 then
638 v
.error
(self, "Type error: formal type {name} cannot have formal parameters.")
641 t
= cla
.formal_dict
[name
]
642 if n_kwnullable
!= null then t
= t
.as_nullable
647 if cla
.has_global_property_by_name
(name
) then
648 if n_types
.length
> 0 then
649 v
.error
(self, "Type error: formal type {name} cannot have formal parameters.")
652 t
= cla
.get_type
.local_class
.select_virtual_type
(name
).stype_for
(cla
.get_type
)
654 v
.error
(self, "Type error: circular definition in formal type {name}.")
657 if n_kwnullable
!= null then t
= t
.as_nullable
662 var local_class
= get_local_class
(v
)
663 if local_class
== null then return null
665 var arity
= n_types
.length
666 if local_class
.arity
!= arity
then
668 v
.error
(self, "Type error: '{local_class}' is a generic class.")
669 else if local_class
.arity
== 0 then
670 v
.error
(self, "Type error: '{local_class}' is not a generic class.")
672 v
.error
(self, "Type error: '{local_class}' has {local_class.arity} parameters ({arity} are provided).")
678 var tab
= new Array[MMType]
680 var t2
= p
.get_unchecked_stype
(v
)
681 if t2
== null then return null
684 t
= local_class
.get_instantiate_type
(tab
)
686 t
= local_class
.get_type
688 if n_kwnullable
!= null then t
= t
.as_nullable
693 # Retrieve corresponding static type.
694 # Display an error and return null if there is a problem
695 fun get_stype
(v
: AbsSyntaxVisitor): nullable MMType
697 var t
= get_unchecked_stype
(v
)
698 if t
== null then return null
699 if not t
.is_valid
then return null
704 # Check that a static definition type is conform with regard to formal types
705 # Useful with get_unchecked_stype
706 # Remember that conformance check need that ancestors are totaly computed
707 fun check_conform
(v
: AbsSyntaxVisitor)
709 var st
= get_unchecked_stype
(v
)
710 if st
== null then return
711 var local_class
= st
.local_class
712 var arity
= n_types
.length
714 for i
in [0..arity
[ do
716 var pt
= p
.get_stype
(v
)
717 var b
= local_class
.get_formal
(i
)
718 if not b
.is_valid
then return
720 bt
= bt
.adapt_to
(st
) # We need to abapt because of F-genericity
721 v
.check_conform
(p
, pt
, bt
)
728 # Is the expression node correcly typed
729 # Return false if typed was not yet computed or
730 # if an error occured during the typing computation
731 fun is_typed
: Bool is abstract
733 # Is the expression node a statement? (ie has no return value)
735 fun is_statement
: Bool is abstract
737 # The static type of the expression
738 # require: is_typed and not is_statement
739 fun stype
: MMType is abstract
742 abstract class AAbsAbsSendExpr
744 # The signature of the called property (require is_typed)
745 fun prop_signature
: MMSignature is abstract
747 # The raw arguments used (without vararg transformation) (require is_typed)
748 fun raw_arguments
: Array[AExpr] is abstract
751 abstract class AAbsSendExpr
752 super AAbsAbsSendExpr
753 # The invoked method (require is_typed)
754 fun prop
: MMMethod is abstract
756 # The return type (if any) (once computed)
757 fun return_type
: nullable MMType is abstract
760 abstract class ASuperInitCall
764 redef class ASuperExpr
766 fun init_in_superclass
: nullable MMMethod is abstract
773 redef class ASendExpr
775 # Closure definitions
776 fun closure_defs
: nullable Array[AClosureDef] is abstract
779 redef class AReassignFormExpr
780 # Method used through the reassigment operator (require is_typed)
781 fun assign_method
: MMMethod is abstract
784 abstract class ASendReassignExpr
786 super AReassignFormExpr
787 # The invoked method used to read (require is_typed)
788 # prop is the method used to write
789 fun read_prop
: MMMethod is abstract
792 redef class ACallReassignExpr
793 super ASendReassignExpr
796 redef class ABraReassignExpr
797 super ASendReassignExpr
800 redef class AAttrFormExpr
801 # Attribute accessed (require is_typed)
802 fun prop
: MMAttribute is abstract
804 # Attribute type of the acceded attribute (require is_typed)
805 fun attr_type
: MMType is abstract
808 redef class ASuperstringExpr
809 fun atype
: MMType is abstract
812 redef class AVardeclExpr
813 # Assiociated local variable
814 fun variable
: VarVariable is abstract
815 #readable writable var _variable: nullable VarVariable
819 # Associated automatic local variable
820 fun variables
: Array[AutoVariable] is abstract
823 redef class ASelfExpr
824 # Associated local variable
825 fun variable
: ParamVariable is abstract
828 redef class AVarFormExpr
829 # Associated local variable
830 fun variable
: Variable is abstract
833 redef class AClosureCallExpr
834 super AAbsAbsSendExpr
835 # Associated closure variable
836 fun variable
: ClosureVariable is abstract
839 redef class AClosureDef
841 fun closure
: MMClosure is abstract
843 # Automatic variables
844 readable writable var _variables
: nullable Array[AutoVariable]
849 fun name
: nullable Symbol is abstract
853 # Return an array made of each expr
854 fun to_a
: Array[AExpr] do return self.n_exprs
.to_a