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 var le
= last_loader_error
159 toolcontext
.error
(null, le
)
160 else if a
.file_exists
then
161 toolcontext
.error
(null, "Error: `{a}` is not a Nit source file.")
163 toolcontext
.error
(null, "Error: cannot find module `{a}`.")
173 # Load a bunch of modules and groups.
177 # * a path to a module, a group or a directory of packages.
178 # * a short name of a module or a group that are looked in the `paths` (-I)
180 # Then, for each entry, if it is:
182 # * a module, then is it parsed and returned.
183 # * a group then recursively all its modules are parsed.
184 # * a directory of packages then all the modules of all packages are parsed.
185 # * else an error is displayed.
187 # See `parse` for details.
188 fun parse_full
(names
: Sequence[String]): Array[MModule]
191 # Parse and recursively load
192 self.toolcontext
.info
("*** PARSE ***", 1)
193 var mmodules
= new ArraySet[MModule]
194 var scans
= scan_full
(names
)
195 for mmodule
in scans
do
196 var ast
= mmodule
.load
(self)
197 if ast
== null then continue # Skip error
201 self.toolcontext
.info
("*** END PARSE: {time1-time0} ***", 2)
203 self.toolcontext
.check_errors
205 if toolcontext
.opt_only_parse
.value
then
206 self.toolcontext
.info
("*** ONLY PARSE...", 1)
207 self.toolcontext
.quit
213 # The list of directories to search for top level modules
214 # The list is initially set with:
216 # * the toolcontext --path option
217 # * the NIT_PATH environment variable
218 # * `toolcontext.nit_dir`
219 # Path can be added (or removed) by the client
220 var paths
= new Array[String]
222 # Like (and used by) `get_mmodule_by_name` but does not force the parsing of the MModule (cf. `identify_module`)
223 fun search_mmodule_by_name
(anode
: nullable ANode, mgroup
: nullable MGroup, name
: String): nullable MModule
225 # First, look in groups
228 var r
= c
.mpackage
.root
231 var res
= r
.mmodules_by_name
(name
)
232 if res
.not_empty
then return res
.first
235 # Look at some known directories
236 var lookpaths
= self.paths
238 # Look in the directory of the group package also (even if not explicitly in the path)
239 if mgroup
!= null then
240 # path of the root group
241 var dirname
= mgroup
.mpackage
.root
.filepath
242 if dirname
!= null then
243 dirname
= dirname
.join_path
("..").simplify_path
244 if not lookpaths
.has
(dirname
) and dirname
.file_exists
then
245 lookpaths
= lookpaths
.to_a
246 lookpaths
.add
(dirname
)
252 if anode
!= null then loc
= anode
.hot_location
253 var candidate
= search_module_in_paths
(loc
, name
, lookpaths
)
255 if candidate
== null then
256 if mgroup
!= null then
257 error
(anode
, "Error: cannot find module `{name}` from `{mgroup.name}`. Tried: {lookpaths.join(", ")}.")
259 error
(anode
, "Error: cannot find module `{name}`. Tried: {lookpaths.join(", ")}.")
266 # Get a module by its short name; if required, the module is loaded, parsed and its hierarchies computed.
267 # If `mgroup` is set, then the module search starts from it up to the top level (see `paths`);
268 # if `mgroup` is null then the module is searched in the top level only.
269 # If no module exists or there is a name conflict, then an error on `anode` is displayed and null is returned.
270 fun get_mmodule_by_name
(anode
: nullable ANode, mgroup
: nullable MGroup, name
: String): nullable MModule
272 var mmodule
= search_mmodule_by_name
(anode
, mgroup
, name
)
273 if mmodule
== null then return null # Forward error
274 var ast
= mmodule
.load
(self)
275 if ast
== null then return null # Forward error
279 # Search a module `name` from path `lookpaths`.
280 # If found, the module is returned.
281 private fun search_module_in_paths
(location
: nullable Location, name
: String, lookpaths
: Collection[String]): nullable MModule
283 var res
= new ArraySet[MModule]
284 for dirname
in lookpaths
do
285 # Try a single module file
286 var mp
= identify_module
((dirname
/"{name}.nit").simplify_path
)
287 if mp
!= null then res
.add mp
288 # Try the default module of a group
289 var g
= identify_group
((dirname
/name
).simplify_path
)
292 res
.add_all g
.mmodules_by_name
(name
)
295 if res
.is_empty
then return null
296 if res
.length
> 1 then
297 toolcontext
.error
(location
, "Error: conflicting module files for `{name}`: `{[for x in res do x.filepath or else x.full_name].join("`, `")}`")
302 # Search groups named `name` from paths `lookpaths`.
303 private fun search_group_in_paths
(name
: String, lookpaths
: Collection[String]): ArraySet[MGroup]
305 var res
= new ArraySet[MGroup]
306 for dirname
in lookpaths
do
307 # try a single group directory
308 var mg
= identify_group
(dirname
/name
)
316 # Cache for `identify_module` by relative and real paths
317 private var identified_modules_by_path
= new HashMap[String, nullable MModule]
319 # All the currently identified modules.
320 # See `identify_module`.
322 # An identified module exists in the model but might be not yet parsed (no AST), or not yet analysed (no importation).
323 var identified_modules
= new Array[MModule]
325 # All the currently parsed modules.
327 # A parsed module exists in the model but might be not yet analysed (no importation).
328 var parsed_modules
= new Array[MModule]
330 # Some `loader` services are silent and return `null` on error.
332 # Those services can set `last_loader_error` to precise an specific error message.
333 # if `last_loader_error == null` then a generic error message can be used.
335 # See `identified_modules` and `identify_group` for details.
336 var last_loader_error
: nullable String = null
338 # Identify a source file and load the associated package and groups if required.
340 # This method does what the user expects when giving an argument to a Nit tool.
342 # * If `path` is an existing Nit source file (with the `.nit` extension),
343 # then the associated MModule is returned
344 # * If `path` is a directory (with a `/`),
345 # then the MModule of its default module is returned (if any)
346 # * If `path` is a simple identifier (eg. `digraph`),
347 # then the main module of the package `digraph` is searched in `paths` and returned.
349 # Silently return `null` if `path` does not exists or cannot be identified.
350 # If `null` is returned, `last_loader_error` can be set to a specific error message.
352 # On success, it returns a module that is possibly not yet parsed (no AST), or not yet analysed (no importation).
353 # If the module was already identified, or loaded, it is returned.
354 fun identify_module
(path
: String): nullable MModule
356 last_loader_error
= null
358 # special case for not a nit file
359 if not path
.has_suffix
(".nit") then do
360 # search dirless files in known -I paths
361 if not path
.chars
.has
('/') then
362 var res
= search_module_in_paths
(null, path
, self.paths
)
363 if res
!= null then return res
366 # Found nothing? maybe it is a group...
367 if path
.file_exists
then
368 var mgroup
= identify_group
(path
)
369 if mgroup
!= null then
370 var owner_path
= mgroup
.filepath
.join_path
(mgroup
.name
+ ".nit")
371 if owner_path
.file_exists
then
378 # Found nothing? maybe it is a qualified name
379 if path
.chars
.has
(':') then
380 var ids
= path
.split
("::")
381 var g
= identify_group
(ids
.first
)
384 var ms
= g
.mmodules_by_name
(ids
.last
)
388 if m
.full_name
== path
then
393 # Where there is only one or two names `foo::bar`
394 # then accept module that matches `foo::*::bar`
395 if ids
.length
<= 2 then
396 if ms
.length
== 1 then return ms
.first
397 if ms
.length
> 1 then
398 var l
= new Array[String]
401 if fp
!= null then fp
= " ({fp})" else fp
= ""
402 l
.add
"`{m.full_name}`{fp}"
404 last_loader_error
= "Error: conflicting module for `{path}`: {l.join(", ")} "
409 var bests
= new BestDistance[String](path
.length
/ 2)
410 # We found nothing. But propose something in the package?
411 for sg
in g
.mpackage
.mgroups
do
412 for m
in sg
.mmodules
do
413 var d
= path
.levenshtein_distance
(m
.full_name
)
414 bests
.update
(d
, m
.full_name
)
417 var last_loader_error
= "Error: cannot find module `{path}`."
418 if bests
.best_items
.not_empty
then
419 last_loader_error
+= " Did you mean " + bests
.best_items
.join
(", ", " or ") + "?"
421 self.last_loader_error
= last_loader_error
429 # Does the file exists?
430 if not path
.file_exists
then
434 # Fast track, the path is already known
435 if identified_modules_by_path
.has_key
(path
) then return identified_modules_by_path
[path
]
436 var rp
= module_absolute_path
(path
)
437 if identified_modules_by_path
.has_key
(rp
) then return identified_modules_by_path
[rp
]
439 var pn
= path
.basename
(".nit")
442 var mgrouppath
= path
.join_path
("..").simplify_path
443 var mgroup
= identify_group
(mgrouppath
)
445 if mgroup
!= null then
446 var mpackage
= mgroup
.mpackage
447 if not mpackage
.accept
(path
) then
449 toolcontext
.info
("module `{path}` excluded from package `{mpackage}`", 2)
452 if mgroup
== null then
454 var loc
= new Location.opaque_file
(path
)
455 var mpackage
= new MPackage(pn
, model
, loc
)
456 mgroup
= new MGroup(pn
, loc
, mpackage
, null) # same name for the root group
457 mpackage
.root
= mgroup
458 toolcontext
.info
("found singleton package `{pn}` at {path}", 2)
460 # Attach homonymous `ini` file to the package
461 var inipath
= path
.dirname
/ "{pn}.ini"
462 if inipath
.file_exists
then
463 var ini
= new ConfigTree(inipath
)
468 var loc
= new Location.opaque_file
(path
)
469 var res
= new MModule(model
, mgroup
, pn
, loc
)
471 identified_modules_by_path
[rp
] = res
472 identified_modules_by_path
[path
] = res
473 identified_modules
.add
(res
)
478 private var mgroups
= new HashMap[String, nullable MGroup]
480 # Return the mgroup associated to a directory path.
481 # If the directory is not a group null is returned.
483 # Silently return `null` if `dirpath` does not exists, is not a directory,
484 # cannot be identified or cannot be attached to a mpackage.
485 # If `null` is returned, `last_loader_error` can be set to a specific error message.
487 # Note: `paths` is also used to look for mgroups
488 fun identify_group
(dirpath
: String): nullable MGroup
491 last_loader_error
= null
493 var stat
= dirpath
.file_stat
495 if stat
== null or not stat
.is_dir
then do
496 # search dirless directories in known -I paths
497 if dirpath
.chars
.has
('/') then return null
499 var try
= p
/ dirpath
509 # Filter out non-directories
510 if not stat
.is_dir
then
511 last_loader_error
= "Error: `{dirpath}` is not a directory."
515 # Fast track, the path is already known
516 var rdp
= module_absolute_path
(dirpath
)
517 if mgroups
.has_key
(rdp
) then
521 # By default, the name of the package or group is the base_name of the directory
522 var pn
= rdp
.basename
524 # Check `package.ini` that indicate a package
527 var inipath
= dirpath
/ "package.ini"
528 if inipath
.file_exists
then
529 ini
= new ConfigTree(inipath
)
533 # No ini, multiple course of action
535 # The root of the directory hierarchy in the file system.
538 last_loader_error
= "Error: `{dirpath}` is not a Nit package."
542 # Special stopper `packages.ini`
543 if (dirpath
/"packages.ini").file_exists
then
544 # dirpath cannot be a package since it is a package directory
546 last_loader_error
= "Error: `{dirpath}` is not a Nit package."
550 # check the parent directory (if it does not contain the stopper file)
551 var parentpath
= dirpath
.join_path
("..").simplify_path
552 var stopper
= parentpath
/ "packages.ini"
553 if not stopper
.file_exists
then
554 # Recursively get the parent group
555 parent
= identify_group
(parentpath
)
556 if parent
!= null then do
557 var mpackage
= parent
.mpackage
558 if not mpackage
.accept
(dirpath
) then
559 toolcontext
.info
("directory `{dirpath}` excluded from package `{mpackage}`", 2)
563 if parent
== null then
564 # Parent is not a group, thus we are not a group either
566 last_loader_error
= "Error: `{dirpath}` is not a Nit package."
572 var loc
= new Location.opaque_file
(dirpath
)
574 if parent
== null then
575 # no parent, thus new package
576 if ini
!= null then pn
= ini
["package.name"] or else pn
577 var mpackage
= new MPackage(pn
, model
, loc
)
578 mgroup
= new MGroup(pn
, loc
, mpackage
, null) # same name for the root group
579 mpackage
.root
= mgroup
580 toolcontext
.info
("found package `{mpackage}` at {dirpath}", 2)
583 mgroup
= new MGroup(pn
, loc
, parent
.mpackage
, parent
)
584 toolcontext
.info
("found sub group `{mgroup.full_name}` at {dirpath}", 2)
587 # search documentation
588 # in src first so the documentation of the package code can be distinct for the documentation of the package usage
589 var readme
= dirpath
.join_path
("README.md")
590 if not readme
.file_exists
then readme
= dirpath
.join_path
("README")
591 if readme
.file_exists
then
592 var mdoc
= load_markdown
(readme
)
594 mdoc
.original_mentity
= mgroup
597 mgroups
[rdp
] = mgroup
601 # Load a markdown file as a documentation object
602 fun load_markdown
(filepath
: String): MDoc
604 var s
= new FileReader.open
(filepath
)
605 var lines
= new Array[String]
606 var line_starts
= new Array[Int]
609 var line
= s
.read_line
612 len
+= line
.length
+ 1
615 var source
= new SourceFile.from_string
(filepath
, lines
.join
("\n"))
616 source
.line_starts
.add_all line_starts
617 var mdoc
= new MDoc(new Location(source
, 1, lines
.length
, 0, 0))
618 mdoc
.content
.add_all
(lines
)
622 # Force the identification of all MModule of the group and sub-groups in the file system.
624 # When a group is scanned, its sub-groups hierarchy is filled (see `MGroup::in_nesting`)
625 # and the potential modules (and nested modules) are identified (see `MGroup::modules`).
627 # Basically, this recursively call `identify_group` and `identify_module` on each directory entry.
629 # No-op if the group was already scanned (see `MGroup::scanned`).
630 fun scan_group
(mgroup
: MGroup) do
631 if mgroup
.scanned
then return
632 mgroup
.scanned
= true
633 var p
= mgroup
.filepath
634 # a virtual group has nothing to scan
635 if p
== null then return
637 alpha_comparator
.sort
(files
)
640 var g
= identify_group
(fp
)
641 # Recursively scan for groups of the same package
644 else if g
.mpackage
== mgroup
.mpackage
then
650 # Transform relative paths (starting with '../') into absolute paths
651 private fun module_absolute_path
(path
: String): String do
655 # Try to load a module AST using a path.
656 # Display an error if there is a problem (IO / lexer / parser) and return null
658 # The AST is loaded as is total independence of the model and its entities.
660 # AST are not cached or reused thus a new AST is returned on success.
661 fun load_module_ast
(filename
: String): nullable AModule
663 if not filename
.has_suffix
(".nit") then
664 self.toolcontext
.error
(null, "Error: file `{filename}` is not a valid nit module.")
667 if not filename
.file_exists
then
668 self.toolcontext
.error
(null, "Error: file `{filename}` not found.")
672 self.toolcontext
.info
("load module {filename}", 2)
675 var file
= new FileReader.open
(filename
)
676 var lexer
= new Lexer(new SourceFile(filename
, file
))
677 var parser
= new Parser(lexer
)
678 var tree
= parser
.parse
681 # Handle lexer and parser error
682 var nmodule
= tree
.n_base
683 if nmodule
== null then
684 var neof
= tree
.n_eof
685 assert neof
isa AError
686 error
(neof
, neof
.message
)
693 # Remove Nit source files from a list of arguments.
695 # Items of `args` that can be loaded as a nit file will be removed from `args` and returned.
696 fun filter_nit_source
(args
: Array[String]): Array[String]
698 var keep
= new Array[String]
699 var res
= new Array[String]
701 var stat
= a
.to_path
.stat
702 if stat
!= null and stat
.is_dir
then
706 var l
= identify_module
(a
)
718 # Try to load a module using a path.
719 # Display an error if there is a problem (IO / lexer / parser) and return null.
720 # Note: usually, you do not need this method, use `get_mmodule_by_name` instead.
722 # The MModule is located, created, parsed and the importation is performed.
723 fun load_module
(filename
: String): nullable AModule
725 # Look for the module
726 var mmodule
= identify_module
(filename
)
727 if mmodule
== null then
728 var le
= last_loader_error
730 toolcontext
.error
(null, le
)
731 else if filename
.file_exists
then
732 toolcontext
.error
(null, "Error: `{filename}` is not a Nit source file.")
734 toolcontext
.error
(null, "Error: cannot find module `{filename}`.")
740 return mmodule
.load
(self)
743 # Injection of a new module without source.
744 # Used by the interpreter.
745 fun load_rt_module
(parent
: nullable MModule, nmodule
: AModule, mod_name
: String): nullable MModule
750 if parent
!= null then mgroup
= parent
.mgroup
751 var mmodule
= new MModule(model
, mgroup
, mod_name
, nmodule
.location
)
752 nmodule
.mmodule
= mmodule
753 nmodules
.add
(nmodule
)
754 parsed_modules
.add mmodule
755 self.mmodule2nmodule
[mmodule
] = nmodule
757 if parent
!= null then
758 var imported_modules
= new Array[MModule]
759 imported_modules
.add
(parent
)
760 mmodule
.set_visibility_for
(parent
, intrude_visibility
)
761 mmodule
.set_imported_mmodules
(imported_modules
)
763 build_module_importation
(nmodule
)
768 # Visit the AST and create the `MModule` object
769 private fun build_a_mmodule
(mgroup
: nullable MGroup, nmodule
: AModule)
771 var mmodule
= nmodule
.mmodule
772 assert mmodule
!= null
774 # Check the module name
775 var decl
= nmodule
.n_moduledecl
777 var decl_name
= decl
.n_name
.n_id
.text
778 if decl_name
!= mmodule
.name
then
779 warning
(decl
.n_name
, "module-name-mismatch", "Error: module name mismatch; declared {decl_name} file named {mmodule.name}.")
783 # Check for conflicting module names in the package
784 if mgroup
!= null then
785 var others
= model
.get_mmodules_by_name
(mmodule
.name
)
786 if others
!= null then for other
in others
do
787 if other
!= mmodule
and mmodule2nmodule
.has_key
(mmodule
) and other
.mgroup
!= null and other
.mgroup
.mpackage
== mgroup
.mpackage
then
789 if decl
== null then node
= nmodule
else node
= decl
.n_name
790 error
(node
, "Error: a module named `{other.full_name}` already exists at {other.location}.")
796 nmodules
.add
(nmodule
)
797 self.mmodule2nmodule
[mmodule
] = nmodule
799 var source
= nmodule
.location
.file
800 if source
!= null then
801 assert source
.mmodule
== null
802 source
.mmodule
= mmodule
806 # Extract documentation
807 var ndoc
= decl
.n_doc
809 var mdoc
= ndoc
.to_mdoc
811 mdoc
.original_mentity
= mmodule
813 # Is the module a test suite?
814 mmodule
.is_test_suite
= not decl
.get_annotations
("test_suite").is_empty
815 # Is the module generated?
816 mmodule
.is_generated
= not decl
.get_annotations
("generated").is_empty
820 # Resolve the module identification for a given `AModuleName`.
822 # This method handles qualified names as used in `AModuleName`.
823 fun seach_module_by_amodule_name
(n_name
: AModuleName, mgroup
: nullable MGroup): nullable MModule
825 var mod_name
= n_name
.n_id
.text
827 # If a quad is given, we ignore the starting group (go from path)
828 if n_name
.n_quad
!= null then mgroup
= null
830 # If name not qualified, just search the name
831 if n_name
.n_path
.is_empty
then
832 # Fast search if no n_path
833 return search_mmodule_by_name
(n_name
, mgroup
, mod_name
)
836 # If qualified and in a group
837 if mgroup
!= null then
838 # First search in the package
839 var r
= mgroup
.mpackage
.root
842 # Get all modules with the final name
843 var res
= r
.mmodules_by_name
(mod_name
)
844 # Filter out the name that does not match the qualifiers
845 res
= [for x
in res
do if match_amodulename
(n_name
, x
) then x
]
846 if res
.not_empty
then
847 if res
.length
> 1 then
848 error
(n_name
, "Error: conflicting module files for `{mod_name}`: `{[for x in res do x.filepath or else x.full_name].join("`, `")}`")
854 # If no module yet, then assume that the first element of the path
855 # Is to be searched in the path.
856 var root_name
= n_name
.n_path
.first
.text
857 var roots
= search_group_in_paths
(root_name
, paths
)
858 if roots
.is_empty
then
859 error
(n_name
, "Error: cannot find `{root_name}`. Tried: {paths.join(", ")}.")
863 var res
= new ArraySet[MModule]
865 # Then, for each root, collect modules that matches the qualifiers
867 var root_res
= r
.mmodules_by_name
(mod_name
)
868 for x
in root_res
do if match_amodulename
(n_name
, x
) then res
.add x
870 if res
.not_empty
then
871 if res
.length
> 1 then
872 error
(n_name
, "Error: conflicting module files for `{mod_name}`: `{[for x in res do x.filepath or else x.full_name].join("`, `")}`")
876 # If still nothing, just call a basic search that will fail and will produce an error message
877 error
(n_name
, "Error: cannot find module `{mod_name}` from `{root_name}`. Tried: {paths.join(", ")}.")
881 # Is elements of `n_name` correspond to the group nesting of `m`?
883 # Basically it check that `bar::foo` matches `bar/foo.nit` and `bar/baz/foo.nit`
884 # but not `baz/foo.nit` nor `foo/bar.nit`
886 # Is used by `seach_module_by_amodule_name` to validate qualified names.
887 private fun match_amodulename
(n_name
: AModuleName, m
: MModule): Bool
889 var g
: nullable MGroup = m
.mgroup
890 for grp
in n_name
.n_path
.reverse_iterator
do
891 while g
!= null and grp
.text
!= g
.name
do
898 # Analyze the module importation and fill the module_importation_hierarchy
900 # If the importation was already done (`nmodule.is_importation_done`), this method does a no-op.
902 # REQUIRE `nmodule.mmodule != null`
903 # ENSURE `nmodule.is_importation_done`
904 fun build_module_importation
(nmodule
: AModule)
906 if nmodule
.is_importation_done
then return
907 nmodule
.is_importation_done
= true
908 var mmodule
= nmodule
.mmodule
.as(not null)
910 var imported_modules
= new Array[MModule]
911 for aimport
in nmodule
.n_imports
do
912 # Do not imports conditional
913 var atconditionals
= aimport
.get_annotations
("conditional")
914 if atconditionals
.not_empty
then continue
917 if not aimport
isa AStdImport then
921 # Load the imported module
922 var sup
= seach_module_by_amodule_name
(aimport
.n_name
, mmodule
.mgroup
)
924 mmodule
.is_broken
= true
925 nmodule
.mmodule
= null # invalidate the module
926 continue # Skip error
928 var ast
= sup
.load
(self)
930 mmodule
.is_broken
= true
931 nmodule
.mmodule
= null # invalidate the module
932 continue # Skip error
935 aimport
.mmodule
= sup
936 imported_modules
.add
(sup
)
937 var mvisibility
= aimport
.n_visibility
.mvisibility
938 if mvisibility
== protected_visibility
then
939 mmodule
.is_broken
= true
940 error
(aimport
.n_visibility
, "Error: only properties can be protected.")
941 mmodule
.is_broken
= true
942 nmodule
.mmodule
= null # invalidate the module
945 if sup
== mmodule
then
946 error
(aimport
.n_name
, "Error: dependency loop in module {mmodule}.")
947 mmodule
.is_broken
= true
948 nmodule
.mmodule
= null # invalidate the module
950 if sup
.in_importation
< mmodule
then
951 error
(aimport
.n_name
, "Error: dependency loop between modules {mmodule} and {sup}.")
952 mmodule
.is_broken
= true
953 nmodule
.mmodule
= null # invalidate the module
956 mmodule
.set_visibility_for
(sup
, mvisibility
)
959 var mod_name
= "core"
960 var sup
= self.get_mmodule_by_name
(nmodule
, null, mod_name
)
962 mmodule
.is_broken
= true
963 nmodule
.mmodule
= null # invalidate the module
965 imported_modules
.add
(sup
)
966 mmodule
.set_visibility_for
(sup
, public_visibility
)
970 # Declare conditional importation
971 for aimport
in nmodule
.n_imports
do
972 if not aimport
isa AStdImport then continue
973 var atconditionals
= aimport
.get_annotations
("conditional")
974 if atconditionals
.is_empty
then continue
976 var suppath
= seach_module_by_amodule_name
(aimport
.n_name
, mmodule
.mgroup
)
977 if suppath
== null then continue # skip error
979 for atconditional
in atconditionals
do
980 var nargs
= atconditional
.n_args
981 if nargs
.is_empty
then
982 error
(atconditional
, "Syntax Error: `conditional` expects module identifiers as arguments.")
987 var rule
= new Array[MModule]
989 # First element is the goal, thus
992 # Second element is the first condition, that is to be a client of the current module
995 # Other condition are to be also a client of each modules indicated as arguments of the annotation
999 error
(narg
, "Syntax Error: `conditional` expects module identifier as arguments.")
1003 var mp
= search_mmodule_by_name
(narg
, mmodule
.mgroup
, id
)
1004 if mp
== null then continue
1009 conditional_importations
.add rule
1013 mmodule
.set_imported_mmodules
(imported_modules
)
1015 apply_conditional_importations
(mmodule
)
1017 self.toolcontext
.info
("{mmodule} imports {mmodule.in_importation.direct_greaters.join(", ")}", 3)
1019 # Force `core` to be public if imported
1020 for sup
in mmodule
.in_importation
.greaters
do
1021 if sup
.name
== "core" then
1022 mmodule
.set_visibility_for
(sup
, public_visibility
)
1026 # TODO: Correctly check for useless importation
1027 # It is even doable?
1028 var directs
= mmodule
.in_importation
.direct_greaters
1029 for nim
in nmodule
.n_imports
do
1030 if not nim
isa AStdImport then continue
1031 var im
= nim
.mmodule
1032 if im
== null then continue
1033 if directs
.has
(im
) then continue
1034 # This generates so much noise that it is simpler to just comment it
1035 #warning(nim, "Warning: possible useless importation of {im}")
1039 # Global list of conditional importation rules.
1041 # Each rule is a "Horn clause"-like sequence of modules.
1042 # It means that the first module is the module to automatically import.
1043 # The remaining modules are the conditions of the rule.
1045 # Rules are declared by `build_module_importation` and are applied by `apply_conditional_importations`
1046 # (and `build_module_importation` that calls it).
1048 # TODO (when the loader will be rewritten): use a better representation and move up rules in the model.
1049 var conditional_importations
= new Array[SequenceRead[MModule]]
1051 # Extends the current importations according to imported rules about conditional importation
1052 fun apply_conditional_importations
(mmodule
: MModule)
1054 # Because a conditional importation may cause additional conditional importation, use a fixed point
1055 # The rules are checked naively because we assume that it does not worth to be optimized
1056 var check_conditional_importations
= true
1057 while check_conditional_importations
do
1058 check_conditional_importations
= false
1060 for ci
in conditional_importations
do
1062 for i
in [1..ci
.length
[ do
1065 if mmodule
== m
or not mmodule
.in_importation
.greaters
.has
(m
) then continue label
1067 # Still here? It means that all conditions modules are loaded and imported
1069 # Identify the module to automatically import
1071 var ast
= sup
.load
(self)
1072 if ast
== null then continue
1074 # Do nothing if already imported
1075 if mmodule
.in_importation
.greaters
.has
(sup
) then continue label
1078 self.toolcontext
.info
("{mmodule} conditionally imports {sup}", 3)
1079 # TODO visibility rules (currently always public)
1080 mmodule
.set_visibility_for
(sup
, public_visibility
)
1081 # TODO linearization rules (currently added at the end in the order of the rules)
1082 mmodule
.set_imported_mmodules
([sup
])
1084 # Prepare to reapply the rules
1085 check_conditional_importations
= true
1090 # All the loaded modules
1091 var nmodules
= new Array[AModule]
1093 # Register the nmodule associated to each mmodule
1095 # Public clients need to use `mmodule2node` to access stuff.
1096 private var mmodule2nmodule
= new HashMap[MModule, AModule]
1098 # Retrieve the associated AST node of a mmodule.
1099 # This method is used to associate model entity with syntactic entities.
1101 # If the module is not associated with a node, returns null.
1102 fun mmodule2node
(mmodule
: MModule): nullable AModule
1104 return mmodule2nmodule
.get_or_null
(mmodule
)
1109 # Force the parsing of the module using `modelbuilder`.
1111 # If the module was already parsed, the existing ASI is returned.
1112 # Else the source file is loaded, and parsed and some
1114 # The importation is not done by this
1116 # REQUIRE: `filepath != null`
1117 # ENSURE: `modelbuilder.parsed_modules.has(self)`
1118 fun parse
(modelbuilder
: ModelBuilder): nullable AModule
1120 # Already known and loaded? then return it
1121 var nmodule
= modelbuilder
.mmodule2nmodule
.get_or_null
(self)
1122 if nmodule
!= null then return nmodule
1124 var filepath
= self.filepath
1125 assert filepath
!= null
1127 nmodule
= modelbuilder
.load_module_ast
(filepath
)
1128 if nmodule
== null then return null # forward error
1131 nmodule
.mmodule
= self
1132 self.location
= nmodule
.location
1133 modelbuilder
.build_a_mmodule
(mgroup
, nmodule
)
1135 modelbuilder
.parsed_modules
.add
self
1139 # Parse and process importation of a given MModule.
1141 # Basically chains `parse` and `build_module_importation`.
1142 fun load
(modelbuilder
: ModelBuilder): nullable AModule
1144 var nmodule
= parse
(modelbuilder
)
1145 if nmodule
== null then return null
1147 modelbuilder
.build_module_importation
(nmodule
)
1152 redef class MPackage
1153 # The associated `.ini` file, if any
1155 # The `ini` file is given as is and might contain invalid or missing information.
1157 # Some packages, like stand-alone packages or virtual packages have no `ini` file associated.
1158 var ini
: nullable ConfigTree = null
1160 # Array of relative source paths excluded according to the `source.exclude` key of the `ini`
1161 var excludes
: nullable Array[String] is lazy
do
1163 if ini
== null then return null
1164 var exclude
= ini
["source.exclude"]
1165 if exclude
== null then return null
1166 var excludes
= exclude
.split
(":")
1170 # Does the source inclusion/inclusion rules of the package `ini` accept such path?
1171 fun accept
(filepath
: String): Bool
1173 var excludes
= self.excludes
1174 if excludes
!= null then
1175 var relpath
= root
.filepath
.relpath
(filepath
)
1176 if excludes
.has
(relpath
) then return false
1183 # Is the group interesting for a final user?
1185 # Groups are mandatory in the model but for simple packages they are not
1186 # always interesting.
1188 # A interesting group has, at least, one of the following true:
1190 # * it has 2 modules or more
1191 # * it has a subgroup
1192 # * it has a documentation
1193 fun is_interesting
: Bool
1195 return mmodules
.length
> 1 or
1196 not in_nesting
.direct_smallers
.is_empty
or
1198 (mmodules
.length
== 1 and default_mmodule
== null)
1201 # Are files and directories in self scanned?
1203 # See `ModelBuilder::scan_group`.
1206 # Return the modules in self and subgroups named `name`.
1208 # If `self` is not scanned (see `ModelBuilder::scan_group`) the
1209 # results might be partial.
1210 fun mmodules_by_name
(name
: String): Array[MModule]
1212 var res
= new Array[MModule]
1213 for g
in in_nesting
.smallers
do
1214 for mp
in g
.mmodules
do
1215 if mp
.name
== name
then
1224 redef class SourceFile
1225 # Associated mmodule, once created
1226 var mmodule
: nullable MModule = null
1229 redef class AStdImport
1230 # The imported module once determined
1231 var mmodule
: nullable MModule = null
1235 # The associated MModule once build by a `ModelBuilder`
1236 var mmodule
: nullable MModule = null
1238 # Flag that indicate if the importation is already completed
1239 var is_importation_done
: Bool = false