1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2012 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 # Load nit source files and build the associated model
21 # FIXME split this module into submodules
22 # FIXME add missing error checks
32 private import more_collections
36 redef class ToolContext
38 var opt_path
: OptionArray = new OptionArray("Set include path for loaders (may be used more than once)", "-I", "--path")
40 # Option --only-metamodel
41 var opt_only_metamodel
: OptionBool = new OptionBool("Stop after meta-model processing", "--only-metamodel")
44 var opt_only_parse
: OptionBool = new OptionBool("Only proceed to parse step of loaders", "--only-parse")
49 option_context
.add_option
(opt_path
, opt_only_parse
, opt_only_metamodel
)
52 fun modelbuilder
: ModelBuilder do return modelbuilder_real
.as(not null)
53 private var modelbuilder_real
: nullable ModelBuilder = null
55 fun run_global_phases
(mainmodule
: MModule)
57 for phase
in phases_list
do
58 phase
.process_mainmodule
(mainmodule
)
64 # Specific action to execute on the whole program
65 # Called by the `ToolContext::run_global_phases`
67 fun process_mainmodule
(mainmodule
: MModule) do end
71 # A model builder knows how to load nit source files and build the associated model
73 # The model where new modules, classes and properties are added
76 # The toolcontext used to control the interaction with the user (getting options and displaying messages)
77 var toolcontext
: ToolContext
79 # Run phases on all loaded modules
82 var mmodules
= model
.mmodules
.to_a
83 model
.mmodule_importation_hierarchy
.sort
(mmodules
)
84 var nmodules
= new Array[AModule]
86 nmodules
.add
(mmodule2nmodule
[mm
])
88 toolcontext
.run_phases
(nmodules
)
90 if toolcontext
.opt_only_metamodel
.value
then
91 self.toolcontext
.info
("*** ONLY METAMODEL", 1)
96 # Instantiate a modelbuilder for a model and a toolcontext
97 # Important, the options of the toolcontext must be correctly set (parse_option already called)
98 init(model
: Model, toolcontext
: ToolContext)
101 self.toolcontext
= toolcontext
102 assert toolcontext
.modelbuilder_real
== null
103 toolcontext
.modelbuilder_real
= self
105 # Setup the paths value
106 paths
.append
(toolcontext
.opt_path
.value
)
108 var path_env
= "NIT_PATH".environ
109 if not path_env
.is_empty
then
110 paths
.append
(path_env
.split_with
(':'))
113 path_env
= "NIT_DIR".environ
114 if not path_env
.is_empty
then
115 var libname
= "{path_env}/lib"
116 if libname
.file_exists
then paths
.add
(libname
)
119 var libname
= "{sys.program_name.dirname}/../lib"
120 if libname
.file_exists
then paths
.add
(libname
.simplify_path
)
123 # Load a bunch of modules.
124 # `modules` can contains filenames or module names.
125 # Imported modules are automatically loaded and modelized.
126 # The result is the corresponding model elements.
127 # Errors and warnings are printed with the toolcontext.
129 # Note: class and property model element are not analysed.
130 fun parse
(modules
: Sequence[String]): Array[MModule]
133 # Parse and recursively load
134 self.toolcontext
.info
("*** PARSE ***", 1)
135 var mmodules
= new ArraySet[MModule]
137 var nmodule
= self.load_module
(a
)
138 if nmodule
== null then continue # Skip error
139 mmodules
.add
(nmodule
.mmodule
.as(not null))
142 self.toolcontext
.info
("*** END PARSE: {time1-time0} ***", 2)
144 self.toolcontext
.check_errors
146 if toolcontext
.opt_only_parse
.value
then
147 self.toolcontext
.info
("*** ONLY PARSE...", 1)
154 # Return a class named `name` visible by the module `mmodule`.
155 # Visibility in modules is correctly handled.
156 # If no such a class exists, then null is returned.
157 # If more than one class exists, then an error on `anode` is displayed and null is returned.
158 # FIXME: add a way to handle class name conflict
159 fun try_get_mclass_by_name
(anode
: ANode, mmodule
: MModule, name
: String): nullable MClass
161 var classes
= model
.get_mclasses_by_name
(name
)
162 if classes
== null then
166 var res
: nullable MClass = null
167 for mclass
in classes
do
168 if not mmodule
.in_importation
<= mclass
.intro_mmodule
then continue
169 if not mmodule
.is_visible
(mclass
.intro_mmodule
, mclass
.visibility
) then continue
173 error
(anode
, "Ambigous class name '{name}'; conflict between {mclass.full_name} and {res.full_name}")
180 # Return a property named `name` on the type `mtype` visible in the module `mmodule`.
181 # Visibility in modules is correctly handled.
182 # Protected properties are returned (it is up to the caller to check and reject protected properties).
183 # If no such a property exists, then null is returned.
184 # If more than one property exists, then an error on `anode` is displayed and null is returned.
185 # FIXME: add a way to handle property name conflict
186 fun try_get_mproperty_by_name2
(anode
: ANode, mmodule
: MModule, mtype
: MType, name
: String): nullable MProperty
188 var props
= self.model
.get_mproperties_by_name
(name
)
189 if props
== null then
193 var cache
= self.try_get_mproperty_by_name2_cache
[mmodule
, mtype
, name
]
194 if cache
!= null then return cache
196 var res
: nullable MProperty = null
197 var ress
: nullable Array[MProperty] = null
198 for mprop
in props
do
199 if not mtype
.has_mproperty
(mmodule
, mprop
) then continue
200 if not mmodule
.is_visible
(mprop
.intro_mclassdef
.mmodule
, mprop
.visibility
) then continue
204 var restype
= res
.intro_mclassdef
.bound_mtype
205 var mproptype
= mprop
.intro_mclassdef
.bound_mtype
206 if restype
.is_subtype
(mmodule
, null, mproptype
) then
208 else if mproptype
.is_subtype
(mmodule
, null, restype
) then
211 if ress
== null then ress
= new Array[MProperty]
217 var restype
= res
.intro_mclassdef
.bound_mtype
219 var mproptype
= mprop
.intro_mclassdef
.bound_mtype
220 if not restype
.is_subtype
(mmodule
, null, mproptype
) then
221 self.error
(anode
, "Ambigous property name '{name}' for {mtype}; conflict between {mprop.full_name} and {res.full_name}")
227 self.try_get_mproperty_by_name2_cache
[mmodule
, mtype
, name
] = res
231 private var try_get_mproperty_by_name2_cache
: HashMap3[MModule, MType, String, nullable MProperty] = new HashMap3[MModule, MType, String, nullable MProperty]
234 # Alias for try_get_mproperty_by_name2(anode, mclassdef.mmodule, mclassdef.mtype, name)
235 fun try_get_mproperty_by_name
(anode
: ANode, mclassdef
: MClassDef, name
: String): nullable MProperty
237 return try_get_mproperty_by_name2
(anode
, mclassdef
.mmodule
, mclassdef
.bound_mtype
, name
)
240 # The list of directories to search for top level modules
241 # The list is initially set with :
242 # * the toolcontext --path option
243 # * the NIT_PATH environment variable
244 # * some heuristics including the NIT_DIR environment variable and the progname of the process
245 # Path can be added (or removed) by the client
246 var paths
: Array[String] = new Array[String]
248 # Get a module by its short name; if required, the module is loaded, parsed and its hierarchies computed.
249 # If `mmodule` is set, then the module search starts from it up to the top level (see `paths`);
250 # if `mmodule` is null then the module is searched in the top level only.
251 # If no module exists or there is a name conflict, then an error on `anode` is displayed and null is returned.
252 # FIXME: add a way to handle module name conflict
253 fun get_mmodule_by_name
(anode
: ANode, mmodule
: nullable MModule, name
: String): nullable MModule
255 # First, look in groups of the module
256 if mmodule
!= null then
257 var mgroup
= mmodule
.mgroup
258 while mgroup
!= null do
259 var dirname
= mgroup
.filepath
260 if dirname
== null then break # virtual group
261 if dirname
.has_suffix
(".nit") then break # singleton project
263 # Second, try the directory to find a file
264 var try_file
= dirname
+ "/" + name
+ ".nit"
265 if try_file
.file_exists
then
266 var res
= self.load_module
(try_file
.simplify_path
)
267 if res
== null then return null # Forward error
268 return res
.mmodule
.as(not null)
271 # Third, try if the requested module is itself a group
272 try_file
= dirname
+ "/" + name
+ "/" + name
+ ".nit"
273 if try_file
.file_exists
then
274 mgroup
= get_mgroup
(dirname
+ "/" + name
)
275 var res
= self.load_module
(try_file
.simplify_path
)
276 if res
== null then return null # Forward error
277 return res
.mmodule
.as(not null)
280 mgroup
= mgroup
.parent
284 # Look at some known directories
285 var lookpaths
= self.paths
287 # Look in the directory of module project also (even if not explicitely in the path)
288 if mmodule
!= null and mmodule
.mgroup
!= null then
289 # path of the root group
290 var dirname
= mmodule
.mgroup
.mproject
.root
.filepath
291 if dirname
!= null then
292 dirname
= dirname
.join_path
("..").simplify_path
293 if not lookpaths
.has
(dirname
) and dirname
.file_exists
then
294 lookpaths
= lookpaths
.to_a
295 lookpaths
.add
(dirname
)
300 var candidate
: nullable String = null
301 for dirname
in lookpaths
do
302 var try_file
= (dirname
+ "/" + name
+ ".nit").simplify_path
303 if try_file
.file_exists
then
304 if candidate
== null then
306 else if candidate
!= try_file
then
307 # try to disambiguate conflicting modules
308 var abs_candidate
= module_absolute_path
(candidate
)
309 var abs_try_file
= module_absolute_path
(try_file
)
310 if abs_candidate
!= abs_try_file
then
311 error
(anode
, "Error: conflicting module file for {name}: {candidate} {try_file}")
315 try_file
= (dirname
+ "/" + name
+ "/" + name
+ ".nit").simplify_path
316 if try_file
.file_exists
then
317 if candidate
== null then
319 else if candidate
!= try_file
then
320 # try to disambiguate conflicting modules
321 var abs_candidate
= module_absolute_path
(candidate
)
322 var abs_try_file
= module_absolute_path
(try_file
)
323 if abs_candidate
!= abs_try_file
then
324 error
(anode
, "Error: conflicting module file for {name}: {candidate} {try_file}")
329 if candidate
== null then
330 if mmodule
!= null then
331 error
(anode
, "Error: cannot find module {name} from {mmodule}. tried {lookpaths.join(", ")}")
333 error
(anode
, "Error: cannot find module {name}. tried {lookpaths.join(", ")}")
337 var res
= self.load_module
(candidate
)
338 if res
== null then return null # Forward error
339 return res
.mmodule
.as(not null)
342 # cache for `identify_file` by realpath
343 private var identified_files
= new HashMap[String, nullable ModulePath]
345 # Identify a source file
346 # Load the associated project and groups if required
347 private fun identify_file
(path
: String): nullable ModulePath
349 if not path
.file_exists
then
350 toolcontext
.error
(null, "Error: `{path}` does not exists")
354 # Fast track, the path is already known
355 var pn
= path
.basename
(".nit")
356 var rp
= module_absolute_path
(path
)
357 if identified_files
.has_key
(rp
) then return identified_files
[rp
]
360 var mgrouppath
= path
.join_path
("..").simplify_path
361 var mgroup
= get_mgroup
(mgrouppath
)
363 if mgroup
== null then
365 var mproject
= new MProject(pn
, model
)
366 mgroup
= new MGroup(pn
, mproject
, null) # same name for the root group
367 mgroup
.filepath
= path
368 mproject
.root
= mgroup
369 toolcontext
.info
("found project `{pn}` at {path}", 2)
372 var res
= new ModulePath(pn
, path
, mgroup
)
374 identified_files
[rp
] = res
379 private var mgroups
= new HashMap[String, nullable MGroup]
381 # return the mgroup associated to a directory path
382 # if the directory is not a group null is returned
383 private fun get_mgroup
(dirpath
: String): nullable MGroup
385 var rdp
= module_absolute_path
(dirpath
)
386 if mgroups
.has_key
(rdp
) then
390 # Hack, a dir is determined by the presence of a honomymous nit file
391 var pn
= rdp
.basename
(".nit")
392 var mp
= dirpath
.join_path
(pn
+ ".nit").simplify_path
394 if not mp
.file_exists
then return null
396 # check parent directory
397 var parentpath
= dirpath
.join_path
("..").simplify_path
398 var parent
= get_mgroup
(parentpath
)
401 if parent
== null then
402 # no parent, thus new project
403 var mproject
= new MProject(pn
, model
)
404 mgroup
= new MGroup(pn
, mproject
, null) # same name for the root group
405 mproject
.root
= mgroup
406 toolcontext
.info
("found project `{mproject}` at {dirpath}", 2)
408 mgroup
= new MGroup(pn
, parent
.mproject
, parent
)
409 toolcontext
.info
("found sub group `{mgroup.full_name}` at {dirpath}", 2)
411 mgroup
.filepath
= dirpath
412 mgroups
[rdp
] = mgroup
416 # Transform relative paths (starting with '../') into absolute paths
417 private fun module_absolute_path
(path
: String): String do
418 return getcwd
.join_path
(path
).simplify_path
421 # Try to load a module AST using a path.
422 # Display an error if there is a problem (IO / lexer / parser) and return null
423 fun load_module_ast
(filename
: String): nullable AModule
425 if filename
.file_extension
!= "nit" then
426 self.toolcontext
.error
(null, "Error: file {filename} is not a valid nit module.")
429 if not filename
.file_exists
then
430 self.toolcontext
.error
(null, "Error: file {filename} not found.")
434 self.toolcontext
.info
("load module {filename}", 2)
437 var file
= new IFStream.open
(filename
)
438 var lexer
= new Lexer(new SourceFile(filename
, file
))
439 var parser
= new Parser(lexer
)
440 var tree
= parser
.parse
442 var mod_name
= filename
.basename
(".nit")
444 # Handle lexer and parser error
445 var nmodule
= tree
.n_base
446 if nmodule
== null then
447 var neof
= tree
.n_eof
448 assert neof
isa AError
449 error
(neof
, neof
.message
)
456 # Try to load a module and its imported modules using a path.
457 # Display an error if there is a problem (IO / lexer / parser / importation) and return null
458 # Note: usually, you do not need this method, use `get_mmodule_by_name` instead.
459 fun load_module
(filename
: String): nullable AModule
461 # Look for the module
462 var file
= identify_file
(filename
)
463 if file
== null then return null # forward error
465 # Already known and loaded? then return it
466 var mmodule
= file
.mmodule
467 if mmodule
!= null then
468 return mmodule2nmodule
[mmodule
]
472 var nmodule
= load_module_ast
(filename
)
473 if nmodule
== null then return null # forward error
475 # build the mmodule and load imported modules
476 mmodule
= build_a_mmodule
(file
.mgroup
, file
.name
, nmodule
)
478 if mmodule
== null then return null # forward error
480 # Update the file information
481 file
.mmodule
= mmodule
483 # Load imported module
484 build_module_importation
(nmodule
)
489 fun load_rt_module
(parent
: MModule, nmodule
: AModule, mod_name
: String): nullable AModule
492 var mmodule
= new MModule(model
, parent
.mgroup
, mod_name
, nmodule
.location
)
493 nmodule
.mmodule
= mmodule
494 nmodules
.add
(nmodule
)
495 self.mmodule2nmodule
[mmodule
] = nmodule
497 var imported_modules
= new Array[MModule]
499 imported_modules
.add
(parent
)
500 mmodule
.set_visibility_for
(parent
, intrude_visibility
)
502 mmodule
.set_imported_mmodules
(imported_modules
)
507 # Visit the AST and create the `MModule` object
508 private fun build_a_mmodule
(mgroup
: nullable MGroup, mod_name
: String, nmodule
: AModule): nullable MModule
510 # Check the module name
511 var decl
= nmodule
.n_moduledecl
513 #warning(nmodule, "Warning: Missing 'module' keyword") #FIXME: NOT YET FOR COMPATIBILITY
515 var decl_name
= decl
.n_name
.n_id
.text
516 if decl_name
!= mod_name
then
517 error
(decl
.n_name
, "Error: module name missmatch; declared {decl_name} file named {mod_name}")
522 var mmodule
= new MModule(model
, mgroup
, mod_name
, nmodule
.location
)
523 nmodule
.mmodule
= mmodule
524 nmodules
.add
(nmodule
)
525 self.mmodule2nmodule
[mmodule
] = nmodule
530 # Analysis the module importation and fill the module_importation_hierarchy
531 private fun build_module_importation
(nmodule
: AModule)
533 if nmodule
.is_importation_done
then return
534 nmodule
.is_importation_done
= true
535 var mmodule
= nmodule
.mmodule
.as(not null)
537 var imported_modules
= new Array[MModule]
538 for aimport
in nmodule
.n_imports
do
540 if not aimport
isa AStdImport then
543 var mod_name
= aimport
.n_name
.n_id
.text
544 var sup
= self.get_mmodule_by_name
(aimport
.n_name
, mmodule
, mod_name
)
545 if sup
== null then continue # Skip error
546 aimport
.mmodule
= sup
547 imported_modules
.add
(sup
)
548 var mvisibility
= aimport
.n_visibility
.mvisibility
549 if mvisibility
== protected_visibility
then
550 error
(aimport
.n_visibility
, "Error: only properties can be protected.")
553 if sup
== mmodule
then
554 error
(aimport
.n_name
, "Error: Dependency loop in module {mmodule}.")
556 if sup
.in_importation
< mmodule
then
557 error
(aimport
.n_name
, "Error: Dependency loop between modules {mmodule} and {sup}.")
560 mmodule
.set_visibility_for
(sup
, mvisibility
)
563 var mod_name
= "standard"
564 var sup
= self.get_mmodule_by_name
(nmodule
, null, mod_name
)
565 if sup
!= null then # Skip error
566 imported_modules
.add
(sup
)
567 mmodule
.set_visibility_for
(sup
, public_visibility
)
570 self.toolcontext
.info
("{mmodule} imports {imported_modules.join(", ")}", 3)
571 mmodule
.set_imported_mmodules
(imported_modules
)
574 # All the loaded modules
575 var nmodules
: Array[AModule] = new Array[AModule]
577 # Register the nmodule associated to each mmodule
578 # FIXME: why not refine the `MModule` class with a nullable attribute?
579 var mmodule2nmodule
: HashMap[MModule, AModule] = new HashMap[MModule, AModule]
581 # Helper function to display an error on a node.
582 # Alias for `self.toolcontext.error(n.hot_location, text)`
583 fun error
(n
: ANode, text
: String)
585 self.toolcontext
.error
(n
.hot_location
, text
)
588 # Helper function to display a warning on a node.
589 # Alias for: `self.toolcontext.warning(n.hot_location, text)`
590 fun warning
(n
: ANode, text
: String)
592 self.toolcontext
.warning
(n
.hot_location
, text
)
595 # Force to get the primitive method named `name` on the type `recv` or do a fatal error on `n`
596 fun force_get_primitive_method
(n
: ANode, name
: String, recv
: MClass, mmodule
: MModule): MMethod
598 var res
= mmodule
.try_get_primitive_method
(name
, recv
)
600 self.toolcontext
.fatal_error
(n
.hot_location
, "Fatal Error: {recv} must have a property named {name}.")
607 # placeholder to a module file identified but not always loaded in a project
608 private class ModulePath
609 # The name of the module
610 # (it's the basename of the filepath)
613 # The human path of the module
616 # The group (and the project) of the possible module
619 # The loaded module (if any)
620 var mmodule
: nullable MModule = null
622 redef fun to_s
do return filepath
626 redef class AStdImport
627 # The imported module once determined
628 var mmodule
: nullable MModule = null
632 # The associated MModule once build by a `ModelBuilder`
633 var mmodule
: nullable MModule
634 # Flag that indicate if the importation is already completed
635 var is_importation_done
: Bool = false
638 redef class AVisibility
639 # The visibility level associated with the AST node class
640 fun mvisibility
: MVisibility is abstract
642 redef class AIntrudeVisibility
643 redef fun mvisibility
do return intrude_visibility
645 redef class APublicVisibility
646 redef fun mvisibility
do return public_visibility
648 redef class AProtectedVisibility
649 redef fun mvisibility
do return protected_visibility
651 redef class APrivateVisibility
652 redef fun mvisibility
do return private_visibility