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 # Loading of Nit source files
19 # The loader takes care of looking for module and projects in the file system, and the associated case of errors.
20 # The loading requires several steps:
22 # Identify: create an empty model entity associated to a name or a file path.
23 # Identification is used for instance when names are given in the command line.
24 # See `identify_module` and `identify_group`.
26 # Scan: visit directories and identify their contents.
27 # Scanning is done to enable the searching of modules in projects.
28 # See `scan_group` and `scan_full`.
30 # Parse: load the AST and associate it with the model entity.
31 # See `MModule::parse`.
33 # Import: means recursively load modules imported by a module.
34 # See `build_module_importation`.
36 # Load: means doing the full sequence: identify, parse and import.
37 # See `ModelBuilder::parse`, `ModelBuilder::parse_full`, `MModule::load` `ModelBuilder::load_module.
40 import modelbuilder_base
43 redef class ToolContext
45 var opt_path
= new OptionArray("Add an additional include path (may be used more than once)", "-I", "--path")
47 # Option --only-metamodel
48 var opt_only_metamodel
= new OptionBool("Stop after meta-model processing", "--only-metamodel")
51 var opt_only_parse
= new OptionBool("Only proceed to parse files", "--only-parse")
56 option_context
.add_option
(opt_path
, opt_only_parse
, opt_only_metamodel
)
60 redef class ModelBuilder
65 # Setup the paths value
66 paths
.append
(toolcontext
.opt_path
.value
)
68 var path_env
= "NIT_PATH".environ
69 if not path_env
.is_empty
then
70 paths
.append
(path_env
.split_with
(':'))
73 var nit_dir
= toolcontext
.nit_dir
74 var libname
= nit_dir
/"lib"
75 if libname
.file_exists
then paths
.add
(libname
)
76 libname
= nit_dir
/"contrib"
77 if libname
.file_exists
then paths
.add
(libname
)
80 # Load a bunch of modules.
81 # `modules` can contains filenames or module names.
82 # Imported modules are automatically loaded and modelized.
83 # The result is the corresponding model elements.
84 # Errors and warnings are printed with the toolcontext.
86 # Note: class and property model elements are not analysed.
87 fun parse
(modules
: Sequence[String]): Array[MModule]
90 # Parse and recursively load
91 self.toolcontext
.info
("*** PARSE ***", 1)
92 var mmodules
= new ArraySet[MModule]
94 var nmodule
= self.load_module
(a
)
95 if nmodule
== null then continue # Skip error
96 var mmodule
= nmodule
.mmodule
97 if mmodule
== null then continue # skip error
101 self.toolcontext
.info
("*** END PARSE: {time1-time0} ***", 2)
103 self.toolcontext
.check_errors
105 if toolcontext
.opt_only_parse
.value
then
106 self.toolcontext
.info
("*** ONLY PARSE...", 1)
107 self.toolcontext
.quit
113 # Identify a bunch of modules and groups.
115 # This does the same as `parse_full` but does only the identification (cf. `identify_module`)
116 fun scan_full
(names
: Sequence[String]): Array[MModule]
118 var mmodules
= new Array[MModule]
120 # Case of a group (root or sub-directory)
121 var mgroup
= self.identify_group
(a
)
122 if mgroup
!= null then
124 for mg
in mgroup
.in_nesting
.smallers
do mmodules
.add_all mg
.mmodules
128 # Case of a directory that is not a group
129 var stat
= a
.to_path
.stat
130 if stat
!= null and stat
.is_dir
then
131 self.toolcontext
.info
("look in directory {a}", 2)
133 alpha_comparator
.sort
(fs
)
134 # Try each entry as a group or a module
137 mgroup
= identify_group
(af
)
138 if mgroup
!= null then
140 for mg
in mgroup
.in_nesting
.smallers
do mmodules
.add_all mg
.mmodules
143 var mmodule
= identify_module
(af
)
144 if mmodule
!= null then
147 self.toolcontext
.info
("ignore file {af}", 2)
153 var mmodule
= identify_module
(a
)
154 if mmodule
== null then
155 if a
.file_exists
then
156 toolcontext
.error
(null, "Error: `{a}` is not a Nit source file.")
158 toolcontext
.error
(null, "Error: cannot find module `{a}`.")
168 # Load a bunch of modules and groups.
172 # * a path to a module, a group or a directory of packages.
173 # * a short name of a module or a group that are looked in the `paths` (-I)
175 # Then, for each entry, if it is:
177 # * a module, then is it parsed and returned.
178 # * a group then recursively all its modules are parsed.
179 # * a directory of packages then all the modules of all packages are parsed.
180 # * else an error is displayed.
182 # See `parse` for details.
183 fun parse_full
(names
: Sequence[String]): Array[MModule]
186 # Parse and recursively load
187 self.toolcontext
.info
("*** PARSE ***", 1)
188 var mmodules
= new ArraySet[MModule]
189 var scans
= scan_full
(names
)
190 for mmodule
in scans
do
191 var ast
= mmodule
.load
(self)
192 if ast
== null then continue # Skip error
196 self.toolcontext
.info
("*** END PARSE: {time1-time0} ***", 2)
198 self.toolcontext
.check_errors
200 if toolcontext
.opt_only_parse
.value
then
201 self.toolcontext
.info
("*** ONLY PARSE...", 1)
202 self.toolcontext
.quit
208 # The list of directories to search for top level modules
209 # The list is initially set with:
211 # * the toolcontext --path option
212 # * the NIT_PATH environment variable
213 # * `toolcontext.nit_dir`
214 # Path can be added (or removed) by the client
215 var paths
= new Array[String]
217 # Like (and used by) `get_mmodule_by_name` but does not force the parsing of the MModule (cf. `identify_module`)
218 fun search_mmodule_by_name
(anode
: nullable ANode, mgroup
: nullable MGroup, name
: String): nullable MModule
220 # First, look in groups
223 var r
= c
.mpackage
.root
226 var res
= r
.mmodules_by_name
(name
)
227 if res
.not_empty
then return res
.first
230 # Look at some known directories
231 var lookpaths
= self.paths
233 # Look in the directory of the group package also (even if not explicitly in the path)
234 if mgroup
!= null then
235 # path of the root group
236 var dirname
= mgroup
.mpackage
.root
.filepath
237 if dirname
!= null then
238 dirname
= dirname
.join_path
("..").simplify_path
239 if not lookpaths
.has
(dirname
) and dirname
.file_exists
then
240 lookpaths
= lookpaths
.to_a
241 lookpaths
.add
(dirname
)
247 if anode
!= null then loc
= anode
.hot_location
248 var candidate
= search_module_in_paths
(loc
, name
, lookpaths
)
250 if candidate
== null then
251 if mgroup
!= null then
252 error
(anode
, "Error: cannot find module `{name}` from `{mgroup.name}`. Tried: {lookpaths.join(", ")}.")
254 error
(anode
, "Error: cannot find module `{name}`. Tried: {lookpaths.join(", ")}.")
261 # Get a module by its short name; if required, the module is loaded, parsed and its hierarchies computed.
262 # If `mgroup` is set, then the module search starts from it up to the top level (see `paths`);
263 # if `mgroup` is null then the module is searched in the top level only.
264 # If no module exists or there is a name conflict, then an error on `anode` is displayed and null is returned.
265 fun get_mmodule_by_name
(anode
: nullable ANode, mgroup
: nullable MGroup, name
: String): nullable MModule
267 var mmodule
= search_mmodule_by_name
(anode
, mgroup
, name
)
268 if mmodule
== null then return null # Forward error
269 var ast
= mmodule
.load
(self)
270 if ast
== null then return null # Forward error
274 # Search a module `name` from path `lookpaths`.
275 # If found, the module is returned.
276 private fun search_module_in_paths
(location
: nullable Location, name
: String, lookpaths
: Collection[String]): nullable MModule
278 var res
= new ArraySet[MModule]
279 for dirname
in lookpaths
do
280 # Try a single module file
281 var mp
= identify_module
((dirname
/"{name}.nit").simplify_path
)
282 if mp
!= null then res
.add mp
283 # Try the default module of a group
284 var g
= identify_group
((dirname
/name
).simplify_path
)
287 res
.add_all g
.mmodules_by_name
(name
)
290 if res
.is_empty
then return null
291 if res
.length
> 1 then
292 toolcontext
.error
(location
, "Error: conflicting module files for `{name}`: `{[for x in res do x.filepath or else x.full_name].join("`, `")}`")
297 # Search groups named `name` from paths `lookpaths`.
298 private fun search_group_in_paths
(name
: String, lookpaths
: Collection[String]): ArraySet[MGroup]
300 var res
= new ArraySet[MGroup]
301 for dirname
in lookpaths
do
302 # try a single group directory
303 var mg
= identify_group
(dirname
/name
)
311 # Cache for `identify_module` by relative and real paths
312 private var identified_modules_by_path
= new HashMap[String, nullable MModule]
314 # All the currently identified modules.
315 # See `identify_module`.
317 # An identified module exists in the model but might be not yet parsed (no AST), or not yet analysed (no importation).
318 var identified_modules
= new Array[MModule]
320 # All the currently parsed modules.
322 # A parsed module exists in the model but might be not yet analysed (no importation).
323 var parsed_modules
= new Array[MModule]
325 # Identify a source file and load the associated package and groups if required.
327 # This method does what the user expects when giving an argument to a Nit tool.
329 # * If `path` is an existing Nit source file (with the `.nit` extension),
330 # then the associated MModule is returned
331 # * If `path` is a directory (with a `/`),
332 # then the MModule of its default module is returned (if any)
333 # * If `path` is a simple identifier (eg. `digraph`),
334 # then the main module of the package `digraph` is searched in `paths` and returned.
336 # Silently return `null` if `path` does not exists or cannot be identified.
338 # On success, it returns a module that is possibly not yet parsed (no AST), or not yet analysed (no importation).
339 # If the module was already identified, or loaded, it is returned.
340 fun identify_module
(path
: String): nullable MModule
342 # special case for not a nit file
343 if not path
.has_suffix
(".nit") then
344 # search dirless files in known -I paths
345 if not path
.chars
.has
('/') then
346 var res
= search_module_in_paths
(null, path
, self.paths
)
347 if res
!= null then return res
350 # Found nothing? maybe it is a group...
352 if path
.file_exists
then
353 var mgroup
= identify_group
(path
)
354 if mgroup
!= null then
355 var owner_path
= mgroup
.filepath
.join_path
(mgroup
.name
+ ".nit")
356 if owner_path
.file_exists
then candidate
= owner_path
360 if candidate
== null then
366 # Does the file exists?
367 if not path
.file_exists
then
371 # Fast track, the path is already known
372 if identified_modules_by_path
.has_key
(path
) then return identified_modules_by_path
[path
]
373 var rp
= module_absolute_path
(path
)
374 if identified_modules_by_path
.has_key
(rp
) then return identified_modules_by_path
[rp
]
376 var pn
= path
.basename
(".nit")
379 var mgrouppath
= path
.join_path
("..").simplify_path
380 var mgroup
= identify_group
(mgrouppath
)
382 if mgroup
!= null then
383 var mpackage
= mgroup
.mpackage
384 if not mpackage
.accept
(path
) then
386 toolcontext
.info
("module `{path}` excluded from package `{mpackage}`", 2)
389 if mgroup
== null then
391 var loc
= new Location.opaque_file
(path
)
392 var mpackage
= new MPackage(pn
, model
, loc
)
393 mgroup
= new MGroup(pn
, loc
, mpackage
, null) # same name for the root group
394 mpackage
.root
= mgroup
395 toolcontext
.info
("found singleton package `{pn}` at {path}", 2)
397 # Attach homonymous `ini` file to the package
398 var inipath
= path
.dirname
/ "{pn}.ini"
399 if inipath
.file_exists
then
400 var ini
= new ConfigTree(inipath
)
405 var loc
= new Location.opaque_file
(path
)
406 var res
= new MModule(model
, mgroup
, pn
, loc
)
408 identified_modules_by_path
[rp
] = res
409 identified_modules_by_path
[path
] = res
410 identified_modules
.add
(res
)
415 private var mgroups
= new HashMap[String, nullable MGroup]
417 # Return the mgroup associated to a directory path.
418 # If the directory is not a group null is returned.
420 # Note: `paths` is also used to look for mgroups
421 fun identify_group
(dirpath
: String): nullable MGroup
423 var stat
= dirpath
.file_stat
425 if stat
== null then do
426 # search dirless directories in known -I paths
427 if dirpath
.chars
.has
('/') then return null
429 var try
= p
/ dirpath
439 # Filter out non-directories
440 if not stat
.is_dir
then
444 # Fast track, the path is already known
445 var rdp
= module_absolute_path
(dirpath
)
446 if mgroups
.has_key
(rdp
) then
450 # By default, the name of the package or group is the base_name of the directory
451 var pn
= rdp
.basename
453 # Check `package.ini` that indicate a package
456 var inipath
= dirpath
/ "package.ini"
457 if inipath
.file_exists
then
458 ini
= new ConfigTree(inipath
)
462 # No ini, multiple course of action
464 # The root of the directory hierarchy in the file system.
470 # Special stopper `packages.ini`
471 if (dirpath
/"packages.ini").file_exists
then
472 # dirpath cannot be a package since it is a package directory
477 # check the parent directory (if it does not contain the stopper file)
478 var parentpath
= dirpath
.join_path
("..").simplify_path
479 var stopper
= parentpath
/ "packages.ini"
480 if not stopper
.file_exists
then
481 # Recursively get the parent group
482 parent
= identify_group
(parentpath
)
483 if parent
!= null then do
484 var mpackage
= parent
.mpackage
485 if not mpackage
.accept
(dirpath
) then
486 toolcontext
.info
("directory `{dirpath}` excluded from package `{mpackage}`", 2)
490 if parent
== null then
491 # Parent is not a group, thus we are not a group either
498 var loc
= new Location.opaque_file
(dirpath
)
500 if parent
== null then
501 # no parent, thus new package
502 if ini
!= null then pn
= ini
["package.name"] or else pn
503 var mpackage
= new MPackage(pn
, model
, loc
)
504 mgroup
= new MGroup(pn
, loc
, mpackage
, null) # same name for the root group
505 mpackage
.root
= mgroup
506 toolcontext
.info
("found package `{mpackage}` at {dirpath}", 2)
509 mgroup
= new MGroup(pn
, loc
, parent
.mpackage
, parent
)
510 toolcontext
.info
("found sub group `{mgroup.full_name}` at {dirpath}", 2)
513 # search documentation
514 # in src first so the documentation of the package code can be distinct for the documentation of the package usage
515 var readme
= dirpath
.join_path
("README.md")
516 if not readme
.file_exists
then readme
= dirpath
.join_path
("README")
517 if readme
.file_exists
then
518 var mdoc
= load_markdown
(readme
)
520 mdoc
.original_mentity
= mgroup
523 mgroups
[rdp
] = mgroup
527 # Load a markdown file as a documentation object
528 fun load_markdown
(filepath
: String): MDoc
530 var s
= new FileReader.open
(filepath
)
531 var lines
= new Array[String]
532 var line_starts
= new Array[Int]
535 var line
= s
.read_line
538 len
+= line
.length
+ 1
541 var source
= new SourceFile.from_string
(filepath
, lines
.join
("\n"))
542 source
.line_starts
.add_all line_starts
543 var mdoc
= new MDoc(new Location(source
, 1, lines
.length
, 0, 0))
544 mdoc
.content
.add_all
(lines
)
548 # Force the identification of all MModule of the group and sub-groups in the file system.
550 # When a group is scanned, its sub-groups hierarchy is filled (see `MGroup::in_nesting`)
551 # and the potential modules (and nested modules) are identified (see `MGroup::modules`).
553 # Basically, this recursively call `identify_group` and `identify_module` on each directory entry.
555 # No-op if the group was already scanned (see `MGroup::scanned`).
556 fun scan_group
(mgroup
: MGroup) do
557 if mgroup
.scanned
then return
558 mgroup
.scanned
= true
559 var p
= mgroup
.filepath
560 # a virtual group has nothing to scan
561 if p
== null then return
563 alpha_comparator
.sort
(files
)
566 var g
= identify_group
(fp
)
567 # Recursively scan for groups of the same package
570 else if g
.mpackage
== mgroup
.mpackage
then
576 # Transform relative paths (starting with '../') into absolute paths
577 private fun module_absolute_path
(path
: String): String do
581 # Try to load a module AST using a path.
582 # Display an error if there is a problem (IO / lexer / parser) and return null
584 # The AST is loaded as is total independence of the model and its entities.
586 # AST are not cached or reused thus a new AST is returned on success.
587 fun load_module_ast
(filename
: String): nullable AModule
589 if not filename
.has_suffix
(".nit") then
590 self.toolcontext
.error
(null, "Error: file `{filename}` is not a valid nit module.")
593 if not filename
.file_exists
then
594 self.toolcontext
.error
(null, "Error: file `{filename}` not found.")
598 self.toolcontext
.info
("load module {filename}", 2)
601 var file
= new FileReader.open
(filename
)
602 var lexer
= new Lexer(new SourceFile(filename
, file
))
603 var parser
= new Parser(lexer
)
604 var tree
= parser
.parse
607 # Handle lexer and parser error
608 var nmodule
= tree
.n_base
609 if nmodule
== null then
610 var neof
= tree
.n_eof
611 assert neof
isa AError
612 error
(neof
, neof
.message
)
619 # Remove Nit source files from a list of arguments.
621 # Items of `args` that can be loaded as a nit file will be removed from `args` and returned.
622 fun filter_nit_source
(args
: Array[String]): Array[String]
624 var keep
= new Array[String]
625 var res
= new Array[String]
627 var stat
= a
.to_path
.stat
628 if stat
!= null and stat
.is_dir
then
632 var l
= identify_module
(a
)
644 # Try to load a module using a path.
645 # Display an error if there is a problem (IO / lexer / parser) and return null.
646 # Note: usually, you do not need this method, use `get_mmodule_by_name` instead.
648 # The MModule is located, created, parsed and the importation is performed.
649 fun load_module
(filename
: String): nullable AModule
651 # Look for the module
652 var mmodule
= identify_module
(filename
)
653 if mmodule
== null then
654 if filename
.file_exists
then
655 toolcontext
.error
(null, "Error: `{filename}` is not a Nit source file.")
657 toolcontext
.error
(null, "Error: cannot find module `{filename}`.")
663 return mmodule
.load
(self)
666 # Injection of a new module without source.
667 # Used by the interpreter.
668 fun load_rt_module
(parent
: nullable MModule, nmodule
: AModule, mod_name
: String): nullable AModule
673 if parent
!= null then mgroup
= parent
.mgroup
674 var mmodule
= new MModule(model
, mgroup
, mod_name
, nmodule
.location
)
675 nmodule
.mmodule
= mmodule
676 nmodules
.add
(nmodule
)
677 parsed_modules
.add mmodule
678 self.mmodule2nmodule
[mmodule
] = nmodule
680 if parent
!= null then
681 var imported_modules
= new Array[MModule]
682 imported_modules
.add
(parent
)
683 mmodule
.set_visibility_for
(parent
, intrude_visibility
)
684 mmodule
.set_imported_mmodules
(imported_modules
)
686 build_module_importation
(nmodule
)
692 # Visit the AST and create the `MModule` object
693 private fun build_a_mmodule
(mgroup
: nullable MGroup, nmodule
: AModule)
695 var mmodule
= nmodule
.mmodule
696 assert mmodule
!= null
698 # Check the module name
699 var decl
= nmodule
.n_moduledecl
701 var decl_name
= decl
.n_name
.n_id
.text
702 if decl_name
!= mmodule
.name
then
703 error
(decl
.n_name
, "Error: module name mismatch; declared {decl_name} file named {mmodule.name}.")
707 # Check for conflicting module names in the package
708 if mgroup
!= null then
709 var others
= model
.get_mmodules_by_name
(mmodule
.name
)
710 if others
!= null then for other
in others
do
711 if other
!= mmodule
and mmodule2nmodule
.has_key
(mmodule
) and other
.mgroup
!= null and other
.mgroup
.mpackage
== mgroup
.mpackage
then
713 if decl
== null then node
= nmodule
else node
= decl
.n_name
714 error
(node
, "Error: a module named `{other.full_name}` already exists at {other.location}.")
720 nmodules
.add
(nmodule
)
721 self.mmodule2nmodule
[mmodule
] = nmodule
723 var source
= nmodule
.location
.file
724 if source
!= null then
725 assert source
.mmodule
== null
726 source
.mmodule
= mmodule
730 # Extract documentation
731 var ndoc
= decl
.n_doc
733 var mdoc
= ndoc
.to_mdoc
735 mdoc
.original_mentity
= mmodule
737 # Is the module a test suite?
738 mmodule
.is_test_suite
= not decl
.get_annotations
("test_suite").is_empty
742 # Resolve the module identification for a given `AModuleName`.
744 # This method handles qualified names as used in `AModuleName`.
745 fun seach_module_by_amodule_name
(n_name
: AModuleName, mgroup
: nullable MGroup): nullable MModule
747 var mod_name
= n_name
.n_id
.text
749 # If a quad is given, we ignore the starting group (go from path)
750 if n_name
.n_quad
!= null then mgroup
= null
752 # If name not qualified, just search the name
753 if n_name
.n_path
.is_empty
then
754 # Fast search if no n_path
755 return search_mmodule_by_name
(n_name
, mgroup
, mod_name
)
758 # If qualified and in a group
759 if mgroup
!= null then
760 # First search in the package
761 var r
= mgroup
.mpackage
.root
764 # Get all modules with the final name
765 var res
= r
.mmodules_by_name
(mod_name
)
766 # Filter out the name that does not match the qualifiers
767 res
= [for x
in res
do if match_amodulename
(n_name
, x
) then x
]
768 if res
.not_empty
then
769 if res
.length
> 1 then
770 error
(n_name
, "Error: conflicting module files for `{mod_name}`: `{[for x in res do x.filepath or else x.full_name].join("`, `")}`")
776 # If no module yet, then assume that the first element of the path
777 # Is to be searched in the path.
778 var root_name
= n_name
.n_path
.first
.text
779 var roots
= search_group_in_paths
(root_name
, paths
)
780 if roots
.is_empty
then
781 error
(n_name
, "Error: cannot find `{root_name}`. Tried: {paths.join(", ")}.")
785 var res
= new ArraySet[MModule]
787 # Then, for each root, collect modules that matches the qualifiers
789 var root_res
= r
.mmodules_by_name
(mod_name
)
790 for x
in root_res
do if match_amodulename
(n_name
, x
) then res
.add x
792 if res
.not_empty
then
793 if res
.length
> 1 then
794 error
(n_name
, "Error: conflicting module files for `{mod_name}`: `{[for x in res do x.filepath or else x.full_name].join("`, `")}`")
798 # If still nothing, just call a basic search that will fail and will produce an error message
799 error
(n_name
, "Error: cannot find module `{mod_name}` from `{root_name}`. Tried: {paths.join(", ")}.")
803 # Is elements of `n_name` correspond to the group nesting of `m`?
805 # Basically it check that `bar::foo` matches `bar/foo.nit` and `bar/baz/foo.nit`
806 # but not `baz/foo.nit` nor `foo/bar.nit`
808 # Is used by `seach_module_by_amodule_name` to validate qualified names.
809 private fun match_amodulename
(n_name
: AModuleName, m
: MModule): Bool
811 var g
: nullable MGroup = m
.mgroup
812 for grp
in n_name
.n_path
.reverse_iterator
do
813 while g
!= null and grp
.text
!= g
.name
do
820 # Analyze the module importation and fill the module_importation_hierarchy
822 # If the importation was already done (`nmodule.is_importation_done`), this method does a no-op.
824 # REQUIRE `nmodule.mmodule != null`
825 # ENSURE `nmodule.is_importation_done`
826 fun build_module_importation
(nmodule
: AModule)
828 if nmodule
.is_importation_done
then return
829 nmodule
.is_importation_done
= true
830 var mmodule
= nmodule
.mmodule
.as(not null)
832 var imported_modules
= new Array[MModule]
833 for aimport
in nmodule
.n_imports
do
834 # Do not imports conditional
835 var atconditionals
= aimport
.get_annotations
("conditional")
836 if atconditionals
.not_empty
then continue
839 if not aimport
isa AStdImport then
843 # Load the imported module
844 var sup
= seach_module_by_amodule_name
(aimport
.n_name
, mmodule
.mgroup
)
846 mmodule
.is_broken
= true
847 nmodule
.mmodule
= null # invalidate the module
848 continue # Skip error
850 var ast
= sup
.load
(self)
852 mmodule
.is_broken
= true
853 nmodule
.mmodule
= null # invalidate the module
854 continue # Skip error
857 aimport
.mmodule
= sup
858 imported_modules
.add
(sup
)
859 var mvisibility
= aimport
.n_visibility
.mvisibility
860 if mvisibility
== protected_visibility
then
861 mmodule
.is_broken
= true
862 error
(aimport
.n_visibility
, "Error: only properties can be protected.")
863 mmodule
.is_broken
= true
864 nmodule
.mmodule
= null # invalidate the module
867 if sup
== mmodule
then
868 error
(aimport
.n_name
, "Error: dependency loop in module {mmodule}.")
869 mmodule
.is_broken
= true
870 nmodule
.mmodule
= null # invalidate the module
872 if sup
.in_importation
< mmodule
then
873 error
(aimport
.n_name
, "Error: dependency loop between modules {mmodule} and {sup}.")
874 mmodule
.is_broken
= true
875 nmodule
.mmodule
= null # invalidate the module
878 mmodule
.set_visibility_for
(sup
, mvisibility
)
881 var mod_name
= "core"
882 var sup
= self.get_mmodule_by_name
(nmodule
, null, mod_name
)
884 mmodule
.is_broken
= true
885 nmodule
.mmodule
= null # invalidate the module
887 imported_modules
.add
(sup
)
888 mmodule
.set_visibility_for
(sup
, public_visibility
)
892 # Declare conditional importation
893 for aimport
in nmodule
.n_imports
do
894 if not aimport
isa AStdImport then continue
895 var atconditionals
= aimport
.get_annotations
("conditional")
896 if atconditionals
.is_empty
then continue
898 var suppath
= seach_module_by_amodule_name
(aimport
.n_name
, mmodule
.mgroup
)
899 if suppath
== null then continue # skip error
901 for atconditional
in atconditionals
do
902 var nargs
= atconditional
.n_args
903 if nargs
.is_empty
then
904 error
(atconditional
, "Syntax Error: `conditional` expects module identifiers as arguments.")
909 var rule
= new Array[MModule]
911 # First element is the goal, thus
914 # Second element is the first condition, that is to be a client of the current module
917 # Other condition are to be also a client of each modules indicated as arguments of the annotation
921 error
(narg
, "Syntax Error: `conditional` expects module identifier as arguments.")
925 var mp
= search_mmodule_by_name
(narg
, mmodule
.mgroup
, id
)
926 if mp
== null then continue
931 conditional_importations
.add rule
935 mmodule
.set_imported_mmodules
(imported_modules
)
937 apply_conditional_importations
(mmodule
)
939 self.toolcontext
.info
("{mmodule} imports {mmodule.in_importation.direct_greaters.join(", ")}", 3)
941 # Force `core` to be public if imported
942 for sup
in mmodule
.in_importation
.greaters
do
943 if sup
.name
== "core" then
944 mmodule
.set_visibility_for
(sup
, public_visibility
)
948 # TODO: Correctly check for useless importation
950 var directs
= mmodule
.in_importation
.direct_greaters
951 for nim
in nmodule
.n_imports
do
952 if not nim
isa AStdImport then continue
954 if im
== null then continue
955 if directs
.has
(im
) then continue
956 # This generates so much noise that it is simpler to just comment it
957 #warning(nim, "Warning: possible useless importation of {im}")
961 # Global list of conditional importation rules.
963 # Each rule is a "Horn clause"-like sequence of modules.
964 # It means that the first module is the module to automatically import.
965 # The remaining modules are the conditions of the rule.
967 # Rules are declared by `build_module_importation` and are applied by `apply_conditional_importations`
968 # (and `build_module_importation` that calls it).
970 # TODO (when the loader will be rewritten): use a better representation and move up rules in the model.
971 private var conditional_importations
= new Array[SequenceRead[MModule]]
973 # Extends the current importations according to imported rules about conditional importation
974 fun apply_conditional_importations
(mmodule
: MModule)
976 # Because a conditional importation may cause additional conditional importation, use a fixed point
977 # The rules are checked naively because we assume that it does not worth to be optimized
978 var check_conditional_importations
= true
979 while check_conditional_importations
do
980 check_conditional_importations
= false
982 for ci
in conditional_importations
do
984 for i
in [1..ci
.length
[ do
987 if not mmodule
.in_importation
.greaters
.has
(m
) then continue label
989 # Still here? It means that all conditions modules are loaded and imported
991 # Identify the module to automatically import
993 var ast
= sup
.load
(self)
994 if ast
== null then continue
996 # Do nothing if already imported
997 if mmodule
.in_importation
.greaters
.has
(sup
) then continue label
1000 self.toolcontext
.info
("{mmodule} conditionally imports {sup}", 3)
1001 # TODO visibility rules (currently always public)
1002 mmodule
.set_visibility_for
(sup
, public_visibility
)
1003 # TODO linearization rules (currently added at the end in the order of the rules)
1004 mmodule
.set_imported_mmodules
([sup
])
1006 # Prepare to reapply the rules
1007 check_conditional_importations
= true
1012 # All the loaded modules
1013 var nmodules
= new Array[AModule]
1015 # Register the nmodule associated to each mmodule
1017 # Public clients need to use `mmodule2node` to access stuff.
1018 private var mmodule2nmodule
= new HashMap[MModule, AModule]
1020 # Retrieve the associated AST node of a mmodule.
1021 # This method is used to associate model entity with syntactic entities.
1023 # If the module is not associated with a node, returns null.
1024 fun mmodule2node
(mmodule
: MModule): nullable AModule
1026 return mmodule2nmodule
.get_or_null
(mmodule
)
1031 # Force the parsing of the module using `modelbuilder`.
1033 # If the module was already parsed, the existing ASI is returned.
1034 # Else the source file is loaded, and parsed and some
1036 # The importation is not done by this
1038 # REQUIRE: `filepath != null`
1039 # ENSURE: `modelbuilder.parsed_modules.has(self)`
1040 fun parse
(modelbuilder
: ModelBuilder): nullable AModule
1042 # Already known and loaded? then return it
1043 var nmodule
= modelbuilder
.mmodule2nmodule
.get_or_null
(self)
1044 if nmodule
!= null then return nmodule
1046 var filepath
= self.filepath
1047 assert filepath
!= null
1049 nmodule
= modelbuilder
.load_module_ast
(filepath
)
1050 if nmodule
== null then return null # forward error
1053 nmodule
.mmodule
= self
1054 self.location
= nmodule
.location
1055 modelbuilder
.build_a_mmodule
(mgroup
, nmodule
)
1057 modelbuilder
.parsed_modules
.add
self
1061 # Parse and process importation of a given MModule.
1063 # Basically chains `parse` and `build_module_importation`.
1064 fun load
(modelbuilder
: ModelBuilder): nullable AModule
1066 var nmodule
= parse
(modelbuilder
)
1067 if nmodule
== null then return null
1069 modelbuilder
.build_module_importation
(nmodule
)
1074 redef class MPackage
1075 # The associated `.ini` file, if any
1077 # The `ini` file is given as is and might contain invalid or missing information.
1079 # Some packages, like stand-alone packages or virtual packages have no `ini` file associated.
1080 var ini
: nullable ConfigTree = null
1082 # Array of relative source paths excluded according to the `source.exclude` key of the `ini`
1083 var excludes
: nullable Array[String] is lazy
do
1085 if ini
== null then return null
1086 var exclude
= ini
["source.exclude"]
1087 if exclude
== null then return null
1088 var excludes
= exclude
.split
(":")
1092 # Does the source inclusion/inclusion rules of the package `ini` accept such path?
1093 fun accept
(filepath
: String): Bool
1095 var excludes
= self.excludes
1096 if excludes
!= null then
1097 var relpath
= root
.filepath
.relpath
(filepath
)
1098 if excludes
.has
(relpath
) then return false
1105 # Is the group interesting for a final user?
1107 # Groups are mandatory in the model but for simple packages they are not
1108 # always interesting.
1110 # A interesting group has, at least, one of the following true:
1112 # * it has 2 modules or more
1113 # * it has a subgroup
1114 # * it has a documentation
1115 fun is_interesting
: Bool
1117 return mmodules
.length
> 1 or
1118 not in_nesting
.direct_smallers
.is_empty
or
1120 (mmodules
.length
== 1 and default_mmodule
== null)
1123 # Are files and directories in self scanned?
1125 # See `ModelBuilder::scan_group`.
1128 # Return the modules in self and subgroups named `name`.
1130 # If `self` is not scanned (see `ModelBuilder::scan_group`) the
1131 # results might be partial.
1132 fun mmodules_by_name
(name
: String): Array[MModule]
1134 var res
= new Array[MModule]
1135 for g
in in_nesting
.smallers
do
1136 for mp
in g
.mmodules
do
1137 if mp
.name
== name
then
1146 redef class SourceFile
1147 # Associated mmodule, once created
1148 var mmodule
: nullable MModule = null
1151 redef class AStdImport
1152 # The imported module once determined
1153 var mmodule
: nullable MModule = null
1157 # The associated MModule once build by a `ModelBuilder`
1158 var mmodule
: nullable MModule = null
1160 # Flag that indicate if the importation is already completed
1161 var is_importation_done
: Bool = false