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
22 redef class ToolContext
24 var opt_path
= new OptionArray("Set include path for loaders (may be used more than once)", "-I", "--path")
26 # Option --only-metamodel
27 var opt_only_metamodel
= new OptionBool("Stop after meta-model processing", "--only-metamodel")
30 var opt_only_parse
= new OptionBool("Only proceed to parse step of loaders", "--only-parse")
35 option_context
.add_option
(opt_path
, opt_only_parse
, opt_only_metamodel
)
39 redef class ModelBuilder
44 # Setup the paths value
45 paths
.append
(toolcontext
.opt_path
.value
)
47 var path_env
= "NIT_PATH".environ
48 if not path_env
.is_empty
then
49 paths
.append
(path_env
.split_with
(':'))
52 var nit_dir
= toolcontext
.nit_dir
53 var libname
= nit_dir
/"lib"
54 if libname
.file_exists
then paths
.add
(libname
)
55 libname
= nit_dir
/"contrib"
56 if libname
.file_exists
then paths
.add
(libname
)
59 # Load a bunch of modules.
60 # `modules` can contains filenames or module names.
61 # Imported modules are automatically loaded and modelized.
62 # The result is the corresponding model elements.
63 # Errors and warnings are printed with the toolcontext.
65 # Note: class and property model elements are not analysed.
66 fun parse
(modules
: Sequence[String]): Array[MModule]
69 # Parse and recursively load
70 self.toolcontext
.info
("*** PARSE ***", 1)
71 var mmodules
= new ArraySet[MModule]
73 var nmodule
= self.load_module
(a
)
74 if nmodule
== null then continue # Skip error
75 # Load imported module
76 build_module_importation
(nmodule
)
77 var mmodule
= nmodule
.mmodule
78 if mmodule
== null then continue # skip error
82 self.toolcontext
.info
("*** END PARSE: {time1-time0} ***", 2)
84 self.toolcontext
.check_errors
86 if toolcontext
.opt_only_parse
.value
then
87 self.toolcontext
.info
("*** ONLY PARSE...", 1)
94 # Load recursively all modules of the group `mgroup`.
95 # See `parse` for details.
96 fun parse_group
(mgroup
: MGroup): Array[MModule]
98 var res
= new Array[MModule]
100 for mg
in mgroup
.in_nesting
.smallers
do
101 for mp
in mg
.module_paths
do
102 var nmodule
= self.load_module
(mp
.filepath
)
103 if nmodule
== null then continue # Skip error
104 # Load imported module
105 build_module_importation
(nmodule
)
106 var mmodule
= nmodule
.mmodule
107 if mmodule
== null then continue # Skip error
114 # Load a bunch of modules and groups.
118 # * a path to a module, a group or a directory of projects.
119 # * a short name of a module or a group that are looked in the `paths` (-I)
121 # Then, for each entry, if it is:
123 # * a module, then is it parser and returned.
124 # * a group then recursively all its modules are parsed.
125 # * a directory of projects then all the modules of all projects are parsed.
126 # * else an error is displayed.
128 # See `parse` for details.
129 fun parse_full
(names
: Sequence[String]): Array[MModule]
132 # Parse and recursively load
133 self.toolcontext
.info
("*** PARSE ***", 1)
134 var mmodules
= new ArraySet[MModule]
137 var mgroup
= self.get_mgroup
(a
)
138 if mgroup
!= null then
139 mmodules
.add_all parse_group
(mgroup
)
143 # Case of a directory that is not a group
144 var stat
= a
.to_path
.stat
145 if stat
!= null and stat
.is_dir
then
146 self.toolcontext
.info
("look in directory {a}", 2)
148 # Try each entry as a group or a module
151 mgroup
= get_mgroup
(af
)
152 if mgroup
!= null then
153 mmodules
.add_all parse_group
(mgroup
)
156 var mp
= identify_file
(af
)
158 var nmodule
= self.load_module
(af
)
159 if nmodule
== null then continue # Skip error
160 build_module_importation
(nmodule
)
161 var mmodule
= nmodule
.mmodule
162 if mmodule
== null then continue # Skip error
165 self.toolcontext
.info
("ignore file {af}", 2)
171 var nmodule
= self.load_module
(a
)
172 if nmodule
== null then continue # Skip error
173 # Load imported module
174 build_module_importation
(nmodule
)
175 var mmodule
= nmodule
.mmodule
176 if mmodule
== null then continue # Skip error
180 self.toolcontext
.info
("*** END PARSE: {time1-time0} ***", 2)
182 self.toolcontext
.check_errors
184 if toolcontext
.opt_only_parse
.value
then
185 self.toolcontext
.info
("*** ONLY PARSE...", 1)
192 # The list of directories to search for top level modules
193 # The list is initially set with:
195 # * the toolcontext --path option
196 # * the NIT_PATH environment variable
197 # * `toolcontext.nit_dir`
198 # Path can be added (or removed) by the client
199 var paths
= new Array[String]
201 # Like (and used by) `get_mmodule_by_name` but just return the ModulePath
202 fun search_mmodule_by_name
(anode
: nullable ANode, mgroup
: nullable MGroup, name
: String): nullable ModulePath
204 # First, look in groups
207 var dirname
= c
.filepath
208 if dirname
== null then break # virtual group
209 if dirname
.has_suffix
(".nit") then break # singleton project
211 # Second, try the directory to find a file
212 var try_file
= dirname
+ "/" + name
+ ".nit"
213 if try_file
.file_exists
then
214 var res
= self.identify_file
(try_file
.simplify_path
)
219 # Third, try if the requested module is itself a group
220 try_file
= dirname
+ "/" + name
+ "/" + name
+ ".nit"
221 if try_file
.file_exists
then
222 var res
= self.identify_file
(try_file
.simplify_path
)
227 # Fourth, try if the requested module is itself a group with a src
228 try_file
= dirname
+ "/" + name
+ "/src/" + name
+ ".nit"
229 if try_file
.file_exists
then
230 var res
= self.identify_file
(try_file
.simplify_path
)
238 # Look at some known directories
239 var lookpaths
= self.paths
241 # Look in the directory of the group project also (even if not explicitly in the path)
242 if mgroup
!= null then
243 # path of the root group
244 var dirname
= mgroup
.mproject
.root
.filepath
245 if dirname
!= null then
246 dirname
= dirname
.join_path
("..").simplify_path
247 if not lookpaths
.has
(dirname
) and dirname
.file_exists
then
248 lookpaths
= lookpaths
.to_a
249 lookpaths
.add
(dirname
)
254 var candidate
= search_module_in_paths
(anode
.hot_location
, name
, lookpaths
)
256 if candidate
== null then
257 if mgroup
!= null then
258 error
(anode
, "Error: cannot find module `{name}` from `{mgroup.name}`. Tried: {lookpaths.join(", ")}.")
260 error
(anode
, "Error: cannot find module `{name}`. Tried: {lookpaths.join(", ")}.")
267 # Get a module by its short name; if required, the module is loaded, parsed and its hierarchies computed.
268 # If `mgroup` is set, then the module search starts from it up to the top level (see `paths`);
269 # if `mgroup` is null then the module is searched in the top level only.
270 # If no module exists or there is a name conflict, then an error on `anode` is displayed and null is returned.
271 fun get_mmodule_by_name
(anode
: nullable ANode, mgroup
: nullable MGroup, name
: String): nullable MModule
273 var path
= search_mmodule_by_name
(anode
, mgroup
, name
)
274 if path
== null then return null # Forward error
275 return load_module_path
(path
)
278 # Load and process importation of a given ModulePath.
280 # Basically chains `load_module` and `build_module_importation`.
281 fun load_module_path
(path
: ModulePath): nullable MModule
283 var res
= self.load_module
(path
.filepath
)
284 if res
== null then return null # Forward error
285 # Load imported module
286 build_module_importation
(res
)
290 # Search a module `name` from path `lookpaths`.
291 # If found, the path of the file is returned
292 private fun search_module_in_paths
(location
: nullable Location, name
: String, lookpaths
: Collection[String]): nullable ModulePath
294 var candidate
: nullable String = null
295 for dirname
in lookpaths
do
296 var try_file
= (dirname
+ "/" + name
+ ".nit").simplify_path
297 if try_file
.file_exists
then
298 if candidate
== null then
300 else if candidate
!= try_file
then
301 # try to disambiguate conflicting modules
302 var abs_candidate
= module_absolute_path
(candidate
)
303 var abs_try_file
= module_absolute_path
(try_file
)
304 if abs_candidate
!= abs_try_file
then
305 toolcontext
.error
(location
, "Error: conflicting module file for `{name}`: `{candidate}` `{try_file}`")
309 try_file
= (dirname
+ "/" + name
+ "/" + name
+ ".nit").simplify_path
310 if try_file
.file_exists
then
311 if candidate
== null then
313 else if candidate
!= try_file
then
314 # try to disambiguate conflicting modules
315 var abs_candidate
= module_absolute_path
(candidate
)
316 var abs_try_file
= module_absolute_path
(try_file
)
317 if abs_candidate
!= abs_try_file
then
318 toolcontext
.error
(location
, "Error: conflicting module file for `{name}`: `{candidate}` `{try_file}`")
322 try_file
= (dirname
+ "/" + name
+ "/src/" + name
+ ".nit").simplify_path
323 if try_file
.file_exists
then
324 if candidate
== null then
326 else if candidate
!= try_file
then
327 # try to disambiguate conflicting modules
328 var abs_candidate
= module_absolute_path
(candidate
)
329 var abs_try_file
= module_absolute_path
(try_file
)
330 if abs_candidate
!= abs_try_file
then
331 toolcontext
.error
(location
, "Error: conflicting module file for `{name}`: `{candidate}` `{try_file}`")
336 if candidate
== null then return null
337 return identify_file
(candidate
)
340 # Cache for `identify_file` by realpath
341 private var identified_files_by_path
= new HashMap[String, nullable ModulePath]
343 # All the currently identified modules.
344 # See `identify_file`.
345 var identified_files
= new Array[ModulePath]
347 # Identify a source file and load the associated project and groups if required.
349 # This method does what the user expects when giving an argument to a Nit tool.
351 # * If `path` is an existing Nit source file (with the `.nit` extension),
352 # then the associated ModulePath is returned
353 # * If `path` is a directory (with a `/`),
354 # then the ModulePath of its default module is returned (if any)
355 # * If `path` is a simple identifier (eg. `digraph`),
356 # then the main module of the project `digraph` is searched in `paths` and returned.
358 # Silently return `null` if `path` does not exists or cannot be identified.
359 fun identify_file
(path
: String): nullable ModulePath
361 # special case for not a nit file
362 if path
.file_extension
!= "nit" then
363 # search dirless files in known -I paths
364 if not path
.chars
.has
('/') then
365 var res
= search_module_in_paths
(null, path
, self.paths
)
366 if res
!= null then return res
369 # Found nothing? maybe it is a group...
371 if path
.file_exists
then
372 var mgroup
= get_mgroup
(path
)
373 if mgroup
!= null then
374 var owner_path
= mgroup
.filepath
.join_path
(mgroup
.name
+ ".nit")
375 if owner_path
.file_exists
then candidate
= owner_path
379 if candidate
== null then
385 # Does the file exists?
386 if not path
.file_exists
then
390 # Fast track, the path is already known
391 var pn
= path
.basename
(".nit")
392 var rp
= module_absolute_path
(path
)
393 if identified_files_by_path
.has_key
(rp
) then return identified_files_by_path
[rp
]
396 var mgrouppath
= path
.join_path
("..").simplify_path
397 var mgroup
= get_mgroup
(mgrouppath
)
399 if mgroup
== null then
401 var mproject
= new MProject(pn
, model
)
402 mgroup
= new MGroup(pn
, mproject
, null) # same name for the root group
403 mgroup
.filepath
= path
404 mproject
.root
= mgroup
405 toolcontext
.info
("found project `{pn}` at {path}", 2)
408 var res
= new ModulePath(pn
, path
, mgroup
)
409 mgroup
.module_paths
.add
(res
)
411 identified_files_by_path
[rp
] = res
412 identified_files
.add
(res
)
417 private var mgroups
= new HashMap[String, nullable MGroup]
419 # Return the mgroup associated to a directory path.
420 # If the directory is not a group null is returned.
422 # Note: `paths` is also used to look for mgroups
423 fun get_mgroup
(dirpath
: String): nullable MGroup
425 if not dirpath
.file_exists
then do
427 var try
= p
/ dirpath
428 if try
.file_exists
then
436 var rdp
= module_absolute_path
(dirpath
)
437 if mgroups
.has_key
(rdp
) then
441 # Hack, a group is determined by one of the following:
442 # * the presence of a honomymous nit file
443 # * the fact that the directory is named `src`
444 # * the fact that there is a sub-directory named `src`
445 var pn
= rdp
.basename
(".nit")
446 var mp
= dirpath
.join_path
(pn
+ ".nit").simplify_path
448 # dirpath2 is the root directory
449 # dirpath is the src subdirectory directory, if any, else it is the same that dirpath2
450 var dirpath2
= dirpath
451 if not mp
.file_exists
then
453 # With a src directory, the group name is the name of the parent directory
454 dirpath2
= rdp
.dirname
455 pn
= dirpath2
.basename
457 # Check a `src` subdirectory
458 dirpath
= dirpath2
/ "src"
459 if not dirpath
.file_exists
then
460 # All rules failed, so return null
466 # check parent directory
467 var parentpath
= dirpath2
.join_path
("..").simplify_path
468 var parent
= get_mgroup
(parentpath
)
471 if parent
== null then
472 # no parent, thus new project
473 var mproject
= new MProject(pn
, model
)
474 mgroup
= new MGroup(pn
, mproject
, null) # same name for the root group
475 mproject
.root
= mgroup
476 toolcontext
.info
("found project `{mproject}` at {dirpath}", 2)
478 mgroup
= new MGroup(pn
, parent
.mproject
, parent
)
479 toolcontext
.info
("found sub group `{mgroup.full_name}` at {dirpath}", 2)
482 # search documentation
483 # in src first so the documentation of the project code can be distinct for the documentation of the project usage
484 var readme
= dirpath
.join_path
("README.md")
485 if not readme
.file_exists
then readme
= dirpath
.join_path
("README")
486 if not readme
.file_exists
then readme
= dirpath2
.join_path
("README.md")
487 if not readme
.file_exists
then readme
= dirpath2
.join_path
("README")
488 if readme
.file_exists
then
489 var mdoc
= load_markdown
(readme
)
491 mdoc
.original_mentity
= mgroup
494 mgroup
.filepath
= dirpath
495 mgroups
[module_absolute_path
(dirpath
)] = mgroup
496 mgroups
[module_absolute_path
(dirpath2
)] = mgroup
500 # Load a markdown file as a documentation object
501 fun load_markdown
(filepath
: String): MDoc
503 var s
= new FileReader.open
(filepath
)
504 var lines
= new Array[String]
505 var line_starts
= new Array[Int]
508 var line
= s
.read_line
511 len
+= line
.length
+ 1
514 var source
= new SourceFile.from_string
(filepath
, lines
.join
("\n"))
515 source
.line_starts
.add_all line_starts
516 var mdoc
= new MDoc(new Location(source
, 1, lines
.length
, 0, 0))
517 mdoc
.content
.add_all
(lines
)
521 # Force the identification of all ModulePath of the group and sub-groups in the file system.
523 # When a group is scanned, its sub-groups hierarchy is filled (see `MGroup::in_nesting`)
524 # and the potential modules (and nested modules) are identified (see `MGroup::module_paths`).
526 # Basically, this recursively call `get_mgroup` and `identify_file` on each directory entry.
528 # No-op if the group was already scanned (see `MGroup::scanned`).
529 fun scan_group
(mgroup
: MGroup) do
530 if mgroup
.scanned
then return
531 mgroup
.scanned
= true
532 var p
= mgroup
.filepath
533 # a virtual group has nothing to scan
534 if p
== null then return
537 var g
= get_mgroup
(fp
)
538 if g
!= null then scan_group
(g
)
543 # Transform relative paths (starting with '../') into absolute paths
544 private fun module_absolute_path
(path
: String): String do
545 return getcwd
.join_path
(path
).simplify_path
548 # Try to load a module AST using a path.
549 # Display an error if there is a problem (IO / lexer / parser) and return null
550 fun load_module_ast
(filename
: String): nullable AModule
552 if filename
.file_extension
!= "nit" then
553 self.toolcontext
.error
(null, "Error: file `{filename}` is not a valid nit module.")
556 if not filename
.file_exists
then
557 self.toolcontext
.error
(null, "Error: file `{filename}` not found.")
561 self.toolcontext
.info
("load module {filename}", 2)
564 var file
= new FileReader.open
(filename
)
565 var lexer
= new Lexer(new SourceFile(filename
, file
))
566 var parser
= new Parser(lexer
)
567 var tree
= parser
.parse
570 # Handle lexer and parser error
571 var nmodule
= tree
.n_base
572 if nmodule
== null then
573 var neof
= tree
.n_eof
574 assert neof
isa AError
575 error
(neof
, neof
.message
)
582 # Remove Nit source files from a list of arguments.
584 # Items of `args` that can be loaded as a nit file will be removed from `args` and returned.
585 fun filter_nit_source
(args
: Array[String]): Array[String]
587 var keep
= new Array[String]
588 var res
= new Array[String]
590 var l
= identify_file
(a
)
602 # Try to load a module using a path.
603 # Display an error if there is a problem (IO / lexer / parser) and return null.
604 # Note: usually, you do not need this method, use `get_mmodule_by_name` instead.
606 # The MModule is created however, the importation is not performed,
607 # therefore you should call `build_module_importation`.
608 fun load_module
(filename
: String): nullable AModule
610 # Look for the module
611 var file
= identify_file
(filename
)
613 if filename
.file_exists
then
614 toolcontext
.error
(null, "Error: `{filename}` is not a Nit source file.")
616 toolcontext
.error
(null, "Error: cannot find module `{filename}`.")
621 # Already known and loaded? then return it
622 var mmodule
= file
.mmodule
623 if mmodule
!= null then
624 return mmodule2nmodule
[mmodule
]
628 var nmodule
= load_module_ast
(file
.filepath
)
629 if nmodule
== null then return null # forward error
631 # build the mmodule and load imported modules
632 mmodule
= build_a_mmodule
(file
.mgroup
, file
.name
, nmodule
)
634 if mmodule
== null then return null # forward error
636 # Update the file information
637 file
.mmodule
= mmodule
642 # Injection of a new module without source.
643 # Used by the interpreter.
644 fun load_rt_module
(parent
: nullable MModule, nmodule
: AModule, mod_name
: String): nullable AModule
649 if parent
!= null then mgroup
= parent
.mgroup
650 var mmodule
= new MModule(model
, mgroup
, mod_name
, nmodule
.location
)
651 nmodule
.mmodule
= mmodule
652 nmodules
.add
(nmodule
)
653 self.mmodule2nmodule
[mmodule
] = nmodule
655 if parent
!= null then
656 var imported_modules
= new Array[MModule]
657 imported_modules
.add
(parent
)
658 mmodule
.set_visibility_for
(parent
, intrude_visibility
)
659 mmodule
.set_imported_mmodules
(imported_modules
)
661 build_module_importation
(nmodule
)
667 # Visit the AST and create the `MModule` object
668 private fun build_a_mmodule
(mgroup
: nullable MGroup, mod_name
: String, nmodule
: AModule): nullable MModule
670 # Check the module name
671 var decl
= nmodule
.n_moduledecl
673 var decl_name
= decl
.n_name
.n_id
.text
674 if decl_name
!= mod_name
then
675 error
(decl
.n_name
, "Error: module name mismatch; declared {decl_name} file named {mod_name}.")
679 # Check for conflicting module names in the project
680 if mgroup
!= null then
681 var others
= model
.get_mmodules_by_name
(mod_name
)
682 if others
!= null then for other
in others
do
683 if other
.mgroup
!= null and other
.mgroup
.mproject
== mgroup
.mproject
then
685 if decl
== null then node
= nmodule
else node
= decl
.n_name
686 error
(node
, "Error: a module named `{other.full_name}` already exists at {other.location}.")
693 var mmodule
= new MModule(model
, mgroup
, mod_name
, nmodule
.location
)
694 nmodule
.mmodule
= mmodule
695 nmodules
.add
(nmodule
)
696 self.mmodule2nmodule
[mmodule
] = nmodule
698 var source
= nmodule
.location
.file
699 if source
!= null then
700 assert source
.mmodule
== null
701 source
.mmodule
= mmodule
705 # Extract documentation
706 var ndoc
= decl
.n_doc
708 var mdoc
= ndoc
.to_mdoc
710 mdoc
.original_mentity
= mmodule
712 advice
(decl
, "missing-doc", "Documentation warning: Undocumented module `{mmodule}`")
714 # Is the module a test suite?
715 mmodule
.is_test_suite
= not decl
.get_annotations
("test_suite").is_empty
721 # Resolve the module identification for a given `AModuleName`.
723 # This method handles qualified names as used in `AModuleName`.
724 fun seach_module_by_amodule_name
(n_name
: AModuleName, mgroup
: nullable MGroup): nullable ModulePath
726 if n_name
.n_quad
!= null then mgroup
= null # Start from top level
727 for grp
in n_name
.n_path
do
728 var path
= search_mmodule_by_name
(grp
, mgroup
, grp
.text
)
729 if path
== null then return null # Forward error
732 var mod_name
= n_name
.n_id
.text
733 return search_mmodule_by_name
(n_name
, mgroup
, mod_name
)
736 # Analyze the module importation and fill the module_importation_hierarchy
738 # Unless you used `load_module`, the importation is already done and this method does a no-op.
739 fun build_module_importation
(nmodule
: AModule)
741 if nmodule
.is_importation_done
then return
742 nmodule
.is_importation_done
= true
743 var mmodule
= nmodule
.mmodule
.as(not null)
745 var imported_modules
= new Array[MModule]
746 for aimport
in nmodule
.n_imports
do
747 # Do not imports conditional
748 var atconditionals
= aimport
.get_annotations
("conditional")
749 if atconditionals
.not_empty
then continue
752 if not aimport
isa AStdImport then
756 # Load the imported module
757 var suppath
= seach_module_by_amodule_name
(aimport
.n_name
, mmodule
.mgroup
)
758 if suppath
== null then
759 nmodule
.mmodule
= null # invalidate the module
760 continue # Skip error
762 var sup
= load_module_path
(suppath
)
764 nmodule
.mmodule
= null # invalidate the module
765 continue # Skip error
768 aimport
.mmodule
= sup
769 imported_modules
.add
(sup
)
770 var mvisibility
= aimport
.n_visibility
.mvisibility
771 if mvisibility
== protected_visibility
then
772 error
(aimport
.n_visibility
, "Error: only properties can be protected.")
773 nmodule
.mmodule
= null # invalidate the module
776 if sup
== mmodule
then
777 error
(aimport
.n_name
, "Error: dependency loop in module {mmodule}.")
778 nmodule
.mmodule
= null # invalidate the module
780 if sup
.in_importation
< mmodule
then
781 error
(aimport
.n_name
, "Error: dependency loop between modules {mmodule} and {sup}.")
782 nmodule
.mmodule
= null # invalidate the module
785 mmodule
.set_visibility_for
(sup
, mvisibility
)
788 var mod_name
= "standard"
789 var sup
= self.get_mmodule_by_name
(nmodule
, null, mod_name
)
791 nmodule
.mmodule
= null # invalidate the module
793 imported_modules
.add
(sup
)
794 mmodule
.set_visibility_for
(sup
, public_visibility
)
798 # Declare conditional importation
799 for aimport
in nmodule
.n_imports
do
800 if not aimport
isa AStdImport then continue
801 var atconditionals
= aimport
.get_annotations
("conditional")
802 if atconditionals
.is_empty
then continue
804 var suppath
= seach_module_by_amodule_name
(aimport
.n_name
, mmodule
.mgroup
)
805 if suppath
== null then continue # skip error
807 for atconditional
in atconditionals
do
808 var nargs
= atconditional
.n_args
809 if nargs
.is_empty
then
810 error
(atconditional
, "Syntax Error: `conditional` expects module identifiers as arguments.")
815 var rule
= new Array[Object]
817 # First element is the goal, thus
820 # Second element is the first condition, that is to be a client of the current module
823 # Other condition are to be also a client of each modules indicated as arguments of the annotation
827 error
(narg
, "Syntax Error: `conditional` expects module identifier as arguments.")
831 var mp
= search_mmodule_by_name
(narg
, mmodule
.mgroup
, id
)
832 if mp
== null then continue
837 conditional_importations
.add rule
841 mmodule
.set_imported_mmodules
(imported_modules
)
843 apply_conditional_importations
(mmodule
)
845 self.toolcontext
.info
("{mmodule} imports {mmodule.in_importation.direct_greaters.join(", ")}", 3)
847 # Force standard to be public if imported
848 for sup
in mmodule
.in_importation
.greaters
do
849 if sup
.name
== "standard" then
850 mmodule
.set_visibility_for
(sup
, public_visibility
)
854 # TODO: Correctly check for useless importation
856 var directs
= mmodule
.in_importation
.direct_greaters
857 for nim
in nmodule
.n_imports
do
858 if not nim
isa AStdImport then continue
860 if im
== null then continue
861 if directs
.has
(im
) then continue
862 # This generates so much noise that it is simpler to just comment it
863 #warning(nim, "Warning: possible useless importation of {im}")
867 # Global list of conditional importation rules.
869 # Each rule is a "Horn clause"-like sequence of modules.
870 # It means that the first module is the module to automatically import.
871 # The remaining modules are the conditions of the rule.
873 # Each module is either represented by a MModule (if the module is already loaded)
874 # or by a ModulePath (if the module is not yet loaded).
876 # Rules are declared by `build_module_importation` and are applied by `apply_conditional_importations`
877 # (and `build_module_importation` that calls it).
879 # TODO (when the loader will be rewritten): use a better representation and move up rules in the model.
880 private var conditional_importations
= new Array[SequenceRead[Object]]
882 # Extends the current importations according to imported rules about conditional importation
883 fun apply_conditional_importations
(mmodule
: MModule)
885 # Because a conditional importation may cause additional conditional importation, use a fixed point
886 # The rules are checked naively because we assume that it does not worth to be optimized
887 var check_conditional_importations
= true
888 while check_conditional_importations
do
889 check_conditional_importations
= false
891 for ci
in conditional_importations
do
893 for i
in [1..ci
.length
[ do
894 var rule_element
= ci
[i
]
895 # An element of a rule is either a MModule or a ModulePath
896 # We need the mmodule to resonate on the importation
898 if rule_element
isa MModule then
900 else if rule_element
isa ModulePath then
901 m
= rule_element
.mmodule
903 if m
== null then continue label
908 if not mmodule
.in_importation
.greaters
.has
(m
) then continue label
910 # Still here? It means that all conditions modules are loaded and imported
912 # Identify the module to automatically import
913 var suppath
= ci
.first
.as(ModulePath)
914 var sup
= load_module_path
(suppath
)
915 if sup
== null then continue
917 # Do nothing if already imported
918 if mmodule
.in_importation
.greaters
.has
(sup
) then continue label
921 self.toolcontext
.info
("{mmodule} conditionally imports {sup}", 3)
922 # TODO visibility rules (currently always public)
923 mmodule
.set_visibility_for
(sup
, public_visibility
)
924 # TODO linearization rules (currently added at the end in the order of the rules)
925 mmodule
.set_imported_mmodules
([sup
])
927 # Prepare to reapply the rules
928 check_conditional_importations
= true
933 # All the loaded modules
934 var nmodules
= new Array[AModule]
936 # Register the nmodule associated to each mmodule
938 # Public clients need to use `mmodule2node` to access stuff.
939 private var mmodule2nmodule
= new HashMap[MModule, AModule]
941 # Retrieve the associated AST node of a mmodule.
942 # This method is used to associate model entity with syntactic entities.
944 # If the module is not associated with a node, returns null.
945 fun mmodule2node
(mmodule
: MModule): nullable AModule
947 return mmodule2nmodule
.get_or_null
(mmodule
)
951 # File-system location of a module (file) that is identified but not always loaded.
953 # The name of the module
954 # (it's the basename of the filepath)
957 # The human path of the module
960 # The group (and the project) of the possible module
963 # The loaded module (if any)
964 var mmodule
: nullable MModule = null
966 redef fun to_s
do return filepath
970 # Modules paths associated with the group
971 var module_paths
= new Array[ModulePath]
973 # Is the group interesting for a final user?
975 # Groups are mandatory in the model but for simple projects they are not
976 # always interesting.
978 # A interesting group has, at least, one of the following true:
980 # * it has 2 modules or more
981 # * it has a subgroup
982 # * it has a documentation
983 fun is_interesting
: Bool
985 return module_paths
.length
> 1 or
986 mmodules
.length
> 1 or
987 not in_nesting
.direct_smallers
.is_empty
or
989 (mmodules
.length
== 1 and default_mmodule
== null)
992 # Are files and directories in self scanned?
994 # See `ModelBuilder::scan_group`.
998 redef class SourceFile
999 # Associated mmodule, once created
1000 var mmodule
: nullable MModule = null
1003 redef class AStdImport
1004 # The imported module once determined
1005 var mmodule
: nullable MModule = null
1009 # The associated MModule once build by a `ModelBuilder`
1010 var mmodule
: nullable MModule
1011 # Flag that indicate if the importation is already completed
1012 var is_importation_done
: Bool = false