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
20 import modelbuilder_base
23 redef class ToolContext
25 var opt_path
= new OptionArray("Set include path for loaders (may be used more than once)", "-I", "--path")
27 # Option --only-metamodel
28 var opt_only_metamodel
= new OptionBool("Stop after meta-model processing", "--only-metamodel")
31 var opt_only_parse
= new OptionBool("Only proceed to parse step of loaders", "--only-parse")
36 option_context
.add_option
(opt_path
, opt_only_parse
, opt_only_metamodel
)
40 redef class ModelBuilder
45 # Setup the paths value
46 paths
.append
(toolcontext
.opt_path
.value
)
48 var path_env
= "NIT_PATH".environ
49 if not path_env
.is_empty
then
50 paths
.append
(path_env
.split_with
(':'))
53 var nit_dir
= toolcontext
.nit_dir
54 var libname
= nit_dir
/"lib"
55 if libname
.file_exists
then paths
.add
(libname
)
56 libname
= nit_dir
/"contrib"
57 if libname
.file_exists
then paths
.add
(libname
)
60 # Load a bunch of modules.
61 # `modules` can contains filenames or module names.
62 # Imported modules are automatically loaded and modelized.
63 # The result is the corresponding model elements.
64 # Errors and warnings are printed with the toolcontext.
66 # Note: class and property model elements are not analysed.
67 fun parse
(modules
: Sequence[String]): Array[MModule]
70 # Parse and recursively load
71 self.toolcontext
.info
("*** PARSE ***", 1)
72 var mmodules
= new ArraySet[MModule]
74 var nmodule
= self.load_module
(a
)
75 if nmodule
== null then continue # Skip error
76 # Load imported module
77 build_module_importation
(nmodule
)
78 var mmodule
= nmodule
.mmodule
79 if mmodule
== null then continue # skip error
83 self.toolcontext
.info
("*** END PARSE: {time1-time0} ***", 2)
85 self.toolcontext
.check_errors
87 if toolcontext
.opt_only_parse
.value
then
88 self.toolcontext
.info
("*** ONLY PARSE...", 1)
95 # Load recursively all modules of the group `mgroup`.
96 # See `parse` for details.
97 fun parse_group
(mgroup
: MGroup): Array[MModule]
99 var res
= new Array[MModule]
101 for mg
in mgroup
.in_nesting
.smallers
do
102 for mp
in mg
.module_paths
do
103 var nmodule
= self.load_module
(mp
.filepath
)
104 if nmodule
== null then continue # Skip error
105 # Load imported module
106 build_module_importation
(nmodule
)
107 var mmodule
= nmodule
.mmodule
108 if mmodule
== null then continue # Skip error
115 # Load a bunch of modules and groups.
119 # * a path to a module, a group or a directory of packages.
120 # * a short name of a module or a group that are looked in the `paths` (-I)
122 # Then, for each entry, if it is:
124 # * a module, then is it parser and returned.
125 # * a group then recursively all its modules are parsed.
126 # * a directory of packages then all the modules of all packages are parsed.
127 # * else an error is displayed.
129 # See `parse` for details.
130 fun parse_full
(names
: Sequence[String]): Array[MModule]
133 # Parse and recursively load
134 self.toolcontext
.info
("*** PARSE ***", 1)
135 var mmodules
= new ArraySet[MModule]
138 var mgroup
= self.get_mgroup
(a
)
139 if mgroup
!= null then
140 mmodules
.add_all parse_group
(mgroup
)
144 # Case of a directory that is not a group
145 var stat
= a
.to_path
.stat
146 if stat
!= null and stat
.is_dir
then
147 self.toolcontext
.info
("look in directory {a}", 2)
149 # Try each entry as a group or a module
152 mgroup
= get_mgroup
(af
)
153 if mgroup
!= null then
154 mmodules
.add_all parse_group
(mgroup
)
157 var mp
= identify_file
(af
)
159 var nmodule
= self.load_module
(af
)
160 if nmodule
== null then continue # Skip error
161 build_module_importation
(nmodule
)
162 var mmodule
= nmodule
.mmodule
163 if mmodule
== null then continue # Skip error
166 self.toolcontext
.info
("ignore file {af}", 2)
172 var nmodule
= self.load_module
(a
)
173 if nmodule
== null then continue # Skip error
174 # Load imported module
175 build_module_importation
(nmodule
)
176 var mmodule
= nmodule
.mmodule
177 if mmodule
== null then continue # Skip error
181 self.toolcontext
.info
("*** END PARSE: {time1-time0} ***", 2)
183 self.toolcontext
.check_errors
185 if toolcontext
.opt_only_parse
.value
then
186 self.toolcontext
.info
("*** ONLY PARSE...", 1)
193 # The list of directories to search for top level modules
194 # The list is initially set with:
196 # * the toolcontext --path option
197 # * the NIT_PATH environment variable
198 # * `toolcontext.nit_dir`
199 # Path can be added (or removed) by the client
200 var paths
= new Array[String]
202 # Like (and used by) `get_mmodule_by_name` but just return the ModulePath
203 fun search_mmodule_by_name
(anode
: nullable ANode, mgroup
: nullable MGroup, name
: String): nullable ModulePath
205 # First, look in groups
208 var r
= c
.mpackage
.root
211 var res
= r
.mmodule_paths_by_name
(name
)
212 if res
.not_empty
then return res
.first
215 # Look at some known directories
216 var lookpaths
= self.paths
218 # Look in the directory of the group package also (even if not explicitly in the path)
219 if mgroup
!= null then
220 # path of the root group
221 var dirname
= mgroup
.mpackage
.root
.filepath
222 if dirname
!= null then
223 dirname
= dirname
.join_path
("..").simplify_path
224 if not lookpaths
.has
(dirname
) and dirname
.file_exists
then
225 lookpaths
= lookpaths
.to_a
226 lookpaths
.add
(dirname
)
231 var candidate
= search_module_in_paths
(anode
.hot_location
, name
, lookpaths
)
233 if candidate
== null then
234 if mgroup
!= null then
235 error
(anode
, "Error: cannot find module `{name}` from `{mgroup.name}`. Tried: {lookpaths.join(", ")}.")
237 error
(anode
, "Error: cannot find module `{name}`. Tried: {lookpaths.join(", ")}.")
244 # Get a module by its short name; if required, the module is loaded, parsed and its hierarchies computed.
245 # If `mgroup` is set, then the module search starts from it up to the top level (see `paths`);
246 # if `mgroup` is null then the module is searched in the top level only.
247 # If no module exists or there is a name conflict, then an error on `anode` is displayed and null is returned.
248 fun get_mmodule_by_name
(anode
: nullable ANode, mgroup
: nullable MGroup, name
: String): nullable MModule
250 var path
= search_mmodule_by_name
(anode
, mgroup
, name
)
251 if path
== null then return null # Forward error
252 return load_module_path
(path
)
255 # Load and process importation of a given ModulePath.
257 # Basically chains `load_module` and `build_module_importation`.
258 fun load_module_path
(path
: ModulePath): nullable MModule
260 var res
= self.load_module
(path
.filepath
)
261 if res
== null then return null # Forward error
262 # Load imported module
263 build_module_importation
(res
)
267 # Search a module `name` from path `lookpaths`.
268 # If found, the path of the file is returned
269 private fun search_module_in_paths
(location
: nullable Location, name
: String, lookpaths
: Collection[String]): nullable ModulePath
271 var res
= new ArraySet[ModulePath]
272 for dirname
in lookpaths
do
273 # Try a single module file
274 var mp
= identify_file
((dirname
/"{name}.nit").simplify_path
)
275 if mp
!= null then res
.add mp
276 # Try the default module of a group
277 var g
= get_mgroup
((dirname
/name
).simplify_path
)
280 res
.add_all g
.mmodule_paths_by_name
(name
)
283 if res
.is_empty
then return null
284 if res
.length
> 1 then
285 toolcontext
.error
(location
, "Error: conflicting module files for `{name}`: `{res.join(",")}`")
290 # Search groups named `name` from paths `lookpaths`.
291 private fun search_group_in_paths
(name
: String, lookpaths
: Collection[String]): ArraySet[MGroup]
293 var res
= new ArraySet[MGroup]
294 for dirname
in lookpaths
do
295 # try a single group directory
296 var mg
= get_mgroup
(dirname
/name
)
304 # Cache for `identify_file` by realpath
305 private var identified_files_by_path
= new HashMap[String, nullable ModulePath]
307 # All the currently identified modules.
308 # See `identify_file`.
309 var identified_files
= new Array[ModulePath]
311 # Identify a source file and load the associated package and groups if required.
313 # This method does what the user expects when giving an argument to a Nit tool.
315 # * If `path` is an existing Nit source file (with the `.nit` extension),
316 # then the associated ModulePath is returned
317 # * If `path` is a directory (with a `/`),
318 # then the ModulePath of its default module is returned (if any)
319 # * If `path` is a simple identifier (eg. `digraph`),
320 # then the main module of the package `digraph` is searched in `paths` and returned.
322 # Silently return `null` if `path` does not exists or cannot be identified.
323 fun identify_file
(path
: String): nullable ModulePath
325 # special case for not a nit file
326 if not path
.has_suffix
(".nit") then
327 # search dirless files in known -I paths
328 if not path
.chars
.has
('/') then
329 var res
= search_module_in_paths
(null, path
, self.paths
)
330 if res
!= null then return res
333 # Found nothing? maybe it is a group...
335 if path
.file_exists
then
336 var mgroup
= get_mgroup
(path
)
337 if mgroup
!= null then
338 var owner_path
= mgroup
.filepath
.join_path
(mgroup
.name
+ ".nit")
339 if owner_path
.file_exists
then candidate
= owner_path
343 if candidate
== null then
349 # Does the file exists?
350 if not path
.file_exists
then
354 # Fast track, the path is already known
355 if identified_files_by_path
.has_key
(path
) then return identified_files_by_path
[path
]
356 var rp
= module_absolute_path
(path
)
357 if identified_files_by_path
.has_key
(rp
) then return identified_files_by_path
[rp
]
359 var pn
= path
.basename
(".nit")
362 var mgrouppath
= path
.join_path
("..").simplify_path
363 var mgroup
= get_mgroup
(mgrouppath
)
365 if mgroup
== null then
367 var mpackage
= new MPackage(pn
, model
)
368 mgroup
= new MGroup(pn
, mpackage
, null) # same name for the root group
369 mgroup
.filepath
= path
370 mpackage
.root
= mgroup
371 toolcontext
.info
("found singleton package `{pn}` at {path}", 2)
373 # Attach homonymous `ini` file to the package
374 var inipath
= path
.dirname
/ "{pn}.ini"
375 if inipath
.file_exists
then
376 var ini
= new ConfigTree(inipath
)
381 var res
= new ModulePath(pn
, path
, mgroup
)
382 mgroup
.module_paths
.add
(res
)
384 identified_files_by_path
[rp
] = res
385 identified_files_by_path
[path
] = res
386 identified_files
.add
(res
)
391 private var mgroups
= new HashMap[String, nullable MGroup]
393 # Return the mgroup associated to a directory path.
394 # If the directory is not a group null is returned.
396 # Note: `paths` is also used to look for mgroups
397 fun get_mgroup
(dirpath
: String): nullable MGroup
399 var stat
= dirpath
.file_stat
401 if stat
== null then do
402 # search dirless directories in known -I paths
403 if dirpath
.chars
.has
('/') then return null
405 var try
= p
/ dirpath
415 # Filter out non-directories
416 if not stat
.is_dir
then
420 # Fast track, the path is already known
421 var rdp
= module_absolute_path
(dirpath
)
422 if mgroups
.has_key
(rdp
) then
426 # By default, the name of the package or group is the base_name of the directory
427 var pn
= rdp
.basename
429 # Check `package.ini` that indicate a package
432 var inipath
= dirpath
/ "package.ini"
433 if inipath
.file_exists
then
434 ini
= new ConfigTree(inipath
)
438 # No ini, multiple course of action
440 # The root of the directory hierarchy in the file system.
446 # Special stopper `packages.ini`
447 if (dirpath
/"packages.ini").file_exists
then
448 # dirpath cannot be a package since it is a package directory
453 # check the parent directory (if it does not contain the stopper file)
454 var parentpath
= dirpath
.join_path
("..").simplify_path
455 var stopper
= parentpath
/ "packages.ini"
456 if not stopper
.file_exists
then
457 # Recursively get the parent group
458 parent
= get_mgroup
(parentpath
)
459 if parent
== null then
460 # Parent is not a group, thus we are not a group either
468 if parent
== null then
469 # no parent, thus new package
470 if ini
!= null then pn
= ini
["package.name"] or else pn
471 var mpackage
= new MPackage(pn
, model
)
472 mgroup
= new MGroup(pn
, mpackage
, null) # same name for the root group
473 mpackage
.root
= mgroup
474 toolcontext
.info
("found package `{mpackage}` at {dirpath}", 2)
477 mgroup
= new MGroup(pn
, parent
.mpackage
, parent
)
478 toolcontext
.info
("found sub group `{mgroup.full_name}` at {dirpath}", 2)
481 # search documentation
482 # in src first so the documentation of the package code can be distinct for the documentation of the package usage
483 var readme
= dirpath
.join_path
("README.md")
484 if not readme
.file_exists
then readme
= dirpath
.join_path
("README")
485 if readme
.file_exists
then
486 var mdoc
= load_markdown
(readme
)
488 mdoc
.original_mentity
= mgroup
491 mgroup
.filepath
= dirpath
492 mgroups
[rdp
] = mgroup
496 # Load a markdown file as a documentation object
497 fun load_markdown
(filepath
: String): MDoc
499 var s
= new FileReader.open
(filepath
)
500 var lines
= new Array[String]
501 var line_starts
= new Array[Int]
504 var line
= s
.read_line
507 len
+= line
.length
+ 1
510 var source
= new SourceFile.from_string
(filepath
, lines
.join
("\n"))
511 source
.line_starts
.add_all line_starts
512 var mdoc
= new MDoc(new Location(source
, 1, lines
.length
, 0, 0))
513 mdoc
.content
.add_all
(lines
)
517 # Force the identification of all ModulePath of the group and sub-groups in the file system.
519 # When a group is scanned, its sub-groups hierarchy is filled (see `MGroup::in_nesting`)
520 # and the potential modules (and nested modules) are identified (see `MGroup::module_paths`).
522 # Basically, this recursively call `get_mgroup` and `identify_file` on each directory entry.
524 # No-op if the group was already scanned (see `MGroup::scanned`).
525 fun scan_group
(mgroup
: MGroup) do
526 if mgroup
.scanned
then return
527 mgroup
.scanned
= true
528 var p
= mgroup
.filepath
529 # a virtual group has nothing to scan
530 if p
== null then return
533 var g
= get_mgroup
(fp
)
534 # Recursively scan for groups of the same package
535 if g
!= null and g
.mpackage
== mgroup
.mpackage
then
542 # Transform relative paths (starting with '../') into absolute paths
543 private fun module_absolute_path
(path
: String): String do
547 # Try to load a module AST using a path.
548 # Display an error if there is a problem (IO / lexer / parser) and return null
549 fun load_module_ast
(filename
: String): nullable AModule
551 if not filename
.has_suffix
(".nit") then
552 self.toolcontext
.error
(null, "Error: file `{filename}` is not a valid nit module.")
555 if not filename
.file_exists
then
556 self.toolcontext
.error
(null, "Error: file `{filename}` not found.")
560 self.toolcontext
.info
("load module {filename}", 2)
563 var file
= new FileReader.open
(filename
)
564 var lexer
= new Lexer(new SourceFile(filename
, file
))
565 var parser
= new Parser(lexer
)
566 var tree
= parser
.parse
569 # Handle lexer and parser error
570 var nmodule
= tree
.n_base
571 if nmodule
== null then
572 var neof
= tree
.n_eof
573 assert neof
isa AError
574 error
(neof
, neof
.message
)
581 # Remove Nit source files from a list of arguments.
583 # Items of `args` that can be loaded as a nit file will be removed from `args` and returned.
584 fun filter_nit_source
(args
: Array[String]): Array[String]
586 var keep
= new Array[String]
587 var res
= new Array[String]
589 var l
= identify_file
(a
)
601 # Try to load a module using a path.
602 # Display an error if there is a problem (IO / lexer / parser) and return null.
603 # Note: usually, you do not need this method, use `get_mmodule_by_name` instead.
605 # The MModule is created however, the importation is not performed,
606 # therefore you should call `build_module_importation`.
607 fun load_module
(filename
: String): nullable AModule
609 # Look for the module
610 var file
= identify_file
(filename
)
612 if filename
.file_exists
then
613 toolcontext
.error
(null, "Error: `{filename}` is not a Nit source file.")
615 toolcontext
.error
(null, "Error: cannot find module `{filename}`.")
620 # Already known and loaded? then return it
621 var mmodule
= file
.mmodule
622 if mmodule
!= null then
623 return mmodule2nmodule
[mmodule
]
627 var nmodule
= load_module_ast
(file
.filepath
)
628 if nmodule
== null then return null # forward error
630 # build the mmodule and load imported modules
631 mmodule
= build_a_mmodule
(file
.mgroup
, file
.name
, nmodule
)
633 if mmodule
== null then return null # forward error
635 # Update the file information
636 file
.mmodule
= mmodule
641 # Injection of a new module without source.
642 # Used by the interpreter.
643 fun load_rt_module
(parent
: nullable MModule, nmodule
: AModule, mod_name
: String): nullable AModule
648 if parent
!= null then mgroup
= parent
.mgroup
649 var mmodule
= new MModule(model
, mgroup
, mod_name
, nmodule
.location
)
650 nmodule
.mmodule
= mmodule
651 nmodules
.add
(nmodule
)
652 self.mmodule2nmodule
[mmodule
] = nmodule
654 if parent
!= null then
655 var imported_modules
= new Array[MModule]
656 imported_modules
.add
(parent
)
657 mmodule
.set_visibility_for
(parent
, intrude_visibility
)
658 mmodule
.set_imported_mmodules
(imported_modules
)
660 build_module_importation
(nmodule
)
666 # Visit the AST and create the `MModule` object
667 private fun build_a_mmodule
(mgroup
: nullable MGroup, mod_name
: String, nmodule
: AModule): nullable MModule
669 # Check the module name
670 var decl
= nmodule
.n_moduledecl
672 var decl_name
= decl
.n_name
.n_id
.text
673 if decl_name
!= mod_name
then
674 error
(decl
.n_name
, "Error: module name mismatch; declared {decl_name} file named {mod_name}.")
678 # Check for conflicting module names in the package
679 if mgroup
!= null then
680 var others
= model
.get_mmodules_by_name
(mod_name
)
681 if others
!= null then for other
in others
do
682 if other
.mgroup
!= null and other
.mgroup
.mpackage
== mgroup
.mpackage
then
684 if decl
== null then node
= nmodule
else node
= decl
.n_name
685 error
(node
, "Error: a module named `{other.full_name}` already exists at {other.location}.")
692 var mmodule
= new MModule(model
, mgroup
, mod_name
, nmodule
.location
)
693 nmodule
.mmodule
= mmodule
694 nmodules
.add
(nmodule
)
695 self.mmodule2nmodule
[mmodule
] = nmodule
697 var source
= nmodule
.location
.file
698 if source
!= null then
699 assert source
.mmodule
== null
700 source
.mmodule
= mmodule
704 # Extract documentation
705 var ndoc
= decl
.n_doc
707 var mdoc
= ndoc
.to_mdoc
709 mdoc
.original_mentity
= mmodule
711 advice
(decl
, "missing-doc", "Documentation warning: Undocumented module `{mmodule}`")
713 # Is the module a test suite?
714 mmodule
.is_test_suite
= not decl
.get_annotations
("test_suite").is_empty
720 # Resolve the module identification for a given `AModuleName`.
722 # This method handles qualified names as used in `AModuleName`.
723 fun seach_module_by_amodule_name
(n_name
: AModuleName, mgroup
: nullable MGroup): nullable ModulePath
725 var mod_name
= n_name
.n_id
.text
727 # If a quad is given, we ignore the starting group (go from path)
728 if n_name
.n_quad
!= null then mgroup
= null
730 # If name not qualified, just search the name
731 if n_name
.n_path
.is_empty
then
732 # Fast search if no n_path
733 return search_mmodule_by_name
(n_name
, mgroup
, mod_name
)
736 # If qualified and in a group
737 if mgroup
!= null then
738 # First search in the package
739 var r
= mgroup
.mpackage
.root
742 # Get all modules with the final name
743 var res
= r
.mmodule_paths_by_name
(mod_name
)
744 # Filter out the name that does not match the qualifiers
745 res
= [for x
in res
do if match_amodulename
(n_name
, x
) then x
]
746 if res
.not_empty
then
747 if res
.length
> 1 then
748 error
(n_name
, "Error: conflicting module files for `{mod_name}`: `{res.join(",")}`")
754 # If no module yet, then assume that the first element of the path
755 # Is to be searched in the path.
756 var root_name
= n_name
.n_path
.first
.text
757 var roots
= search_group_in_paths
(root_name
, paths
)
758 if roots
.is_empty
then
759 error
(n_name
, "Error: cannot find `{root_name}`. Tried: {paths.join(", ")}.")
763 var res
= new ArraySet[ModulePath]
765 # Then, for each root, collect modules that matches the qualifiers
767 var root_res
= r
.mmodule_paths_by_name
(mod_name
)
768 for x
in root_res
do if match_amodulename
(n_name
, x
) then res
.add x
770 if res
.not_empty
then
771 if res
.length
> 1 then
772 error
(n_name
, "Error: conflicting module files for `{mod_name}`: `{res.join(",")}`")
776 # If still nothing, just call a basic search that will fail and will produce an error message
777 error
(n_name
, "Error: cannot find module `{mod_name}` from `{root_name}`. Tried: {paths.join(", ")}.")
781 # Is elements of `n_name` correspond to the group nesting of `m`?
783 # Basically it check that `bar::foo` matches `bar/foo.nit` and `bar/baz/foo.nit`
784 # but not `baz/foo.nit` nor `foo/bar.nit`
786 # Is used by `seach_module_by_amodule_name` to validate qualified names.
787 private fun match_amodulename
(n_name
: AModuleName, m
: ModulePath): Bool
789 var g
: nullable MGroup = m
.mgroup
790 for grp
in n_name
.n_path
.reverse_iterator
do
791 while g
!= null and grp
.text
!= g
.name
do
798 # Analyze the module importation and fill the module_importation_hierarchy
800 # Unless you used `load_module`, the importation is already done and this method does a no-op.
801 fun build_module_importation
(nmodule
: AModule)
803 if nmodule
.is_importation_done
then return
804 nmodule
.is_importation_done
= true
805 var mmodule
= nmodule
.mmodule
.as(not null)
807 var imported_modules
= new Array[MModule]
808 for aimport
in nmodule
.n_imports
do
809 # Do not imports conditional
810 var atconditionals
= aimport
.get_annotations
("conditional")
811 if atconditionals
.not_empty
then continue
814 if not aimport
isa AStdImport then
818 # Load the imported module
819 var suppath
= seach_module_by_amodule_name
(aimport
.n_name
, mmodule
.mgroup
)
820 if suppath
== null then
821 nmodule
.mmodule
= null # invalidate the module
822 continue # Skip error
824 var sup
= load_module_path
(suppath
)
826 nmodule
.mmodule
= null # invalidate the module
827 continue # Skip error
830 aimport
.mmodule
= sup
831 imported_modules
.add
(sup
)
832 var mvisibility
= aimport
.n_visibility
.mvisibility
833 if mvisibility
== protected_visibility
then
834 error
(aimport
.n_visibility
, "Error: only properties can be protected.")
835 nmodule
.mmodule
= null # invalidate the module
838 if sup
== mmodule
then
839 error
(aimport
.n_name
, "Error: dependency loop in module {mmodule}.")
840 nmodule
.mmodule
= null # invalidate the module
842 if sup
.in_importation
< mmodule
then
843 error
(aimport
.n_name
, "Error: dependency loop between modules {mmodule} and {sup}.")
844 nmodule
.mmodule
= null # invalidate the module
847 mmodule
.set_visibility_for
(sup
, mvisibility
)
850 var mod_name
= "core"
851 var sup
= self.get_mmodule_by_name
(nmodule
, null, mod_name
)
853 nmodule
.mmodule
= null # invalidate the module
855 imported_modules
.add
(sup
)
856 mmodule
.set_visibility_for
(sup
, public_visibility
)
860 # Declare conditional importation
861 for aimport
in nmodule
.n_imports
do
862 if not aimport
isa AStdImport then continue
863 var atconditionals
= aimport
.get_annotations
("conditional")
864 if atconditionals
.is_empty
then continue
866 var suppath
= seach_module_by_amodule_name
(aimport
.n_name
, mmodule
.mgroup
)
867 if suppath
== null then continue # skip error
869 for atconditional
in atconditionals
do
870 var nargs
= atconditional
.n_args
871 if nargs
.is_empty
then
872 error
(atconditional
, "Syntax Error: `conditional` expects module identifiers as arguments.")
877 var rule
= new Array[Object]
879 # First element is the goal, thus
882 # Second element is the first condition, that is to be a client of the current module
885 # Other condition are to be also a client of each modules indicated as arguments of the annotation
889 error
(narg
, "Syntax Error: `conditional` expects module identifier as arguments.")
893 var mp
= search_mmodule_by_name
(narg
, mmodule
.mgroup
, id
)
894 if mp
== null then continue
899 conditional_importations
.add rule
903 mmodule
.set_imported_mmodules
(imported_modules
)
905 apply_conditional_importations
(mmodule
)
907 self.toolcontext
.info
("{mmodule} imports {mmodule.in_importation.direct_greaters.join(", ")}", 3)
909 # Force `core` to be public if imported
910 for sup
in mmodule
.in_importation
.greaters
do
911 if sup
.name
== "core" then
912 mmodule
.set_visibility_for
(sup
, public_visibility
)
916 # TODO: Correctly check for useless importation
918 var directs
= mmodule
.in_importation
.direct_greaters
919 for nim
in nmodule
.n_imports
do
920 if not nim
isa AStdImport then continue
922 if im
== null then continue
923 if directs
.has
(im
) then continue
924 # This generates so much noise that it is simpler to just comment it
925 #warning(nim, "Warning: possible useless importation of {im}")
929 # Global list of conditional importation rules.
931 # Each rule is a "Horn clause"-like sequence of modules.
932 # It means that the first module is the module to automatically import.
933 # The remaining modules are the conditions of the rule.
935 # Each module is either represented by a MModule (if the module is already loaded)
936 # or by a ModulePath (if the module is not yet loaded).
938 # Rules are declared by `build_module_importation` and are applied by `apply_conditional_importations`
939 # (and `build_module_importation` that calls it).
941 # TODO (when the loader will be rewritten): use a better representation and move up rules in the model.
942 private var conditional_importations
= new Array[SequenceRead[Object]]
944 # Extends the current importations according to imported rules about conditional importation
945 fun apply_conditional_importations
(mmodule
: MModule)
947 # Because a conditional importation may cause additional conditional importation, use a fixed point
948 # The rules are checked naively because we assume that it does not worth to be optimized
949 var check_conditional_importations
= true
950 while check_conditional_importations
do
951 check_conditional_importations
= false
953 for ci
in conditional_importations
do
955 for i
in [1..ci
.length
[ do
956 var rule_element
= ci
[i
]
957 # An element of a rule is either a MModule or a ModulePath
958 # We need the mmodule to resonate on the importation
960 if rule_element
isa MModule then
962 else if rule_element
isa ModulePath then
963 m
= rule_element
.mmodule
965 if m
== null then continue label
970 if not mmodule
.in_importation
.greaters
.has
(m
) then continue label
972 # Still here? It means that all conditions modules are loaded and imported
974 # Identify the module to automatically import
975 var suppath
= ci
.first
.as(ModulePath)
976 var sup
= load_module_path
(suppath
)
977 if sup
== null then continue
979 # Do nothing if already imported
980 if mmodule
.in_importation
.greaters
.has
(sup
) then continue label
983 self.toolcontext
.info
("{mmodule} conditionally imports {sup}", 3)
984 # TODO visibility rules (currently always public)
985 mmodule
.set_visibility_for
(sup
, public_visibility
)
986 # TODO linearization rules (currently added at the end in the order of the rules)
987 mmodule
.set_imported_mmodules
([sup
])
989 # Prepare to reapply the rules
990 check_conditional_importations
= true
995 # All the loaded modules
996 var nmodules
= new Array[AModule]
998 # Register the nmodule associated to each mmodule
1000 # Public clients need to use `mmodule2node` to access stuff.
1001 private var mmodule2nmodule
= new HashMap[MModule, AModule]
1003 # Retrieve the associated AST node of a mmodule.
1004 # This method is used to associate model entity with syntactic entities.
1006 # If the module is not associated with a node, returns null.
1007 fun mmodule2node
(mmodule
: MModule): nullable AModule
1009 return mmodule2nmodule
.get_or_null
(mmodule
)
1013 # File-system location of a module (file) that is identified but not always loaded.
1015 # The name of the module
1016 # (it's the basename of the filepath)
1019 # The human path of the module
1020 var filepath
: String
1022 # The group (and the package) of the possible module
1025 # The loaded module (if any)
1026 var mmodule
: nullable MModule = null
1028 redef fun to_s
do return filepath
1031 redef class MPackage
1032 # The associated `.ini` file, if any
1034 # The `ini` file is given as is and might contain invalid or missing information.
1036 # Some packages, like stand-alone packages or virtual packages have no `ini` file associated.
1037 var ini
: nullable ConfigTree = null
1041 # Modules paths associated with the group
1042 var module_paths
= new Array[ModulePath]
1044 # Is the group interesting for a final user?
1046 # Groups are mandatory in the model but for simple packages they are not
1047 # always interesting.
1049 # A interesting group has, at least, one of the following true:
1051 # * it has 2 modules or more
1052 # * it has a subgroup
1053 # * it has a documentation
1054 fun is_interesting
: Bool
1056 return module_paths
.length
> 1 or
1057 mmodules
.length
> 1 or
1058 not in_nesting
.direct_smallers
.is_empty
or
1060 (mmodules
.length
== 1 and default_mmodule
== null)
1063 # Are files and directories in self scanned?
1065 # See `ModelBuilder::scan_group`.
1068 # Return the modules in self and subgroups named `name`.
1070 # If `self` is not scanned (see `ModelBuilder::scan_group`) the
1071 # results might be partial.
1072 fun mmodule_paths_by_name
(name
: String): Array[ModulePath]
1074 var res
= new Array[ModulePath]
1075 for g
in in_nesting
.smallers
do
1076 for mp
in g
.module_paths
do
1077 if mp
.name
== name
then
1086 redef class SourceFile
1087 # Associated mmodule, once created
1088 var mmodule
: nullable MModule = null
1091 redef class AStdImport
1092 # The imported module once determined
1093 var mmodule
: nullable MModule = null
1097 # The associated MModule once build by a `ModelBuilder`
1098 var mmodule
: nullable MModule
1099 # Flag that indicate if the importation is already completed
1100 var is_importation_done
: Bool = false