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
44 redef class ToolContext
46 var opt_path
= new OptionArray("Add an additional include path (may be used more than once)", "-I", "--path")
48 # Option --only-metamodel
49 var opt_only_metamodel
= new OptionBool("Stop after meta-model processing", "--only-metamodel")
52 var opt_only_parse
= new OptionBool("Only proceed to parse files", "--only-parse")
57 option_context
.add_option
(opt_path
, opt_only_parse
, opt_only_metamodel
)
61 redef class ModelBuilder
66 # Setup the paths value
67 paths
.append
(toolcontext
.opt_path
.value
)
69 # Packages managed by picnit, only use when not testing with tests.sh
70 if "NIT_TESTING_TESTS_SH".environ
!= "true" then
71 paths
.add picnit_lib_dir
74 var path_env
= "NIT_PATH".environ
75 if not path_env
.is_empty
then
76 paths
.append
(path_env
.split_with
(':'))
79 var nit_dir
= toolcontext
.nit_dir
80 if nit_dir
!= null then
81 var libname
= nit_dir
/"lib"
82 if libname
.file_exists
then paths
.add
(libname
)
83 libname
= nit_dir
/"contrib"
84 if libname
.file_exists
then paths
.add
(libname
)
88 # Load a bunch of modules.
89 # `modules` can contains filenames or module names.
90 # Imported modules are automatically loaded and modelized.
91 # The result is the corresponding model elements.
92 # Errors and warnings are printed with the toolcontext.
94 # Note: class and property model elements are not analysed.
95 fun parse
(modules
: Sequence[String]): Array[MModule]
98 # Parse and recursively load
99 self.toolcontext
.info
("*** PARSE ***", 1)
100 var mmodules
= new ArraySet[MModule]
102 var nmodule
= self.load_module
(a
)
103 if nmodule
== null then continue # Skip error
104 var mmodule
= nmodule
.mmodule
105 if mmodule
== null then continue # skip error
109 self.toolcontext
.info
("*** END PARSE: {time1-time0} ***", 2)
111 self.toolcontext
.check_errors
113 if toolcontext
.opt_only_parse
.value
then
114 self.toolcontext
.info
("*** ONLY PARSE...", 1)
115 self.toolcontext
.quit
121 # Identify a bunch of modules and groups.
123 # This does the same as `parse_full` but does only the identification (cf. `identify_module`)
124 fun scan_full
(names
: Sequence[String]): Array[MModule]
126 var mmodules
= new Array[MModule]
128 # Case of a group (root or sub-directory)
129 var mgroup
= self.identify_group
(a
)
130 if mgroup
!= null then
132 for mg
in mgroup
.in_nesting
.smallers
do mmodules
.add_all mg
.mmodules
136 # Case of a directory that is not a group
137 var stat
= a
.to_path
.stat
138 if stat
!= null and stat
.is_dir
then
139 self.toolcontext
.info
("look in directory {a}", 2)
141 alpha_comparator
.sort
(fs
)
142 # Try each entry as a group or a module
144 if f
.first
== '.' then continue
146 mgroup
= identify_group
(af
)
147 if mgroup
!= null then
149 for mg
in mgroup
.in_nesting
.smallers
do mmodules
.add_all mg
.mmodules
152 var mmodule
= identify_module
(af
)
153 if mmodule
!= null then
156 self.toolcontext
.info
("ignore file {af}", 2)
162 var mmodule
= identify_module
(a
)
163 if mmodule
== null then
164 var le
= last_loader_error
166 toolcontext
.error
(null, le
)
167 else if a
.file_exists
then
168 toolcontext
.error
(null, "Error: `{a}` is not a Nit source file.")
170 toolcontext
.error
(null, "Error: cannot find module `{a}`.")
180 # Load a bunch of modules and groups.
184 # * a path to a module, a group or a directory of packages.
185 # * a short name of a module or a group that are looked in the `paths` (-I)
187 # Then, for each entry, if it is:
189 # * a module, then is it parsed and returned.
190 # * a group then recursively all its modules are parsed.
191 # * a directory of packages then all the modules of all packages are parsed.
192 # * else an error is displayed.
194 # See `parse` for details.
195 fun parse_full
(names
: Sequence[String]): Array[MModule]
198 # Parse and recursively load
199 self.toolcontext
.info
("*** PARSE ***", 1)
200 var mmodules
= new ArraySet[MModule]
201 var scans
= scan_full
(names
)
202 for mmodule
in scans
do
203 var ast
= mmodule
.load
(self)
204 if ast
== null then continue # Skip error
208 self.toolcontext
.info
("*** END PARSE: {time1-time0} ***", 2)
210 self.toolcontext
.check_errors
212 if toolcontext
.opt_only_parse
.value
then
213 self.toolcontext
.info
("*** ONLY PARSE...", 1)
214 self.toolcontext
.quit
220 # The list of directories to search for top level modules
221 # The list is initially set with:
223 # * the toolcontext --path option
224 # * the NIT_PATH environment variable
225 # * `toolcontext.nit_dir`
226 # Path can be added (or removed) by the client
227 var paths
= new Array[String]
229 # Like (and used by) `get_mmodule_by_name` but does not force the parsing of the MModule (cf. `identify_module`)
230 fun search_mmodule_by_name
(anode
: nullable ANode, mgroup
: nullable MGroup, name
: String): nullable MModule
232 # First, look in groups
235 var r
= c
.mpackage
.root
238 var res
= r
.mmodules_by_name
(name
)
239 if res
.not_empty
then return res
.first
242 # Look at some known directories
243 var lookpaths
= self.paths
245 # Look in the directory of the group package also (even if not explicitly in the path)
246 if mgroup
!= null then
247 # path of the root group
248 var dirname
= mgroup
.mpackage
.root
.filepath
249 if dirname
!= null then
250 dirname
= dirname
.join_path
("..").simplify_path
251 if not lookpaths
.has
(dirname
) and dirname
.file_exists
then
252 lookpaths
= lookpaths
.to_a
253 lookpaths
.add
(dirname
)
259 if anode
!= null then loc
= anode
.hot_location
260 var candidate
= search_module_in_paths
(loc
, name
, lookpaths
)
262 if candidate
== null then
263 if mgroup
!= null then
264 error
(anode
, "Error: cannot find module `{name}` from `{mgroup.name}`. Tried: {lookpaths.join(", ")}.")
266 error
(anode
, "Error: cannot find module `{name}`. Tried: {lookpaths.join(", ")}.")
273 # Get a module by its short name; if required, the module is loaded, parsed and its hierarchies computed.
274 # If `mgroup` is set, then the module search starts from it up to the top level (see `paths`);
275 # if `mgroup` is null then the module is searched in the top level only.
276 # If no module exists or there is a name conflict, then an error on `anode` is displayed and null is returned.
277 fun get_mmodule_by_name
(anode
: nullable ANode, mgroup
: nullable MGroup, name
: String): nullable MModule
279 var mmodule
= search_mmodule_by_name
(anode
, mgroup
, name
)
280 if mmodule
== null then return null # Forward error
281 var ast
= mmodule
.load
(self)
282 if ast
== null then return null # Forward error
286 # Search a module `name` from path `lookpaths`.
287 # If found, the module is returned.
288 private fun search_module_in_paths
(location
: nullable Location, name
: String, lookpaths
: Collection[String]): nullable MModule
290 var res
= new ArraySet[MModule]
291 for dirname
in lookpaths
do
292 # Try a single module file
293 var mp
= identify_module
((dirname
/"{name}.nit").simplify_path
)
294 if mp
!= null then res
.add mp
295 # Try the default module of a group
296 var g
= identify_group
((dirname
/name
).simplify_path
)
299 res
.add_all g
.mmodules_by_name
(name
)
302 if res
.is_empty
then return null
303 if res
.length
> 1 then
304 toolcontext
.error
(location
, "Error: conflicting module files for `{name}`: `{[for x in res do x.filepath or else x.full_name].join("`, `")}`")
309 # Search groups named `name` from paths `lookpaths`.
310 private fun search_group_in_paths
(name
: String, lookpaths
: Collection[String]): ArraySet[MGroup]
312 var res
= new ArraySet[MGroup]
313 for dirname
in lookpaths
do
314 # try a single group directory
315 var mg
= identify_group
(dirname
/name
)
323 # Cache for `identify_module` by relative and real paths
324 private var identified_modules_by_path
= new HashMap[String, nullable MModule]
326 # All the currently identified modules.
327 # See `identify_module`.
329 # An identified module exists in the model but might be not yet parsed (no AST), or not yet analysed (no importation).
330 var identified_modules
= new Array[MModule]
332 # All the currently parsed modules.
334 # A parsed module exists in the model but might be not yet analysed (no importation).
335 var parsed_modules
= new Array[MModule]
337 # Some `loader` services are silent and return `null` on error.
339 # Those services can set `last_loader_error` to precise an specific error message.
340 # if `last_loader_error == null` then a generic error message can be used.
342 # See `identified_modules` and `identify_group` for details.
343 var last_loader_error
: nullable String = null
345 # Identify a source file and load the associated package and groups if required.
347 # This method does what the user expects when giving an argument to a Nit tool.
349 # * If `path` is an existing Nit source file (with the `.nit` extension),
350 # then the associated MModule is returned
351 # * If `path` is a directory (with a `/`),
352 # then the MModule of its default module is returned (if any)
353 # * If `path` is a simple identifier (eg. `digraph`),
354 # then the main module of the package `digraph` is searched in `paths` and returned.
356 # Silently return `null` if `path` does not exists or cannot be identified.
357 # If `null` is returned, `last_loader_error` can be set to a specific error message.
359 # On success, it returns a module that is possibly not yet parsed (no AST), or not yet analysed (no importation).
360 # If the module was already identified, or loaded, it is returned.
361 fun identify_module
(path
: String): nullable MModule
363 last_loader_error
= null
365 # special case for not a nit file
366 if not path
.has_suffix
(".nit") then do
367 # search dirless files in known -I paths
368 if not path
.chars
.has
('/') then
369 var res
= search_module_in_paths
(null, path
, self.paths
)
370 if res
!= null then return res
373 # Found nothing? maybe it is a group...
374 if path
.file_exists
then
375 var mgroup
= identify_group
(path
)
376 if mgroup
!= null then
377 var owner_path
= mgroup
.filepath
.join_path
(mgroup
.name
+ ".nit")
378 if owner_path
.file_exists
then
385 # Found nothing? maybe it is a qualified name
386 if path
.chars
.has
(':') then
387 var ids
= path
.split
("::")
388 var g
= identify_group
(ids
.first
)
391 var ms
= g
.mmodules_by_name
(ids
.last
)
395 if m
.full_name
== path
then
400 # Where there is only one or two names `foo::bar`
401 # then accept module that matches `foo::*::bar`
402 if ids
.length
<= 2 then
403 if ms
.length
== 1 then return ms
.first
404 if ms
.length
> 1 then
405 var l
= new Array[String]
408 if fp
!= null then fp
= " ({fp})" else fp
= ""
409 l
.add
"`{m.full_name}`{fp}"
411 last_loader_error
= "Error: conflicting module for `{path}`: {l.join(", ")} "
416 var bests
= new BestDistance[String](path
.length
/ 2)
417 # We found nothing. But propose something in the package?
418 for sg
in g
.mpackage
.mgroups
do
419 for m
in sg
.mmodules
do
420 var d
= path
.levenshtein_distance
(m
.full_name
)
421 bests
.update
(d
, m
.full_name
)
424 var last_loader_error
= "Error: cannot find module `{path}`."
425 if bests
.best_items
.not_empty
then
426 last_loader_error
+= " Did you mean " + bests
.best_items
.join
(", ", " or ") + "?"
428 self.last_loader_error
= last_loader_error
436 # Does the file exists?
437 if not path
.file_exists
then
441 # Fast track, the path is already known
442 if identified_modules_by_path
.has_key
(path
) then return identified_modules_by_path
[path
]
443 var rp
= module_absolute_path
(path
)
444 if identified_modules_by_path
.has_key
(rp
) then return identified_modules_by_path
[rp
]
446 var pn
= path
.basename
(".nit")
449 var mgrouppath
= path
.join_path
("..").simplify_path
450 var mgroup
= identify_group
(mgrouppath
)
452 if mgroup
!= null then
453 var mpackage
= mgroup
.mpackage
454 if not mpackage
.accept
(path
) then
456 toolcontext
.info
("module `{path}` excluded from package `{mpackage}`", 2)
459 if mgroup
== null then
461 var loc
= new Location.opaque_file
(path
)
462 var mpackage
= new MPackage(pn
, model
, loc
)
463 mgroup
= new MGroup(pn
, loc
, mpackage
, null) # same name for the root group
464 mpackage
.root
= mgroup
465 toolcontext
.info
("found singleton package `{pn}` at {path}", 2)
467 # Attach homonymous `ini` file to the package
468 var inipath
= path
.dirname
/ "{pn}.ini"
469 if inipath
.file_exists
then
470 var ini
= new ConfigTree(inipath
)
475 var loc
= new Location.opaque_file
(path
)
476 var res
= new MModule(model
, mgroup
, pn
, loc
)
478 identified_modules_by_path
[rp
] = res
479 identified_modules_by_path
[path
] = res
480 identified_modules
.add
(res
)
485 private var mgroups
= new HashMap[String, nullable MGroup]
487 # Return the mgroup associated to a directory path.
488 # If the directory is not a group null is returned.
490 # Silently return `null` if `dirpath` does not exists, is not a directory,
491 # cannot be identified or cannot be attached to a mpackage.
492 # If `null` is returned, `last_loader_error` can be set to a specific error message.
494 # Note: `paths` is also used to look for mgroups
495 fun identify_group
(dirpath
: String): nullable MGroup
498 last_loader_error
= null
500 var stat
= dirpath
.file_stat
502 if stat
== null or not stat
.is_dir
then do
503 # search dirless directories in known -I paths
504 if dirpath
.chars
.has
('/') then return null
506 var try
= p
/ dirpath
516 # Filter out non-directories
517 if not stat
.is_dir
then
518 last_loader_error
= "Error: `{dirpath}` is not a directory."
522 # Fast track, the path is already known
523 var rdp
= module_absolute_path
(dirpath
)
524 if mgroups
.has_key
(rdp
) then
528 # By default, the name of the package or group is the base_name of the directory
529 var pn
= rdp
.basename
531 # Check `package.ini` that indicate a package
534 var inipath
= dirpath
/ "package.ini"
535 if inipath
.file_exists
then
536 ini
= new ConfigTree(inipath
)
540 # No ini, multiple course of action
542 # The root of the directory hierarchy in the file system.
545 last_loader_error
= "Error: `{dirpath}` is not a Nit package."
549 # Special stopper `packages.ini`
550 if (dirpath
/"packages.ini").file_exists
then
551 # dirpath cannot be a package since it is a package directory
553 last_loader_error
= "Error: `{dirpath}` is not a Nit package."
557 # check the parent directory (if it does not contain the stopper file)
558 var parentpath
= dirpath
.join_path
("..").simplify_path
559 var stopper
= parentpath
/ "packages.ini"
560 if not stopper
.file_exists
then
561 # Recursively get the parent group
562 parent
= identify_group
(parentpath
)
563 if parent
!= null then do
564 var mpackage
= parent
.mpackage
565 if not mpackage
.accept
(dirpath
) then
566 toolcontext
.info
("directory `{dirpath}` excluded from package `{mpackage}`", 2)
570 if parent
== null then
571 # Parent is not a group, thus we are not a group either
573 last_loader_error
= "Error: `{dirpath}` is not a Nit package."
579 var loc
= new Location.opaque_file
(dirpath
)
581 if parent
== null then
582 # no parent, thus new package
583 if ini
!= null then pn
= ini
["package.name"] or else pn
584 var mpackage
= new MPackage(pn
, model
, loc
)
585 mgroup
= new MGroup(pn
, loc
, mpackage
, null) # same name for the root group
586 mpackage
.root
= mgroup
587 toolcontext
.info
("found package `{mpackage}` at {dirpath}", 2)
590 mgroup
= new MGroup(pn
, loc
, parent
.mpackage
, parent
)
591 toolcontext
.info
("found sub group `{mgroup.full_name}` at {dirpath}", 2)
594 # search documentation
595 # in src first so the documentation of the package code can be distinct for the documentation of the package usage
596 var readme
= dirpath
.join_path
("README.md")
597 if not readme
.file_exists
then readme
= dirpath
.join_path
("README")
598 if readme
.file_exists
then
599 var mdoc
= load_markdown
(readme
)
601 mdoc
.original_mentity
= mgroup
604 mgroups
[rdp
] = mgroup
608 # Load a markdown file as a documentation object
609 fun load_markdown
(filepath
: String): MDoc
611 var s
= new FileReader.open
(filepath
)
612 var lines
= new Array[String]
613 var line_starts
= new Array[Int]
616 var line
= s
.read_line
619 len
+= line
.length
+ 1
622 var source
= new SourceFile.from_string
(filepath
, lines
.join
("\n"))
623 source
.line_starts
.add_all line_starts
624 var mdoc
= new MDoc(new Location(source
, 1, lines
.length
, 0, 0))
625 mdoc
.content
.add_all
(lines
)
629 # Force the identification of all MModule of the group and sub-groups in the file system.
631 # When a group is scanned, its sub-groups hierarchy is filled (see `MGroup::in_nesting`)
632 # and the potential modules (and nested modules) are identified (see `MGroup::modules`).
634 # Basically, this recursively call `identify_group` and `identify_module` on each directory entry.
636 # No-op if the group was already scanned (see `MGroup::scanned`).
637 fun scan_group
(mgroup
: MGroup) do
638 if mgroup
.scanned
then return
639 mgroup
.scanned
= true
640 var p
= mgroup
.filepath
641 # a virtual group has nothing to scan
642 if p
== null then return
644 alpha_comparator
.sort
(files
)
646 if f
.first
== '.' then continue
648 var g
= identify_group
(fp
)
649 # Recursively scan for groups of the same package
652 else if g
.mpackage
== mgroup
.mpackage
then
658 # Transform relative paths (starting with '../') into absolute paths
659 private fun module_absolute_path
(path
: String): String do
663 # Try to load a module AST using a path.
664 # Display an error if there is a problem (IO / lexer / parser) and return null
666 # The AST is loaded as is total independence of the model and its entities.
668 # AST are not cached or reused thus a new AST is returned on success.
669 fun load_module_ast
(filename
: String): nullable AModule
671 if not filename
.has_suffix
(".nit") then
672 self.toolcontext
.error
(null, "Error: file `{filename}` is not a valid nit module.")
675 if not filename
.file_exists
then
676 self.toolcontext
.error
(null, "Error: file `{filename}` not found.")
680 self.toolcontext
.info
("load module {filename}", 2)
683 var file
= new FileReader.open
(filename
)
684 var lexer
= new Lexer(new SourceFile(filename
, file
))
685 var parser
= new Parser(lexer
)
686 var tree
= parser
.parse
689 # Handle lexer and parser error
690 var nmodule
= tree
.n_base
691 if nmodule
== null then
692 var neof
= tree
.n_eof
693 assert neof
isa AError
694 error
(neof
, neof
.message
)
701 # Remove Nit source files from a list of arguments.
703 # Items of `args` that can be loaded as a nit file will be removed from `args` and returned.
704 fun filter_nit_source
(args
: Array[String]): Array[String]
706 var keep
= new Array[String]
707 var res
= new Array[String]
709 var stat
= a
.to_path
.stat
710 if stat
!= null and stat
.is_dir
then
714 var l
= identify_module
(a
)
726 # Try to load a module using a path.
727 # Display an error if there is a problem (IO / lexer / parser) and return null.
728 # Note: usually, you do not need this method, use `get_mmodule_by_name` instead.
730 # The MModule is located, created, parsed and the importation is performed.
731 fun load_module
(filename
: String): nullable AModule
733 # Look for the module
734 var mmodule
= identify_module
(filename
)
735 if mmodule
== null then
736 var le
= last_loader_error
738 toolcontext
.error
(null, le
)
739 else if filename
.file_exists
then
740 toolcontext
.error
(null, "Error: `{filename}` is not a Nit source file.")
742 toolcontext
.error
(null, "Error: cannot find module `{filename}`.")
748 return mmodule
.load
(self)
751 # Injection of a new module without source.
752 # Used by the interpreter.
753 fun load_rt_module
(parent
: nullable MModule, nmodule
: AModule, mod_name
: String): nullable MModule
758 if parent
!= null then mgroup
= parent
.mgroup
759 var mmodule
= new MModule(model
, mgroup
, mod_name
, nmodule
.location
)
760 nmodule
.mmodule
= mmodule
761 nmodules
.add
(nmodule
)
762 parsed_modules
.add mmodule
763 self.mmodule2nmodule
[mmodule
] = nmodule
765 if parent
!= null then
766 var imported_modules
= new Array[MModule]
767 imported_modules
.add
(parent
)
768 mmodule
.set_visibility_for
(parent
, intrude_visibility
)
769 mmodule
.set_imported_mmodules
(imported_modules
)
771 build_module_importation
(nmodule
)
776 # Visit the AST and create the `MModule` object
777 private fun build_a_mmodule
(mgroup
: nullable MGroup, nmodule
: AModule)
779 var mmodule
= nmodule
.mmodule
780 assert mmodule
!= null
782 # Check the module name
783 var decl
= nmodule
.n_moduledecl
785 var decl_name
= decl
.n_name
.n_id
.text
786 if decl_name
!= mmodule
.name
then
787 warning
(decl
.n_name
, "module-name-mismatch", "Error: module name mismatch; declared {decl_name} file named {mmodule.name}.")
791 # Check for conflicting module names in the package
792 if mgroup
!= null then
793 var others
= model
.get_mmodules_by_name
(mmodule
.name
)
794 if others
!= null then for other
in others
do
795 if other
!= mmodule
and mmodule2nmodule
.has_key
(mmodule
) and other
.mgroup
!= null and other
.mgroup
.mpackage
== mgroup
.mpackage
then
797 if decl
== null then node
= nmodule
else node
= decl
.n_name
798 error
(node
, "Error: a module named `{other.full_name}` already exists at {other.location}.")
804 nmodules
.add
(nmodule
)
805 self.mmodule2nmodule
[mmodule
] = nmodule
807 var source
= nmodule
.location
.file
808 if source
!= null then
809 assert source
.mmodule
== null
810 source
.mmodule
= mmodule
814 # Extract documentation
815 var ndoc
= decl
.n_doc
817 var mdoc
= ndoc
.to_mdoc
819 mdoc
.original_mentity
= mmodule
821 # Is the module generated?
822 mmodule
.is_generated
= not decl
.get_annotations
("generated").is_empty
826 # Resolve the module identification for a given `AModuleName`.
828 # This method handles qualified names as used in `AModuleName`.
829 fun seach_module_by_amodule_name
(n_name
: AModuleName, mgroup
: nullable MGroup): nullable MModule
831 var mod_name
= n_name
.n_id
.text
833 # If a quad is given, we ignore the starting group (go from path)
834 if n_name
.n_quad
!= null then mgroup
= null
836 # If name not qualified, just search the name
837 if n_name
.n_path
.is_empty
then
838 # Fast search if no n_path
839 return search_mmodule_by_name
(n_name
, mgroup
, mod_name
)
842 # If qualified and in a group
843 if mgroup
!= null then
844 # First search in the package
845 var r
= mgroup
.mpackage
.root
848 # Get all modules with the final name
849 var res
= r
.mmodules_by_name
(mod_name
)
850 # Filter out the name that does not match the qualifiers
851 res
= [for x
in res
do if match_amodulename
(n_name
, x
) then x
]
852 if res
.not_empty
then
853 if res
.length
> 1 then
854 error
(n_name
, "Error: conflicting module files for `{mod_name}`: `{[for x in res do x.filepath or else x.full_name].join("`, `")}`")
860 # If no module yet, then assume that the first element of the path
861 # Is to be searched in the path.
862 var root_name
= n_name
.n_path
.first
.text
863 var roots
= search_group_in_paths
(root_name
, paths
)
864 if roots
.is_empty
then
865 error
(n_name
, "Error: cannot find `{root_name}`. Tried: {paths.join(", ")}.")
869 var res
= new ArraySet[MModule]
871 # Then, for each root, collect modules that matches the qualifiers
873 var root_res
= r
.mmodules_by_name
(mod_name
)
874 for x
in root_res
do if match_amodulename
(n_name
, x
) then res
.add x
876 if res
.not_empty
then
877 if res
.length
> 1 then
878 error
(n_name
, "Error: conflicting module files for `{mod_name}`: `{[for x in res do x.filepath or else x.full_name].join("`, `")}`")
882 # If still nothing, just call a basic search that will fail and will produce an error message
883 error
(n_name
, "Error: cannot find module `{mod_name}` from `{root_name}`. Tried: {paths.join(", ")}.")
887 # Is elements of `n_name` correspond to the group nesting of `m`?
889 # Basically it check that `bar::foo` matches `bar/foo.nit` and `bar/baz/foo.nit`
890 # but not `baz/foo.nit` nor `foo/bar.nit`
892 # Is used by `seach_module_by_amodule_name` to validate qualified names.
893 private fun match_amodulename
(n_name
: AModuleName, m
: MModule): Bool
895 var g
: nullable MGroup = m
.mgroup
896 for grp
in n_name
.n_path
.reverse_iterator
do
897 while g
!= null and grp
.text
!= g
.name
do
904 # Analyze the module importation and fill the module_importation_hierarchy
906 # If the importation was already done (`nmodule.is_importation_done`), this method does a no-op.
908 # REQUIRE `nmodule.mmodule != null`
909 # ENSURE `nmodule.is_importation_done`
910 fun build_module_importation
(nmodule
: AModule)
912 if nmodule
.is_importation_done
then return
913 nmodule
.is_importation_done
= true
914 var mmodule
= nmodule
.mmodule
.as(not null)
916 var imported_modules
= new Array[MModule]
917 for aimport
in nmodule
.n_imports
do
918 # Do not imports conditional
919 var atconditionals
= aimport
.get_annotations
("conditional")
920 if atconditionals
.not_empty
then continue
923 if not aimport
isa AStdImport then
927 # Load the imported module
928 var sup
= seach_module_by_amodule_name
(aimport
.n_name
, mmodule
.mgroup
)
930 mmodule
.is_broken
= true
931 nmodule
.mmodule
= null # invalidate the module
932 continue # Skip error
934 var ast
= sup
.load
(self)
936 mmodule
.is_broken
= true
937 nmodule
.mmodule
= null # invalidate the module
938 continue # Skip error
941 aimport
.mmodule
= sup
942 imported_modules
.add
(sup
)
943 var mvisibility
= aimport
.n_visibility
.mvisibility
944 if mvisibility
== protected_visibility
then
945 mmodule
.is_broken
= true
946 error
(aimport
.n_visibility
, "Error: only properties can be protected.")
947 mmodule
.is_broken
= true
948 nmodule
.mmodule
= null # invalidate the module
951 if sup
== mmodule
then
952 error
(aimport
.n_name
, "Error: dependency loop in module {mmodule}.")
953 mmodule
.is_broken
= true
954 nmodule
.mmodule
= null # invalidate the module
956 if sup
.in_importation
< mmodule
then
957 error
(aimport
.n_name
, "Error: dependency loop between modules {mmodule} and {sup}.")
958 mmodule
.is_broken
= true
959 nmodule
.mmodule
= null # invalidate the module
962 mmodule
.set_visibility_for
(sup
, mvisibility
)
965 var mod_name
= "core"
966 var sup
= self.get_mmodule_by_name
(nmodule
, null, mod_name
)
968 mmodule
.is_broken
= true
969 nmodule
.mmodule
= null # invalidate the module
971 imported_modules
.add
(sup
)
972 mmodule
.set_visibility_for
(sup
, public_visibility
)
976 # Declare conditional importation
977 for aimport
in nmodule
.n_imports
do
978 if not aimport
isa AStdImport then continue
979 var atconditionals
= aimport
.get_annotations
("conditional")
980 if atconditionals
.is_empty
then continue
982 var suppath
= seach_module_by_amodule_name
(aimport
.n_name
, mmodule
.mgroup
)
983 if suppath
== null then continue # skip error
985 for atconditional
in atconditionals
do
986 var nargs
= atconditional
.n_args
987 if nargs
.is_empty
then
988 error
(atconditional
, "Syntax Error: `conditional` expects module identifiers as arguments.")
993 var rule
= new Array[MModule]
995 # First element is the goal, thus
998 # Second element is the first condition, that is to be a client of the current module
1001 # Other condition are to be also a client of each modules indicated as arguments of the annotation
1002 for narg
in nargs
do
1005 error
(narg
, "Syntax Error: `conditional` expects module identifier as arguments.")
1009 var mp
= search_mmodule_by_name
(narg
, mmodule
.mgroup
, id
)
1010 if mp
== null then continue
1015 conditional_importations
.add rule
1019 mmodule
.set_imported_mmodules
(imported_modules
)
1021 apply_conditional_importations
(mmodule
)
1023 self.toolcontext
.info
("{mmodule} imports {mmodule.in_importation.direct_greaters.join(", ")}", 3)
1025 # Force `core` to be public if imported
1026 for sup
in mmodule
.in_importation
.greaters
do
1027 if sup
.name
== "core" then
1028 mmodule
.set_visibility_for
(sup
, public_visibility
)
1032 # TODO: Correctly check for useless importation
1033 # It is even doable?
1034 var directs
= mmodule
.in_importation
.direct_greaters
1035 for nim
in nmodule
.n_imports
do
1036 if not nim
isa AStdImport then continue
1037 var im
= nim
.mmodule
1038 if im
== null then continue
1039 if directs
.has
(im
) then continue
1040 # This generates so much noise that it is simpler to just comment it
1041 #warning(nim, "Warning: possible useless importation of {im}")
1045 # Global list of conditional importation rules.
1047 # Each rule is a "Horn clause"-like sequence of modules.
1048 # It means that the first module is the module to automatically import.
1049 # The remaining modules are the conditions of the rule.
1051 # Rules are declared by `build_module_importation` and are applied by `apply_conditional_importations`
1052 # (and `build_module_importation` that calls it).
1054 # TODO (when the loader will be rewritten): use a better representation and move up rules in the model.
1055 var conditional_importations
= new Array[SequenceRead[MModule]]
1057 # Extends the current importations according to imported rules about conditional importation
1058 fun apply_conditional_importations
(mmodule
: MModule)
1060 # Because a conditional importation may cause additional conditional importation, use a fixed point
1061 # The rules are checked naively because we assume that it does not worth to be optimized
1062 var check_conditional_importations
= true
1063 while check_conditional_importations
do
1064 check_conditional_importations
= false
1066 for ci
in conditional_importations
do
1068 for i
in [1..ci
.length
[ do
1071 if mmodule
== m
or not mmodule
.in_importation
.greaters
.has
(m
) then continue label
1073 # Still here? It means that all conditions modules are loaded and imported
1075 # Identify the module to automatically import
1077 var ast
= sup
.load
(self)
1078 if ast
== null then continue
1080 # Do nothing if already imported
1081 if mmodule
.in_importation
.greaters
.has
(sup
) then continue label
1084 self.toolcontext
.info
("{mmodule} conditionally imports {sup}", 3)
1085 # TODO visibility rules (currently always public)
1086 mmodule
.set_visibility_for
(sup
, public_visibility
)
1087 # TODO linearization rules (currently added at the end in the order of the rules)
1088 mmodule
.set_imported_mmodules
([sup
])
1090 # Prepare to reapply the rules
1091 check_conditional_importations
= true
1096 # All the loaded modules
1097 var nmodules
= new Array[AModule]
1099 # Register the nmodule associated to each mmodule
1101 # Public clients need to use `mmodule2node` to access stuff.
1102 private var mmodule2nmodule
= new HashMap[MModule, AModule]
1104 # Retrieve the associated AST node of a mmodule.
1105 # This method is used to associate model entity with syntactic entities.
1107 # If the module is not associated with a node, returns null.
1108 fun mmodule2node
(mmodule
: MModule): nullable AModule
1110 return mmodule2nmodule
.get_or_null
(mmodule
)
1115 # Force the parsing of the module using `modelbuilder`.
1117 # If the module was already parsed, the existing ASI is returned.
1118 # Else the source file is loaded, and parsed and some
1120 # The importation is not done by this
1122 # REQUIRE: `filepath != null`
1123 # ENSURE: `modelbuilder.parsed_modules.has(self)`
1124 fun parse
(modelbuilder
: ModelBuilder): nullable AModule
1126 # Already known and loaded? then return it
1127 var nmodule
= modelbuilder
.mmodule2nmodule
.get_or_null
(self)
1128 if nmodule
!= null then return nmodule
1130 var filepath
= self.filepath
1131 assert filepath
!= null
1133 nmodule
= modelbuilder
.load_module_ast
(filepath
)
1134 if nmodule
== null then return null # forward error
1137 nmodule
.mmodule
= self
1138 self.location
= nmodule
.location
1139 modelbuilder
.build_a_mmodule
(mgroup
, nmodule
)
1141 modelbuilder
.parsed_modules
.add
self
1145 # Parse and process importation of a given MModule.
1147 # Basically chains `parse` and `build_module_importation`.
1148 fun load
(modelbuilder
: ModelBuilder): nullable AModule
1150 var nmodule
= parse
(modelbuilder
)
1151 if nmodule
== null then return null
1153 modelbuilder
.build_module_importation
(nmodule
)
1158 redef class MPackage
1159 # The associated `.ini` file, if any
1161 # The `ini` file is given as is and might contain invalid or missing information.
1163 # Some packages, like stand-alone packages or virtual packages have no `ini` file associated.
1164 var ini
: nullable ConfigTree = null
1166 # Array of relative source paths excluded according to the `source.exclude` key of the `ini`
1167 var excludes
: nullable Array[String] is lazy
do
1169 if ini
== null then return null
1170 var exclude
= ini
["source.exclude"]
1171 if exclude
== null then return null
1172 var excludes
= exclude
.split
(":")
1176 # Does the source inclusion/inclusion rules of the package `ini` accept such path?
1177 fun accept
(filepath
: String): Bool
1179 var excludes
= self.excludes
1180 if excludes
!= null then
1181 var relpath
= root
.filepath
.relpath
(filepath
)
1182 if excludes
.has
(relpath
) then return false
1189 # Is the group interesting for a final user?
1191 # Groups are mandatory in the model but for simple packages they are not
1192 # always interesting.
1194 # A interesting group has, at least, one of the following true:
1196 # * it has 2 modules or more
1197 # * it has a subgroup
1198 # * it has a documentation
1199 fun is_interesting
: Bool
1201 return mmodules
.length
> 1 or
1202 not in_nesting
.direct_smallers
.is_empty
or
1204 (mmodules
.length
== 1 and default_mmodule
== null)
1207 # Are files and directories in self scanned?
1209 # See `ModelBuilder::scan_group`.
1212 # Return the modules in self and subgroups named `name`.
1214 # If `self` is not scanned (see `ModelBuilder::scan_group`) the
1215 # results might be partial.
1216 fun mmodules_by_name
(name
: String): Array[MModule]
1218 var res
= new Array[MModule]
1219 for g
in in_nesting
.smallers
do
1220 for mp
in g
.mmodules
do
1221 if mp
.name
== name
then
1230 redef class SourceFile
1231 # Associated mmodule, once created
1232 var mmodule
: nullable MModule = null
1235 redef class AStdImport
1236 # The imported module once determined
1237 var mmodule
: nullable MModule = null
1241 # The associated MModule once build by a `ModelBuilder`
1242 var mmodule
: nullable MModule = null
1244 # Flag that indicate if the importation is already completed
1245 var is_importation_done
: Bool = false