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 if nit_dir
!= null then
75 var libname
= nit_dir
/"lib"
76 if libname
.file_exists
then paths
.add
(libname
)
77 libname
= nit_dir
/"contrib"
78 if libname
.file_exists
then paths
.add
(libname
)
82 # Load a bunch of modules.
83 # `modules` can contains filenames or module names.
84 # Imported modules are automatically loaded and modelized.
85 # The result is the corresponding model elements.
86 # Errors and warnings are printed with the toolcontext.
88 # Note: class and property model elements are not analysed.
89 fun parse
(modules
: Sequence[String]): Array[MModule]
92 # Parse and recursively load
93 self.toolcontext
.info
("*** PARSE ***", 1)
94 var mmodules
= new ArraySet[MModule]
96 var nmodule
= self.load_module
(a
)
97 if nmodule
== null then continue # Skip error
98 var mmodule
= nmodule
.mmodule
99 if mmodule
== null then continue # skip error
103 self.toolcontext
.info
("*** END PARSE: {time1-time0} ***", 2)
105 self.toolcontext
.check_errors
107 if toolcontext
.opt_only_parse
.value
then
108 self.toolcontext
.info
("*** ONLY PARSE...", 1)
109 self.toolcontext
.quit
115 # Identify a bunch of modules and groups.
117 # This does the same as `parse_full` but does only the identification (cf. `identify_module`)
118 fun scan_full
(names
: Sequence[String]): Array[MModule]
120 var mmodules
= new Array[MModule]
122 # Case of a group (root or sub-directory)
123 var mgroup
= self.identify_group
(a
)
124 if mgroup
!= null then
126 for mg
in mgroup
.in_nesting
.smallers
do mmodules
.add_all mg
.mmodules
130 # Case of a directory that is not a group
131 var stat
= a
.to_path
.stat
132 if stat
!= null and stat
.is_dir
then
133 self.toolcontext
.info
("look in directory {a}", 2)
135 alpha_comparator
.sort
(fs
)
136 # Try each entry as a group or a module
139 mgroup
= identify_group
(af
)
140 if mgroup
!= null then
142 for mg
in mgroup
.in_nesting
.smallers
do mmodules
.add_all mg
.mmodules
145 var mmodule
= identify_module
(af
)
146 if mmodule
!= null then
149 self.toolcontext
.info
("ignore file {af}", 2)
155 var mmodule
= identify_module
(a
)
156 if mmodule
== null then
157 if a
.file_exists
then
158 toolcontext
.error
(null, "Error: `{a}` is not a Nit source file.")
160 toolcontext
.error
(null, "Error: cannot find module `{a}`.")
170 # Load a bunch of modules and groups.
174 # * a path to a module, a group or a directory of packages.
175 # * a short name of a module or a group that are looked in the `paths` (-I)
177 # Then, for each entry, if it is:
179 # * a module, then is it parsed and returned.
180 # * a group then recursively all its modules are parsed.
181 # * a directory of packages then all the modules of all packages are parsed.
182 # * else an error is displayed.
184 # See `parse` for details.
185 fun parse_full
(names
: Sequence[String]): Array[MModule]
188 # Parse and recursively load
189 self.toolcontext
.info
("*** PARSE ***", 1)
190 var mmodules
= new ArraySet[MModule]
191 var scans
= scan_full
(names
)
192 for mmodule
in scans
do
193 var ast
= mmodule
.load
(self)
194 if ast
== null then continue # Skip error
198 self.toolcontext
.info
("*** END PARSE: {time1-time0} ***", 2)
200 self.toolcontext
.check_errors
202 if toolcontext
.opt_only_parse
.value
then
203 self.toolcontext
.info
("*** ONLY PARSE...", 1)
204 self.toolcontext
.quit
210 # The list of directories to search for top level modules
211 # The list is initially set with:
213 # * the toolcontext --path option
214 # * the NIT_PATH environment variable
215 # * `toolcontext.nit_dir`
216 # Path can be added (or removed) by the client
217 var paths
= new Array[String]
219 # Like (and used by) `get_mmodule_by_name` but does not force the parsing of the MModule (cf. `identify_module`)
220 fun search_mmodule_by_name
(anode
: nullable ANode, mgroup
: nullable MGroup, name
: String): nullable MModule
222 # First, look in groups
225 var r
= c
.mpackage
.root
228 var res
= r
.mmodules_by_name
(name
)
229 if res
.not_empty
then return res
.first
232 # Look at some known directories
233 var lookpaths
= self.paths
235 # Look in the directory of the group package also (even if not explicitly in the path)
236 if mgroup
!= null then
237 # path of the root group
238 var dirname
= mgroup
.mpackage
.root
.filepath
239 if dirname
!= null then
240 dirname
= dirname
.join_path
("..").simplify_path
241 if not lookpaths
.has
(dirname
) and dirname
.file_exists
then
242 lookpaths
= lookpaths
.to_a
243 lookpaths
.add
(dirname
)
249 if anode
!= null then loc
= anode
.hot_location
250 var candidate
= search_module_in_paths
(loc
, name
, lookpaths
)
252 if candidate
== null then
253 if mgroup
!= null then
254 error
(anode
, "Error: cannot find module `{name}` from `{mgroup.name}`. Tried: {lookpaths.join(", ")}.")
256 error
(anode
, "Error: cannot find module `{name}`. Tried: {lookpaths.join(", ")}.")
263 # Get a module by its short name; if required, the module is loaded, parsed and its hierarchies computed.
264 # If `mgroup` is set, then the module search starts from it up to the top level (see `paths`);
265 # if `mgroup` is null then the module is searched in the top level only.
266 # If no module exists or there is a name conflict, then an error on `anode` is displayed and null is returned.
267 fun get_mmodule_by_name
(anode
: nullable ANode, mgroup
: nullable MGroup, name
: String): nullable MModule
269 var mmodule
= search_mmodule_by_name
(anode
, mgroup
, name
)
270 if mmodule
== null then return null # Forward error
271 var ast
= mmodule
.load
(self)
272 if ast
== null then return null # Forward error
276 # Search a module `name` from path `lookpaths`.
277 # If found, the module is returned.
278 private fun search_module_in_paths
(location
: nullable Location, name
: String, lookpaths
: Collection[String]): nullable MModule
280 var res
= new ArraySet[MModule]
281 for dirname
in lookpaths
do
282 # Try a single module file
283 var mp
= identify_module
((dirname
/"{name}.nit").simplify_path
)
284 if mp
!= null then res
.add mp
285 # Try the default module of a group
286 var g
= identify_group
((dirname
/name
).simplify_path
)
289 res
.add_all g
.mmodules_by_name
(name
)
292 if res
.is_empty
then return null
293 if res
.length
> 1 then
294 toolcontext
.error
(location
, "Error: conflicting module files for `{name}`: `{[for x in res do x.filepath or else x.full_name].join("`, `")}`")
299 # Search groups named `name` from paths `lookpaths`.
300 private fun search_group_in_paths
(name
: String, lookpaths
: Collection[String]): ArraySet[MGroup]
302 var res
= new ArraySet[MGroup]
303 for dirname
in lookpaths
do
304 # try a single group directory
305 var mg
= identify_group
(dirname
/name
)
313 # Cache for `identify_module` by relative and real paths
314 private var identified_modules_by_path
= new HashMap[String, nullable MModule]
316 # All the currently identified modules.
317 # See `identify_module`.
319 # An identified module exists in the model but might be not yet parsed (no AST), or not yet analysed (no importation).
320 var identified_modules
= new Array[MModule]
322 # All the currently parsed modules.
324 # A parsed module exists in the model but might be not yet analysed (no importation).
325 var parsed_modules
= new Array[MModule]
327 # Identify a source file and load the associated package and groups if required.
329 # This method does what the user expects when giving an argument to a Nit tool.
331 # * If `path` is an existing Nit source file (with the `.nit` extension),
332 # then the associated MModule is returned
333 # * If `path` is a directory (with a `/`),
334 # then the MModule of its default module is returned (if any)
335 # * If `path` is a simple identifier (eg. `digraph`),
336 # then the main module of the package `digraph` is searched in `paths` and returned.
338 # Silently return `null` if `path` does not exists or cannot be identified.
340 # On success, it returns a module that is possibly not yet parsed (no AST), or not yet analysed (no importation).
341 # If the module was already identified, or loaded, it is returned.
342 fun identify_module
(path
: String): nullable MModule
344 # special case for not a nit file
345 if not path
.has_suffix
(".nit") then
346 # search dirless files in known -I paths
347 if not path
.chars
.has
('/') then
348 var res
= search_module_in_paths
(null, path
, self.paths
)
349 if res
!= null then return res
352 # Found nothing? maybe it is a group...
354 if path
.file_exists
then
355 var mgroup
= identify_group
(path
)
356 if mgroup
!= null then
357 var owner_path
= mgroup
.filepath
.join_path
(mgroup
.name
+ ".nit")
358 if owner_path
.file_exists
then candidate
= owner_path
362 if candidate
== null then
368 # Does the file exists?
369 if not path
.file_exists
then
373 # Fast track, the path is already known
374 if identified_modules_by_path
.has_key
(path
) then return identified_modules_by_path
[path
]
375 var rp
= module_absolute_path
(path
)
376 if identified_modules_by_path
.has_key
(rp
) then return identified_modules_by_path
[rp
]
378 var pn
= path
.basename
(".nit")
381 var mgrouppath
= path
.join_path
("..").simplify_path
382 var mgroup
= identify_group
(mgrouppath
)
384 if mgroup
!= null then
385 var mpackage
= mgroup
.mpackage
386 if not mpackage
.accept
(path
) then
388 toolcontext
.info
("module `{path}` excluded from package `{mpackage}`", 2)
391 if mgroup
== null then
393 var loc
= new Location.opaque_file
(path
)
394 var mpackage
= new MPackage(pn
, model
, loc
)
395 mgroup
= new MGroup(pn
, loc
, mpackage
, null) # same name for the root group
396 mpackage
.root
= mgroup
397 toolcontext
.info
("found singleton package `{pn}` at {path}", 2)
399 # Attach homonymous `ini` file to the package
400 var inipath
= path
.dirname
/ "{pn}.ini"
401 if inipath
.file_exists
then
402 var ini
= new ConfigTree(inipath
)
407 var loc
= new Location.opaque_file
(path
)
408 var res
= new MModule(model
, mgroup
, pn
, loc
)
410 identified_modules_by_path
[rp
] = res
411 identified_modules_by_path
[path
] = res
412 identified_modules
.add
(res
)
417 private var mgroups
= new HashMap[String, nullable MGroup]
419 # Return the mgroup associated to a directory path.
420 # If the directory is not a group null is returned.
422 # Note: `paths` is also used to look for mgroups
423 fun identify_group
(dirpath
: String): nullable MGroup
425 var stat
= dirpath
.file_stat
427 if stat
== null or not stat
.is_dir
then do
428 # search dirless directories in known -I paths
429 if dirpath
.chars
.has
('/') then return null
431 var try
= p
/ dirpath
441 # Filter out non-directories
442 if not stat
.is_dir
then
446 # Fast track, the path is already known
447 var rdp
= module_absolute_path
(dirpath
)
448 if mgroups
.has_key
(rdp
) then
452 # By default, the name of the package or group is the base_name of the directory
453 var pn
= rdp
.basename
455 # Check `package.ini` that indicate a package
458 var inipath
= dirpath
/ "package.ini"
459 if inipath
.file_exists
then
460 ini
= new ConfigTree(inipath
)
464 # No ini, multiple course of action
466 # The root of the directory hierarchy in the file system.
472 # Special stopper `packages.ini`
473 if (dirpath
/"packages.ini").file_exists
then
474 # dirpath cannot be a package since it is a package directory
479 # check the parent directory (if it does not contain the stopper file)
480 var parentpath
= dirpath
.join_path
("..").simplify_path
481 var stopper
= parentpath
/ "packages.ini"
482 if not stopper
.file_exists
then
483 # Recursively get the parent group
484 parent
= identify_group
(parentpath
)
485 if parent
!= null then do
486 var mpackage
= parent
.mpackage
487 if not mpackage
.accept
(dirpath
) then
488 toolcontext
.info
("directory `{dirpath}` excluded from package `{mpackage}`", 2)
492 if parent
== null then
493 # Parent is not a group, thus we are not a group either
500 var loc
= new Location.opaque_file
(dirpath
)
502 if parent
== null then
503 # no parent, thus new package
504 if ini
!= null then pn
= ini
["package.name"] or else pn
505 var mpackage
= new MPackage(pn
, model
, loc
)
506 mgroup
= new MGroup(pn
, loc
, mpackage
, null) # same name for the root group
507 mpackage
.root
= mgroup
508 toolcontext
.info
("found package `{mpackage}` at {dirpath}", 2)
511 mgroup
= new MGroup(pn
, loc
, parent
.mpackage
, parent
)
512 toolcontext
.info
("found sub group `{mgroup.full_name}` at {dirpath}", 2)
515 # search documentation
516 # in src first so the documentation of the package code can be distinct for the documentation of the package usage
517 var readme
= dirpath
.join_path
("README.md")
518 if not readme
.file_exists
then readme
= dirpath
.join_path
("README")
519 if readme
.file_exists
then
520 var mdoc
= load_markdown
(readme
)
522 mdoc
.original_mentity
= mgroup
525 mgroups
[rdp
] = mgroup
529 # Load a markdown file as a documentation object
530 fun load_markdown
(filepath
: String): MDoc
532 var s
= new FileReader.open
(filepath
)
533 var lines
= new Array[String]
534 var line_starts
= new Array[Int]
537 var line
= s
.read_line
540 len
+= line
.length
+ 1
543 var source
= new SourceFile.from_string
(filepath
, lines
.join
("\n"))
544 source
.line_starts
.add_all line_starts
545 var mdoc
= new MDoc(new Location(source
, 1, lines
.length
, 0, 0))
546 mdoc
.content
.add_all
(lines
)
550 # Force the identification of all MModule of the group and sub-groups in the file system.
552 # When a group is scanned, its sub-groups hierarchy is filled (see `MGroup::in_nesting`)
553 # and the potential modules (and nested modules) are identified (see `MGroup::modules`).
555 # Basically, this recursively call `identify_group` and `identify_module` on each directory entry.
557 # No-op if the group was already scanned (see `MGroup::scanned`).
558 fun scan_group
(mgroup
: MGroup) do
559 if mgroup
.scanned
then return
560 mgroup
.scanned
= true
561 var p
= mgroup
.filepath
562 # a virtual group has nothing to scan
563 if p
== null then return
565 alpha_comparator
.sort
(files
)
568 var g
= identify_group
(fp
)
569 # Recursively scan for groups of the same package
572 else if g
.mpackage
== mgroup
.mpackage
then
578 # Transform relative paths (starting with '../') into absolute paths
579 private fun module_absolute_path
(path
: String): String do
583 # Try to load a module AST using a path.
584 # Display an error if there is a problem (IO / lexer / parser) and return null
586 # The AST is loaded as is total independence of the model and its entities.
588 # AST are not cached or reused thus a new AST is returned on success.
589 fun load_module_ast
(filename
: String): nullable AModule
591 if not filename
.has_suffix
(".nit") then
592 self.toolcontext
.error
(null, "Error: file `{filename}` is not a valid nit module.")
595 if not filename
.file_exists
then
596 self.toolcontext
.error
(null, "Error: file `{filename}` not found.")
600 self.toolcontext
.info
("load module {filename}", 2)
603 var file
= new FileReader.open
(filename
)
604 var lexer
= new Lexer(new SourceFile(filename
, file
))
605 var parser
= new Parser(lexer
)
606 var tree
= parser
.parse
609 # Handle lexer and parser error
610 var nmodule
= tree
.n_base
611 if nmodule
== null then
612 var neof
= tree
.n_eof
613 assert neof
isa AError
614 error
(neof
, neof
.message
)
621 # Remove Nit source files from a list of arguments.
623 # Items of `args` that can be loaded as a nit file will be removed from `args` and returned.
624 fun filter_nit_source
(args
: Array[String]): Array[String]
626 var keep
= new Array[String]
627 var res
= new Array[String]
629 var stat
= a
.to_path
.stat
630 if stat
!= null and stat
.is_dir
then
634 var l
= identify_module
(a
)
646 # Try to load a module using a path.
647 # Display an error if there is a problem (IO / lexer / parser) and return null.
648 # Note: usually, you do not need this method, use `get_mmodule_by_name` instead.
650 # The MModule is located, created, parsed and the importation is performed.
651 fun load_module
(filename
: String): nullable AModule
653 # Look for the module
654 var mmodule
= identify_module
(filename
)
655 if mmodule
== null then
656 if filename
.file_exists
then
657 toolcontext
.error
(null, "Error: `{filename}` is not a Nit source file.")
659 toolcontext
.error
(null, "Error: cannot find module `{filename}`.")
665 return mmodule
.load
(self)
668 # Injection of a new module without source.
669 # Used by the interpreter.
670 fun load_rt_module
(parent
: nullable MModule, nmodule
: AModule, mod_name
: String): nullable AModule
675 if parent
!= null then mgroup
= parent
.mgroup
676 var mmodule
= new MModule(model
, mgroup
, mod_name
, nmodule
.location
)
677 nmodule
.mmodule
= mmodule
678 nmodules
.add
(nmodule
)
679 parsed_modules
.add mmodule
680 self.mmodule2nmodule
[mmodule
] = nmodule
682 if parent
!= null then
683 var imported_modules
= new Array[MModule]
684 imported_modules
.add
(parent
)
685 mmodule
.set_visibility_for
(parent
, intrude_visibility
)
686 mmodule
.set_imported_mmodules
(imported_modules
)
688 build_module_importation
(nmodule
)
694 # Visit the AST and create the `MModule` object
695 private fun build_a_mmodule
(mgroup
: nullable MGroup, nmodule
: AModule)
697 var mmodule
= nmodule
.mmodule
698 assert mmodule
!= null
700 # Check the module name
701 var decl
= nmodule
.n_moduledecl
703 var decl_name
= decl
.n_name
.n_id
.text
704 if decl_name
!= mmodule
.name
then
705 warning
(decl
.n_name
, "module-name-mismatch", "Error: module name mismatch; declared {decl_name} file named {mmodule.name}.")
709 # Check for conflicting module names in the package
710 if mgroup
!= null then
711 var others
= model
.get_mmodules_by_name
(mmodule
.name
)
712 if others
!= null then for other
in others
do
713 if other
!= mmodule
and mmodule2nmodule
.has_key
(mmodule
) and other
.mgroup
!= null and other
.mgroup
.mpackage
== mgroup
.mpackage
then
715 if decl
== null then node
= nmodule
else node
= decl
.n_name
716 error
(node
, "Error: a module named `{other.full_name}` already exists at {other.location}.")
722 nmodules
.add
(nmodule
)
723 self.mmodule2nmodule
[mmodule
] = nmodule
725 var source
= nmodule
.location
.file
726 if source
!= null then
727 assert source
.mmodule
== null
728 source
.mmodule
= mmodule
732 # Extract documentation
733 var ndoc
= decl
.n_doc
735 var mdoc
= ndoc
.to_mdoc
737 mdoc
.original_mentity
= mmodule
739 # Is the module a test suite?
740 mmodule
.is_test_suite
= not decl
.get_annotations
("test_suite").is_empty
744 # Resolve the module identification for a given `AModuleName`.
746 # This method handles qualified names as used in `AModuleName`.
747 fun seach_module_by_amodule_name
(n_name
: AModuleName, mgroup
: nullable MGroup): nullable MModule
749 var mod_name
= n_name
.n_id
.text
751 # If a quad is given, we ignore the starting group (go from path)
752 if n_name
.n_quad
!= null then mgroup
= null
754 # If name not qualified, just search the name
755 if n_name
.n_path
.is_empty
then
756 # Fast search if no n_path
757 return search_mmodule_by_name
(n_name
, mgroup
, mod_name
)
760 # If qualified and in a group
761 if mgroup
!= null then
762 # First search in the package
763 var r
= mgroup
.mpackage
.root
766 # Get all modules with the final name
767 var res
= r
.mmodules_by_name
(mod_name
)
768 # Filter out the name that does not match the qualifiers
769 res
= [for x
in res
do if match_amodulename
(n_name
, x
) then x
]
770 if res
.not_empty
then
771 if res
.length
> 1 then
772 error
(n_name
, "Error: conflicting module files for `{mod_name}`: `{[for x in res do x.filepath or else x.full_name].join("`, `")}`")
778 # If no module yet, then assume that the first element of the path
779 # Is to be searched in the path.
780 var root_name
= n_name
.n_path
.first
.text
781 var roots
= search_group_in_paths
(root_name
, paths
)
782 if roots
.is_empty
then
783 error
(n_name
, "Error: cannot find `{root_name}`. Tried: {paths.join(", ")}.")
787 var res
= new ArraySet[MModule]
789 # Then, for each root, collect modules that matches the qualifiers
791 var root_res
= r
.mmodules_by_name
(mod_name
)
792 for x
in root_res
do if match_amodulename
(n_name
, x
) then res
.add x
794 if res
.not_empty
then
795 if res
.length
> 1 then
796 error
(n_name
, "Error: conflicting module files for `{mod_name}`: `{[for x in res do x.filepath or else x.full_name].join("`, `")}`")
800 # If still nothing, just call a basic search that will fail and will produce an error message
801 error
(n_name
, "Error: cannot find module `{mod_name}` from `{root_name}`. Tried: {paths.join(", ")}.")
805 # Is elements of `n_name` correspond to the group nesting of `m`?
807 # Basically it check that `bar::foo` matches `bar/foo.nit` and `bar/baz/foo.nit`
808 # but not `baz/foo.nit` nor `foo/bar.nit`
810 # Is used by `seach_module_by_amodule_name` to validate qualified names.
811 private fun match_amodulename
(n_name
: AModuleName, m
: MModule): Bool
813 var g
: nullable MGroup = m
.mgroup
814 for grp
in n_name
.n_path
.reverse_iterator
do
815 while g
!= null and grp
.text
!= g
.name
do
822 # Analyze the module importation and fill the module_importation_hierarchy
824 # If the importation was already done (`nmodule.is_importation_done`), this method does a no-op.
826 # REQUIRE `nmodule.mmodule != null`
827 # ENSURE `nmodule.is_importation_done`
828 fun build_module_importation
(nmodule
: AModule)
830 if nmodule
.is_importation_done
then return
831 nmodule
.is_importation_done
= true
832 var mmodule
= nmodule
.mmodule
.as(not null)
834 var imported_modules
= new Array[MModule]
835 for aimport
in nmodule
.n_imports
do
836 # Do not imports conditional
837 var atconditionals
= aimport
.get_annotations
("conditional")
838 if atconditionals
.not_empty
then continue
841 if not aimport
isa AStdImport then
845 # Load the imported module
846 var sup
= seach_module_by_amodule_name
(aimport
.n_name
, mmodule
.mgroup
)
848 mmodule
.is_broken
= true
849 nmodule
.mmodule
= null # invalidate the module
850 continue # Skip error
852 var ast
= sup
.load
(self)
854 mmodule
.is_broken
= true
855 nmodule
.mmodule
= null # invalidate the module
856 continue # Skip error
859 aimport
.mmodule
= sup
860 imported_modules
.add
(sup
)
861 var mvisibility
= aimport
.n_visibility
.mvisibility
862 if mvisibility
== protected_visibility
then
863 mmodule
.is_broken
= true
864 error
(aimport
.n_visibility
, "Error: only properties can be protected.")
865 mmodule
.is_broken
= true
866 nmodule
.mmodule
= null # invalidate the module
869 if sup
== mmodule
then
870 error
(aimport
.n_name
, "Error: dependency loop in module {mmodule}.")
871 mmodule
.is_broken
= true
872 nmodule
.mmodule
= null # invalidate the module
874 if sup
.in_importation
< mmodule
then
875 error
(aimport
.n_name
, "Error: dependency loop between modules {mmodule} and {sup}.")
876 mmodule
.is_broken
= true
877 nmodule
.mmodule
= null # invalidate the module
880 mmodule
.set_visibility_for
(sup
, mvisibility
)
883 var mod_name
= "core"
884 var sup
= self.get_mmodule_by_name
(nmodule
, null, mod_name
)
886 mmodule
.is_broken
= true
887 nmodule
.mmodule
= null # invalidate the module
889 imported_modules
.add
(sup
)
890 mmodule
.set_visibility_for
(sup
, public_visibility
)
894 # Declare conditional importation
895 for aimport
in nmodule
.n_imports
do
896 if not aimport
isa AStdImport then continue
897 var atconditionals
= aimport
.get_annotations
("conditional")
898 if atconditionals
.is_empty
then continue
900 var suppath
= seach_module_by_amodule_name
(aimport
.n_name
, mmodule
.mgroup
)
901 if suppath
== null then continue # skip error
903 for atconditional
in atconditionals
do
904 var nargs
= atconditional
.n_args
905 if nargs
.is_empty
then
906 error
(atconditional
, "Syntax Error: `conditional` expects module identifiers as arguments.")
911 var rule
= new Array[MModule]
913 # First element is the goal, thus
916 # Second element is the first condition, that is to be a client of the current module
919 # Other condition are to be also a client of each modules indicated as arguments of the annotation
923 error
(narg
, "Syntax Error: `conditional` expects module identifier as arguments.")
927 var mp
= search_mmodule_by_name
(narg
, mmodule
.mgroup
, id
)
928 if mp
== null then continue
933 conditional_importations
.add rule
937 mmodule
.set_imported_mmodules
(imported_modules
)
939 apply_conditional_importations
(mmodule
)
941 self.toolcontext
.info
("{mmodule} imports {mmodule.in_importation.direct_greaters.join(", ")}", 3)
943 # Force `core` to be public if imported
944 for sup
in mmodule
.in_importation
.greaters
do
945 if sup
.name
== "core" then
946 mmodule
.set_visibility_for
(sup
, public_visibility
)
950 # TODO: Correctly check for useless importation
952 var directs
= mmodule
.in_importation
.direct_greaters
953 for nim
in nmodule
.n_imports
do
954 if not nim
isa AStdImport then continue
956 if im
== null then continue
957 if directs
.has
(im
) then continue
958 # This generates so much noise that it is simpler to just comment it
959 #warning(nim, "Warning: possible useless importation of {im}")
963 # Global list of conditional importation rules.
965 # Each rule is a "Horn clause"-like sequence of modules.
966 # It means that the first module is the module to automatically import.
967 # The remaining modules are the conditions of the rule.
969 # Rules are declared by `build_module_importation` and are applied by `apply_conditional_importations`
970 # (and `build_module_importation` that calls it).
972 # TODO (when the loader will be rewritten): use a better representation and move up rules in the model.
973 private var conditional_importations
= new Array[SequenceRead[MModule]]
975 # Extends the current importations according to imported rules about conditional importation
976 fun apply_conditional_importations
(mmodule
: MModule)
978 # Because a conditional importation may cause additional conditional importation, use a fixed point
979 # The rules are checked naively because we assume that it does not worth to be optimized
980 var check_conditional_importations
= true
981 while check_conditional_importations
do
982 check_conditional_importations
= false
984 for ci
in conditional_importations
do
986 for i
in [1..ci
.length
[ do
989 if not mmodule
.in_importation
.greaters
.has
(m
) then continue label
991 # Still here? It means that all conditions modules are loaded and imported
993 # Identify the module to automatically import
995 var ast
= sup
.load
(self)
996 if ast
== null then continue
998 # Do nothing if already imported
999 if mmodule
.in_importation
.greaters
.has
(sup
) then continue label
1002 self.toolcontext
.info
("{mmodule} conditionally imports {sup}", 3)
1003 # TODO visibility rules (currently always public)
1004 mmodule
.set_visibility_for
(sup
, public_visibility
)
1005 # TODO linearization rules (currently added at the end in the order of the rules)
1006 mmodule
.set_imported_mmodules
([sup
])
1008 # Prepare to reapply the rules
1009 check_conditional_importations
= true
1014 # All the loaded modules
1015 var nmodules
= new Array[AModule]
1017 # Register the nmodule associated to each mmodule
1019 # Public clients need to use `mmodule2node` to access stuff.
1020 private var mmodule2nmodule
= new HashMap[MModule, AModule]
1022 # Retrieve the associated AST node of a mmodule.
1023 # This method is used to associate model entity with syntactic entities.
1025 # If the module is not associated with a node, returns null.
1026 fun mmodule2node
(mmodule
: MModule): nullable AModule
1028 return mmodule2nmodule
.get_or_null
(mmodule
)
1033 # Force the parsing of the module using `modelbuilder`.
1035 # If the module was already parsed, the existing ASI is returned.
1036 # Else the source file is loaded, and parsed and some
1038 # The importation is not done by this
1040 # REQUIRE: `filepath != null`
1041 # ENSURE: `modelbuilder.parsed_modules.has(self)`
1042 fun parse
(modelbuilder
: ModelBuilder): nullable AModule
1044 # Already known and loaded? then return it
1045 var nmodule
= modelbuilder
.mmodule2nmodule
.get_or_null
(self)
1046 if nmodule
!= null then return nmodule
1048 var filepath
= self.filepath
1049 assert filepath
!= null
1051 nmodule
= modelbuilder
.load_module_ast
(filepath
)
1052 if nmodule
== null then return null # forward error
1055 nmodule
.mmodule
= self
1056 self.location
= nmodule
.location
1057 modelbuilder
.build_a_mmodule
(mgroup
, nmodule
)
1059 modelbuilder
.parsed_modules
.add
self
1063 # Parse and process importation of a given MModule.
1065 # Basically chains `parse` and `build_module_importation`.
1066 fun load
(modelbuilder
: ModelBuilder): nullable AModule
1068 var nmodule
= parse
(modelbuilder
)
1069 if nmodule
== null then return null
1071 modelbuilder
.build_module_importation
(nmodule
)
1076 redef class MPackage
1077 # The associated `.ini` file, if any
1079 # The `ini` file is given as is and might contain invalid or missing information.
1081 # Some packages, like stand-alone packages or virtual packages have no `ini` file associated.
1082 var ini
: nullable ConfigTree = null
1084 # Array of relative source paths excluded according to the `source.exclude` key of the `ini`
1085 var excludes
: nullable Array[String] is lazy
do
1087 if ini
== null then return null
1088 var exclude
= ini
["source.exclude"]
1089 if exclude
== null then return null
1090 var excludes
= exclude
.split
(":")
1094 # Does the source inclusion/inclusion rules of the package `ini` accept such path?
1095 fun accept
(filepath
: String): Bool
1097 var excludes
= self.excludes
1098 if excludes
!= null then
1099 var relpath
= root
.filepath
.relpath
(filepath
)
1100 if excludes
.has
(relpath
) then return false
1107 # Is the group interesting for a final user?
1109 # Groups are mandatory in the model but for simple packages they are not
1110 # always interesting.
1112 # A interesting group has, at least, one of the following true:
1114 # * it has 2 modules or more
1115 # * it has a subgroup
1116 # * it has a documentation
1117 fun is_interesting
: Bool
1119 return mmodules
.length
> 1 or
1120 not in_nesting
.direct_smallers
.is_empty
or
1122 (mmodules
.length
== 1 and default_mmodule
== null)
1125 # Are files and directories in self scanned?
1127 # See `ModelBuilder::scan_group`.
1130 # Return the modules in self and subgroups named `name`.
1132 # If `self` is not scanned (see `ModelBuilder::scan_group`) the
1133 # results might be partial.
1134 fun mmodules_by_name
(name
: String): Array[MModule]
1136 var res
= new Array[MModule]
1137 for g
in in_nesting
.smallers
do
1138 for mp
in g
.mmodules
do
1139 if mp
.name
== name
then
1148 redef class SourceFile
1149 # Associated mmodule, once created
1150 var mmodule
: nullable MModule = null
1153 redef class AStdImport
1154 # The imported module once determined
1155 var mmodule
: nullable MModule = null
1159 # The associated MModule once build by a `ModelBuilder`
1160 var mmodule
: nullable MModule = null
1162 # Flag that indicate if the importation is already completed
1163 var is_importation_done
: Bool = false