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 var mmodule
= nmodule
.mmodule
77 if mmodule
== null then continue # skip error
81 self.toolcontext
.info
("*** END PARSE: {time1-time0} ***", 2)
83 self.toolcontext
.check_errors
85 if toolcontext
.opt_only_parse
.value
then
86 self.toolcontext
.info
("*** ONLY PARSE...", 1)
93 # Identify a bunch of modules and groups.
95 # This does the same as `parse_full` but does only the identification (cf. `identify_module`)
96 fun scan_full
(names
: Sequence[String]): Array[MModule]
98 var mmodules
= new Array[MModule]
100 # Case of a group (root or sub-directory)
101 var mgroup
= self.identify_group
(a
)
102 if mgroup
!= null then
104 for mg
in mgroup
.in_nesting
.smallers
do mmodules
.add_all mg
.mmodules
108 # Case of a directory that is not a group
109 var stat
= a
.to_path
.stat
110 if stat
!= null and stat
.is_dir
then
111 self.toolcontext
.info
("look in directory {a}", 2)
113 # Try each entry as a group or a module
116 mgroup
= identify_group
(af
)
117 if mgroup
!= null then
119 for mg
in mgroup
.in_nesting
.smallers
do mmodules
.add_all mg
.mmodules
122 var mmodule
= identify_module
(af
)
123 if mmodule
!= null then
126 self.toolcontext
.info
("ignore file {af}", 2)
132 var mmodule
= identify_module
(a
)
133 if mmodule
== null then
142 # Load a bunch of modules and groups.
146 # * a path to a module, a group or a directory of packages.
147 # * a short name of a module or a group that are looked in the `paths` (-I)
149 # Then, for each entry, if it is:
151 # * a module, then is it parsed and returned.
152 # * a group then recursively all its modules are parsed.
153 # * a directory of packages then all the modules of all packages are parsed.
154 # * else an error is displayed.
156 # See `parse` for details.
157 fun parse_full
(names
: Sequence[String]): Array[MModule]
160 # Parse and recursively load
161 self.toolcontext
.info
("*** PARSE ***", 1)
162 var mmodules
= new ArraySet[MModule]
163 var scans
= scan_full
(names
)
164 for mmodule
in scans
do
165 var ast
= mmodule
.load
(self)
166 if ast
== null then continue # Skip error
170 self.toolcontext
.info
("*** END PARSE: {time1-time0} ***", 2)
172 self.toolcontext
.check_errors
174 if toolcontext
.opt_only_parse
.value
then
175 self.toolcontext
.info
("*** ONLY PARSE...", 1)
182 # The list of directories to search for top level modules
183 # The list is initially set with:
185 # * the toolcontext --path option
186 # * the NIT_PATH environment variable
187 # * `toolcontext.nit_dir`
188 # Path can be added (or removed) by the client
189 var paths
= new Array[String]
191 # Like (and used by) `get_mmodule_by_name` but does not force the parsing of the MModule (cf. `identify_module`)
192 fun search_mmodule_by_name
(anode
: nullable ANode, mgroup
: nullable MGroup, name
: String): nullable MModule
194 # First, look in groups
197 var r
= c
.mpackage
.root
200 var res
= r
.mmodules_by_name
(name
)
201 if res
.not_empty
then return res
.first
204 # Look at some known directories
205 var lookpaths
= self.paths
207 # Look in the directory of the group package also (even if not explicitly in the path)
208 if mgroup
!= null then
209 # path of the root group
210 var dirname
= mgroup
.mpackage
.root
.filepath
211 if dirname
!= null then
212 dirname
= dirname
.join_path
("..").simplify_path
213 if not lookpaths
.has
(dirname
) and dirname
.file_exists
then
214 lookpaths
= lookpaths
.to_a
215 lookpaths
.add
(dirname
)
220 var candidate
= search_module_in_paths
(anode
.hot_location
, name
, lookpaths
)
222 if candidate
== null then
223 if mgroup
!= null then
224 error
(anode
, "Error: cannot find module `{name}` from `{mgroup.name}`. Tried: {lookpaths.join(", ")}.")
226 error
(anode
, "Error: cannot find module `{name}`. Tried: {lookpaths.join(", ")}.")
233 # Get a module by its short name; if required, the module is loaded, parsed and its hierarchies computed.
234 # If `mgroup` is set, then the module search starts from it up to the top level (see `paths`);
235 # if `mgroup` is null then the module is searched in the top level only.
236 # If no module exists or there is a name conflict, then an error on `anode` is displayed and null is returned.
237 fun get_mmodule_by_name
(anode
: nullable ANode, mgroup
: nullable MGroup, name
: String): nullable MModule
239 var mmodule
= search_mmodule_by_name
(anode
, mgroup
, name
)
240 if mmodule
== null then return null # Forward error
241 var ast
= mmodule
.load
(self)
242 if ast
== null then return null # Forward error
246 # Search a module `name` from path `lookpaths`.
247 # If found, the module is returned.
248 private fun search_module_in_paths
(location
: nullable Location, name
: String, lookpaths
: Collection[String]): nullable MModule
250 var res
= new ArraySet[MModule]
251 for dirname
in lookpaths
do
252 # Try a single module file
253 var mp
= identify_module
((dirname
/"{name}.nit").simplify_path
)
254 if mp
!= null then res
.add mp
255 # Try the default module of a group
256 var g
= identify_group
((dirname
/name
).simplify_path
)
259 res
.add_all g
.mmodules_by_name
(name
)
262 if res
.is_empty
then return null
263 if res
.length
> 1 then
264 toolcontext
.error
(location
, "Error: conflicting module files for `{name}`: `{[for x in res do x.filepath or else x.full_name].join("`, `")}`")
269 # Search groups named `name` from paths `lookpaths`.
270 private fun search_group_in_paths
(name
: String, lookpaths
: Collection[String]): ArraySet[MGroup]
272 var res
= new ArraySet[MGroup]
273 for dirname
in lookpaths
do
274 # try a single group directory
275 var mg
= identify_group
(dirname
/name
)
283 # Cache for `identify_module` by relative and real paths
284 private var identified_modules_by_path
= new HashMap[String, nullable MModule]
286 # All the currently identified modules.
287 # See `identify_module`.
289 # An identified module exists in the model but might be not yet parsed (no AST), or not yet analysed (no importation).
290 var identified_modules
= new Array[MModule]
292 # All the currently parsed modules.
294 # A parsed module exists in the model but might be not yet analysed (no importation).
295 var parsed_modules
= new Array[MModule]
297 # Identify a source file and load the associated package and groups if required.
299 # This method does what the user expects when giving an argument to a Nit tool.
301 # * If `path` is an existing Nit source file (with the `.nit` extension),
302 # then the associated MModule is returned
303 # * If `path` is a directory (with a `/`),
304 # then the MModule of its default module is returned (if any)
305 # * If `path` is a simple identifier (eg. `digraph`),
306 # then the main module of the package `digraph` is searched in `paths` and returned.
308 # Silently return `null` if `path` does not exists or cannot be identified.
310 # On success, it returns a module that is possibly not yet parsed (no AST), or not yet analysed (no importation).
311 # If the module was already identified, or loaded, it is returned.
312 fun identify_module
(path
: String): nullable MModule
314 # special case for not a nit file
315 if not path
.has_suffix
(".nit") then
316 # search dirless files in known -I paths
317 if not path
.chars
.has
('/') then
318 var res
= search_module_in_paths
(null, path
, self.paths
)
319 if res
!= null then return res
322 # Found nothing? maybe it is a group...
324 if path
.file_exists
then
325 var mgroup
= identify_group
(path
)
326 if mgroup
!= null then
327 var owner_path
= mgroup
.filepath
.join_path
(mgroup
.name
+ ".nit")
328 if owner_path
.file_exists
then candidate
= owner_path
332 if candidate
== null then
338 # Does the file exists?
339 if not path
.file_exists
then
343 # Fast track, the path is already known
344 if identified_modules_by_path
.has_key
(path
) then return identified_modules_by_path
[path
]
345 var rp
= module_absolute_path
(path
)
346 if identified_modules_by_path
.has_key
(rp
) then return identified_modules_by_path
[rp
]
348 var pn
= path
.basename
(".nit")
351 var mgrouppath
= path
.join_path
("..").simplify_path
352 var mgroup
= identify_group
(mgrouppath
)
354 if mgroup
== null then
356 var mpackage
= new MPackage(pn
, model
)
357 mgroup
= new MGroup(pn
, mpackage
, null) # same name for the root group
358 mgroup
.filepath
= path
359 mpackage
.root
= mgroup
360 toolcontext
.info
("found singleton package `{pn}` at {path}", 2)
362 # Attach homonymous `ini` file to the package
363 var inipath
= path
.dirname
/ "{pn}.ini"
364 if inipath
.file_exists
then
365 var ini
= new ConfigTree(inipath
)
370 var src
= new SourceFile.from_string
(path
, "")
371 var loc
= new Location(src
, 0, 0, 0, 0)
372 var res
= new MModule(model
, mgroup
, pn
, loc
)
375 identified_modules_by_path
[rp
] = res
376 identified_modules_by_path
[path
] = res
377 identified_modules
.add
(res
)
382 private var mgroups
= new HashMap[String, nullable MGroup]
384 # Return the mgroup associated to a directory path.
385 # If the directory is not a group null is returned.
387 # Note: `paths` is also used to look for mgroups
388 fun identify_group
(dirpath
: String): nullable MGroup
390 var stat
= dirpath
.file_stat
392 if stat
== null then do
393 # search dirless directories in known -I paths
394 if dirpath
.chars
.has
('/') then return null
396 var try
= p
/ dirpath
406 # Filter out non-directories
407 if not stat
.is_dir
then
411 # Fast track, the path is already known
412 var rdp
= module_absolute_path
(dirpath
)
413 if mgroups
.has_key
(rdp
) then
417 # By default, the name of the package or group is the base_name of the directory
418 var pn
= rdp
.basename
420 # Check `package.ini` that indicate a package
423 var inipath
= dirpath
/ "package.ini"
424 if inipath
.file_exists
then
425 ini
= new ConfigTree(inipath
)
429 # No ini, multiple course of action
431 # The root of the directory hierarchy in the file system.
437 # Special stopper `packages.ini`
438 if (dirpath
/"packages.ini").file_exists
then
439 # dirpath cannot be a package since it is a package directory
444 # check the parent directory (if it does not contain the stopper file)
445 var parentpath
= dirpath
.join_path
("..").simplify_path
446 var stopper
= parentpath
/ "packages.ini"
447 if not stopper
.file_exists
then
448 # Recursively get the parent group
449 parent
= identify_group
(parentpath
)
450 if parent
== null then
451 # Parent is not a group, thus we are not a group either
459 if parent
== null then
460 # no parent, thus new package
461 if ini
!= null then pn
= ini
["package.name"] or else pn
462 var mpackage
= new MPackage(pn
, model
)
463 mgroup
= new MGroup(pn
, mpackage
, null) # same name for the root group
464 mpackage
.root
= mgroup
465 toolcontext
.info
("found package `{mpackage}` at {dirpath}", 2)
468 mgroup
= new MGroup(pn
, parent
.mpackage
, parent
)
469 toolcontext
.info
("found sub group `{mgroup.full_name}` at {dirpath}", 2)
472 # search documentation
473 # in src first so the documentation of the package code can be distinct for the documentation of the package usage
474 var readme
= dirpath
.join_path
("README.md")
475 if not readme
.file_exists
then readme
= dirpath
.join_path
("README")
476 if readme
.file_exists
then
477 var mdoc
= load_markdown
(readme
)
479 mdoc
.original_mentity
= mgroup
482 mgroup
.filepath
= dirpath
483 mgroups
[rdp
] = mgroup
487 # Load a markdown file as a documentation object
488 fun load_markdown
(filepath
: String): MDoc
490 var s
= new FileReader.open
(filepath
)
491 var lines
= new Array[String]
492 var line_starts
= new Array[Int]
495 var line
= s
.read_line
498 len
+= line
.length
+ 1
501 var source
= new SourceFile.from_string
(filepath
, lines
.join
("\n"))
502 source
.line_starts
.add_all line_starts
503 var mdoc
= new MDoc(new Location(source
, 1, lines
.length
, 0, 0))
504 mdoc
.content
.add_all
(lines
)
508 # Force the identification of all ModulePath of the group and sub-groups in the file system.
510 # When a group is scanned, its sub-groups hierarchy is filled (see `MGroup::in_nesting`)
511 # and the potential modules (and nested modules) are identified (see `MGroup::module_paths`).
513 # Basically, this recursively call `get_mgroup` and `identify_file` on each directory entry.
515 # No-op if the group was already scanned (see `MGroup::scanned`).
516 fun scan_group
(mgroup
: MGroup) do
517 if mgroup
.scanned
then return
518 mgroup
.scanned
= true
519 var p
= mgroup
.filepath
520 # a virtual group has nothing to scan
521 if p
== null then return
524 var g
= identify_group
(fp
)
525 # Recursively scan for groups of the same package
528 else if g
.mpackage
== mgroup
.mpackage
then
534 # Transform relative paths (starting with '../') into absolute paths
535 private fun module_absolute_path
(path
: String): String do
539 # Try to load a module AST using a path.
540 # Display an error if there is a problem (IO / lexer / parser) and return null
541 fun load_module_ast
(filename
: String): nullable AModule
543 if not filename
.has_suffix
(".nit") then
544 self.toolcontext
.error
(null, "Error: file `{filename}` is not a valid nit module.")
547 if not filename
.file_exists
then
548 self.toolcontext
.error
(null, "Error: file `{filename}` not found.")
552 self.toolcontext
.info
("load module {filename}", 2)
555 var file
= new FileReader.open
(filename
)
556 var lexer
= new Lexer(new SourceFile(filename
, file
))
557 var parser
= new Parser(lexer
)
558 var tree
= parser
.parse
561 # Handle lexer and parser error
562 var nmodule
= tree
.n_base
563 if nmodule
== null then
564 var neof
= tree
.n_eof
565 assert neof
isa AError
566 error
(neof
, neof
.message
)
573 # Remove Nit source files from a list of arguments.
575 # Items of `args` that can be loaded as a nit file will be removed from `args` and returned.
576 fun filter_nit_source
(args
: Array[String]): Array[String]
578 var keep
= new Array[String]
579 var res
= new Array[String]
581 var l
= identify_module
(a
)
593 # Try to load a module using a path.
594 # Display an error if there is a problem (IO / lexer / parser) and return null.
595 # Note: usually, you do not need this method, use `get_mmodule_by_name` instead.
597 # The MModule is located, created, parsed and the importation is performed.
598 fun load_module
(filename
: String): nullable AModule
600 # Look for the module
601 var mmodule
= identify_module
(filename
)
602 if mmodule
== null then
603 if filename
.file_exists
then
604 toolcontext
.error
(null, "Error: `{filename}` is not a Nit source file.")
606 toolcontext
.error
(null, "Error: cannot find module `{filename}`.")
612 return mmodule
.load
(self)
615 # Injection of a new module without source.
616 # Used by the interpreter.
617 fun load_rt_module
(parent
: nullable MModule, nmodule
: AModule, mod_name
: String): nullable AModule
622 if parent
!= null then mgroup
= parent
.mgroup
623 var mmodule
= new MModule(model
, mgroup
, mod_name
, nmodule
.location
)
624 nmodule
.mmodule
= mmodule
625 nmodules
.add
(nmodule
)
626 self.mmodule2nmodule
[mmodule
] = nmodule
628 if parent
!= null then
629 var imported_modules
= new Array[MModule]
630 imported_modules
.add
(parent
)
631 mmodule
.set_visibility_for
(parent
, intrude_visibility
)
632 mmodule
.set_imported_mmodules
(imported_modules
)
634 build_module_importation
(nmodule
)
640 # Visit the AST and create the `MModule` object
641 private fun build_a_mmodule
(mgroup
: nullable MGroup, nmodule
: AModule)
643 var mmodule
= nmodule
.mmodule
644 assert mmodule
!= null
646 # Check the module name
647 var decl
= nmodule
.n_moduledecl
649 var decl_name
= decl
.n_name
.n_id
.text
650 if decl_name
!= mmodule
.name
then
651 error
(decl
.n_name
, "Error: module name mismatch; declared {decl_name} file named {mmodule.name}.")
655 # Check for conflicting module names in the package
656 if mgroup
!= null then
657 var others
= model
.get_mmodules_by_name
(mmodule
.name
)
658 if others
!= null then for other
in others
do
659 if other
!= mmodule
and mmodule2nmodule
.has_key
(mmodule
) and other
.mgroup
!= null and other
.mgroup
.mpackage
== mgroup
.mpackage
then
661 if decl
== null then node
= nmodule
else node
= decl
.n_name
662 error
(node
, "Error: a module named `{other.full_name}` already exists at {other.location}.")
668 nmodules
.add
(nmodule
)
669 self.mmodule2nmodule
[mmodule
] = nmodule
671 var source
= nmodule
.location
.file
672 if source
!= null then
673 assert source
.mmodule
== null
674 source
.mmodule
= mmodule
678 # Extract documentation
679 var ndoc
= decl
.n_doc
681 var mdoc
= ndoc
.to_mdoc
683 mdoc
.original_mentity
= mmodule
685 advice
(decl
, "missing-doc", "Documentation warning: Undocumented module `{mmodule}`")
687 # Is the module a test suite?
688 mmodule
.is_test_suite
= not decl
.get_annotations
("test_suite").is_empty
692 # Resolve the module identification for a given `AModuleName`.
694 # This method handles qualified names as used in `AModuleName`.
695 fun seach_module_by_amodule_name
(n_name
: AModuleName, mgroup
: nullable MGroup): nullable MModule
697 var mod_name
= n_name
.n_id
.text
699 # If a quad is given, we ignore the starting group (go from path)
700 if n_name
.n_quad
!= null then mgroup
= null
702 # If name not qualified, just search the name
703 if n_name
.n_path
.is_empty
then
704 # Fast search if no n_path
705 return search_mmodule_by_name
(n_name
, mgroup
, mod_name
)
708 # If qualified and in a group
709 if mgroup
!= null then
710 # First search in the package
711 var r
= mgroup
.mpackage
.root
714 # Get all modules with the final name
715 var res
= r
.mmodules_by_name
(mod_name
)
716 # Filter out the name that does not match the qualifiers
717 res
= [for x
in res
do if match_amodulename
(n_name
, x
) then x
]
718 if res
.not_empty
then
719 if res
.length
> 1 then
720 error
(n_name
, "Error: conflicting module files for `{mod_name}`: `{[for x in res do x.filepath or else x.full_name].join("`, `")}`")
726 # If no module yet, then assume that the first element of the path
727 # Is to be searched in the path.
728 var root_name
= n_name
.n_path
.first
.text
729 var roots
= search_group_in_paths
(root_name
, paths
)
730 if roots
.is_empty
then
731 error
(n_name
, "Error: cannot find `{root_name}`. Tried: {paths.join(", ")}.")
735 var res
= new ArraySet[MModule]
737 # Then, for each root, collect modules that matches the qualifiers
739 var root_res
= r
.mmodules_by_name
(mod_name
)
740 for x
in root_res
do if match_amodulename
(n_name
, x
) then res
.add x
742 if res
.not_empty
then
743 if res
.length
> 1 then
744 error
(n_name
, "Error: conflicting module files for `{mod_name}`: `{[for x in res do x.filepath or else x.full_name].join("`, `")}`")
748 # If still nothing, just call a basic search that will fail and will produce an error message
749 error
(n_name
, "Error: cannot find module `{mod_name}` from `{root_name}`. Tried: {paths.join(", ")}.")
753 # Is elements of `n_name` correspond to the group nesting of `m`?
755 # Basically it check that `bar::foo` matches `bar/foo.nit` and `bar/baz/foo.nit`
756 # but not `baz/foo.nit` nor `foo/bar.nit`
758 # Is used by `seach_module_by_amodule_name` to validate qualified names.
759 private fun match_amodulename
(n_name
: AModuleName, m
: MModule): Bool
761 var g
: nullable MGroup = m
.mgroup
762 for grp
in n_name
.n_path
.reverse_iterator
do
763 while g
!= null and grp
.text
!= g
.name
do
770 # Analyze the module importation and fill the module_importation_hierarchy
772 # Unless you used `load_module`, the importation is already done and this method does a no-op.
773 fun build_module_importation
(nmodule
: AModule)
775 if nmodule
.is_importation_done
then return
776 nmodule
.is_importation_done
= true
777 var mmodule
= nmodule
.mmodule
.as(not null)
779 var imported_modules
= new Array[MModule]
780 for aimport
in nmodule
.n_imports
do
781 # Do not imports conditional
782 var atconditionals
= aimport
.get_annotations
("conditional")
783 if atconditionals
.not_empty
then continue
786 if not aimport
isa AStdImport then
790 # Load the imported module
791 var sup
= seach_module_by_amodule_name
(aimport
.n_name
, mmodule
.mgroup
)
793 mmodule
.is_broken
= true
794 nmodule
.mmodule
= null # invalidate the module
795 continue # Skip error
797 var ast
= sup
.load
(self)
799 mmodule
.is_broken
= true
800 nmodule
.mmodule
= null # invalidate the module
801 continue # Skip error
804 aimport
.mmodule
= sup
805 imported_modules
.add
(sup
)
806 var mvisibility
= aimport
.n_visibility
.mvisibility
807 if mvisibility
== protected_visibility
then
808 mmodule
.is_broken
= true
809 error
(aimport
.n_visibility
, "Error: only properties can be protected.")
810 mmodule
.is_broken
= true
811 nmodule
.mmodule
= null # invalidate the module
814 if sup
== mmodule
then
815 error
(aimport
.n_name
, "Error: dependency loop in module {mmodule}.")
816 mmodule
.is_broken
= true
817 nmodule
.mmodule
= null # invalidate the module
819 if sup
.in_importation
< mmodule
then
820 error
(aimport
.n_name
, "Error: dependency loop between modules {mmodule} and {sup}.")
821 mmodule
.is_broken
= true
822 nmodule
.mmodule
= null # invalidate the module
825 mmodule
.set_visibility_for
(sup
, mvisibility
)
828 var mod_name
= "core"
829 var sup
= self.get_mmodule_by_name
(nmodule
, null, mod_name
)
831 mmodule
.is_broken
= true
832 nmodule
.mmodule
= null # invalidate the module
834 imported_modules
.add
(sup
)
835 mmodule
.set_visibility_for
(sup
, public_visibility
)
839 # Declare conditional importation
840 for aimport
in nmodule
.n_imports
do
841 if not aimport
isa AStdImport then continue
842 var atconditionals
= aimport
.get_annotations
("conditional")
843 if atconditionals
.is_empty
then continue
845 var suppath
= seach_module_by_amodule_name
(aimport
.n_name
, mmodule
.mgroup
)
846 if suppath
== null then continue # skip error
848 for atconditional
in atconditionals
do
849 var nargs
= atconditional
.n_args
850 if nargs
.is_empty
then
851 error
(atconditional
, "Syntax Error: `conditional` expects module identifiers as arguments.")
856 var rule
= new Array[MModule]
858 # First element is the goal, thus
861 # Second element is the first condition, that is to be a client of the current module
864 # Other condition are to be also a client of each modules indicated as arguments of the annotation
868 error
(narg
, "Syntax Error: `conditional` expects module identifier as arguments.")
872 var mp
= search_mmodule_by_name
(narg
, mmodule
.mgroup
, id
)
873 if mp
== null then continue
878 conditional_importations
.add rule
882 mmodule
.set_imported_mmodules
(imported_modules
)
884 apply_conditional_importations
(mmodule
)
886 self.toolcontext
.info
("{mmodule} imports {mmodule.in_importation.direct_greaters.join(", ")}", 3)
888 # Force `core` to be public if imported
889 for sup
in mmodule
.in_importation
.greaters
do
890 if sup
.name
== "core" then
891 mmodule
.set_visibility_for
(sup
, public_visibility
)
895 # TODO: Correctly check for useless importation
897 var directs
= mmodule
.in_importation
.direct_greaters
898 for nim
in nmodule
.n_imports
do
899 if not nim
isa AStdImport then continue
901 if im
== null then continue
902 if directs
.has
(im
) then continue
903 # This generates so much noise that it is simpler to just comment it
904 #warning(nim, "Warning: possible useless importation of {im}")
908 # Global list of conditional importation rules.
910 # Each rule is a "Horn clause"-like sequence of modules.
911 # It means that the first module is the module to automatically import.
912 # The remaining modules are the conditions of the rule.
914 # Rules are declared by `build_module_importation` and are applied by `apply_conditional_importations`
915 # (and `build_module_importation` that calls it).
917 # TODO (when the loader will be rewritten): use a better representation and move up rules in the model.
918 private var conditional_importations
= new Array[SequenceRead[MModule]]
920 # Extends the current importations according to imported rules about conditional importation
921 fun apply_conditional_importations
(mmodule
: MModule)
923 # Because a conditional importation may cause additional conditional importation, use a fixed point
924 # The rules are checked naively because we assume that it does not worth to be optimized
925 var check_conditional_importations
= true
926 while check_conditional_importations
do
927 check_conditional_importations
= false
929 for ci
in conditional_importations
do
931 for i
in [1..ci
.length
[ do
934 if not mmodule
.in_importation
.greaters
.has
(m
) then continue label
936 # Still here? It means that all conditions modules are loaded and imported
938 # Identify the module to automatically import
940 var ast
= sup
.load
(self)
941 if ast
== null then continue
943 # Do nothing if already imported
944 if mmodule
.in_importation
.greaters
.has
(sup
) then continue label
947 self.toolcontext
.info
("{mmodule} conditionally imports {sup}", 3)
948 # TODO visibility rules (currently always public)
949 mmodule
.set_visibility_for
(sup
, public_visibility
)
950 # TODO linearization rules (currently added at the end in the order of the rules)
951 mmodule
.set_imported_mmodules
([sup
])
953 # Prepare to reapply the rules
954 check_conditional_importations
= true
959 # All the loaded modules
960 var nmodules
= new Array[AModule]
962 # Register the nmodule associated to each mmodule
964 # Public clients need to use `mmodule2node` to access stuff.
965 private var mmodule2nmodule
= new HashMap[MModule, AModule]
967 # Retrieve the associated AST node of a mmodule.
968 # This method is used to associate model entity with syntactic entities.
970 # If the module is not associated with a node, returns null.
971 fun mmodule2node
(mmodule
: MModule): nullable AModule
973 return mmodule2nmodule
.get_or_null
(mmodule
)
978 # The path of the module source
979 var filepath
: nullable String = null
981 # Force the parsing of the module using `modelbuilder`.
983 # If the module was already parsed, the existing ASI is returned.
984 # Else the source file is loaded, and parsed and some
986 # The importation is not done by this
988 # REQUIRE: `filepath != null`
989 # ENSURE: `modelbuilder.parsed_modules.has(self)`
990 fun parse
(modelbuilder
: ModelBuilder): nullable AModule
992 # Already known and loaded? then return it
993 var nmodule
= modelbuilder
.mmodule2nmodule
.get_or_null
(self)
994 if nmodule
!= null then return nmodule
996 var filepath
= self.filepath
997 assert filepath
!= null
999 nmodule
= modelbuilder
.load_module_ast
(filepath
)
1000 if nmodule
== null then return null # forward error
1003 nmodule
.mmodule
= self
1004 modelbuilder
.build_a_mmodule
(mgroup
, nmodule
)
1006 modelbuilder
.parsed_modules
.add
self
1010 # Parse and process importation of a given MModule.
1012 # Basically chains `parse` and `build_module_importation`.
1013 fun load
(modelbuilder
: ModelBuilder): nullable AModule
1015 var nmodule
= parse
(modelbuilder
)
1016 if nmodule
== null then return null
1018 modelbuilder
.build_module_importation
(nmodule
)
1023 redef class MPackage
1024 # The associated `.ini` file, if any
1026 # The `ini` file is given as is and might contain invalid or missing information.
1028 # Some packages, like stand-alone packages or virtual packages have no `ini` file associated.
1029 var ini
: nullable ConfigTree = null
1033 # Is the group interesting for a final user?
1035 # Groups are mandatory in the model but for simple packages they are not
1036 # always interesting.
1038 # A interesting group has, at least, one of the following true:
1040 # * it has 2 modules or more
1041 # * it has a subgroup
1042 # * it has a documentation
1043 fun is_interesting
: Bool
1045 return mmodules
.length
> 1 or
1046 not in_nesting
.direct_smallers
.is_empty
or
1048 (mmodules
.length
== 1 and default_mmodule
== null)
1051 # Are files and directories in self scanned?
1053 # See `ModelBuilder::scan_group`.
1056 # Return the modules in self and subgroups named `name`.
1058 # If `self` is not scanned (see `ModelBuilder::scan_group`) the
1059 # results might be partial.
1060 fun mmodules_by_name
(name
: String): Array[MModule]
1062 var res
= new Array[MModule]
1063 for g
in in_nesting
.smallers
do
1064 for mp
in g
.mmodules
do
1065 if mp
.name
== name
then
1074 redef class SourceFile
1075 # Associated mmodule, once created
1076 var mmodule
: nullable MModule = null
1079 redef class AStdImport
1080 # The imported module once determined
1081 var mmodule
: nullable MModule = null
1085 # The associated MModule once build by a `ModelBuilder`
1086 var mmodule
: nullable MModule = null
1088 # Flag that indicate if the importation is already completed
1089 var is_importation_done
: Bool = false