Merge: Improve ini
[nit.git] / src / loader.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2012 Jean Privat <jean@pryen.org>
4 #
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
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
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.
16
17 # Loading of Nit source files
18 module loader
19
20 import modelbuilder_base
21 import ini
22
23 redef class ToolContext
24 # Option --path
25 var opt_path = new OptionArray("Set include path for loaders (may be used more than once)", "-I", "--path")
26
27 # Option --only-metamodel
28 var opt_only_metamodel = new OptionBool("Stop after meta-model processing", "--only-metamodel")
29
30 # Option --only-parse
31 var opt_only_parse = new OptionBool("Only proceed to parse step of loaders", "--only-parse")
32
33 redef init
34 do
35 super
36 option_context.add_option(opt_path, opt_only_parse, opt_only_metamodel)
37 end
38 end
39
40 redef class ModelBuilder
41 redef init
42 do
43 super
44
45 # Setup the paths value
46 paths.append(toolcontext.opt_path.value)
47
48 var path_env = "NIT_PATH".environ
49 if not path_env.is_empty then
50 paths.append(path_env.split_with(':'))
51 end
52
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)
58 end
59
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.
65 #
66 # Note: class and property model elements are not analysed.
67 fun parse(modules: Sequence[String]): Array[MModule]
68 do
69 var time0 = get_time
70 # Parse and recursively load
71 self.toolcontext.info("*** PARSE ***", 1)
72 var mmodules = new ArraySet[MModule]
73 for a in modules do
74 var nmodule = self.load_module(a)
75 if nmodule == null then continue # Skip error
76 # Load imported module
77 build_module_importation(nmodule)
78 var mmodule = nmodule.mmodule
79 if mmodule == null then continue # skip error
80 mmodules.add mmodule
81 end
82 var time1 = get_time
83 self.toolcontext.info("*** END PARSE: {time1-time0} ***", 2)
84
85 self.toolcontext.check_errors
86
87 if toolcontext.opt_only_parse.value then
88 self.toolcontext.info("*** ONLY PARSE...", 1)
89 exit(0)
90 end
91
92 return mmodules.to_a
93 end
94
95 # Load recursively all modules of the group `mgroup`.
96 # See `parse` for details.
97 fun parse_group(mgroup: MGroup): Array[MModule]
98 do
99 var res = new Array[MModule]
100 scan_group(mgroup)
101 for mg in mgroup.in_nesting.smallers do
102 for mp in mg.module_paths do
103 var nmodule = self.load_module(mp.filepath)
104 if nmodule == null then continue # Skip error
105 # Load imported module
106 build_module_importation(nmodule)
107 var mmodule = nmodule.mmodule
108 if mmodule == null then continue # Skip error
109 res.add mmodule
110 end
111 end
112 return res
113 end
114
115 # Load a bunch of modules and groups.
116 #
117 # Each name can be:
118 #
119 # * a path to a module, a group or a directory of projects.
120 # * a short name of a module or a group that are looked in the `paths` (-I)
121 #
122 # Then, for each entry, if it is:
123 #
124 # * a module, then is it parser and returned.
125 # * a group then recursively all its modules are parsed.
126 # * a directory of projects then all the modules of all projects are parsed.
127 # * else an error is displayed.
128 #
129 # See `parse` for details.
130 fun parse_full(names: Sequence[String]): Array[MModule]
131 do
132 var time0 = get_time
133 # Parse and recursively load
134 self.toolcontext.info("*** PARSE ***", 1)
135 var mmodules = new ArraySet[MModule]
136 for a in names do
137 # Case of a group
138 var mgroup = self.get_mgroup(a)
139 if mgroup != null then
140 mmodules.add_all parse_group(mgroup)
141 continue
142 end
143
144 # Case of a directory that is not a group
145 var stat = a.to_path.stat
146 if stat != null and stat.is_dir then
147 self.toolcontext.info("look in directory {a}", 2)
148 var fs = a.files
149 # Try each entry as a group or a module
150 for f in fs do
151 var af = a/f
152 mgroup = get_mgroup(af)
153 if mgroup != null then
154 mmodules.add_all parse_group(mgroup)
155 continue
156 end
157 var mp = identify_file(af)
158 if mp != null then
159 var nmodule = self.load_module(af)
160 if nmodule == null then continue # Skip error
161 build_module_importation(nmodule)
162 var mmodule = nmodule.mmodule
163 if mmodule == null then continue # Skip error
164 mmodules.add mmodule
165 else
166 self.toolcontext.info("ignore file {af}", 2)
167 end
168 end
169 continue
170 end
171
172 var nmodule = self.load_module(a)
173 if nmodule == null then continue # Skip error
174 # Load imported module
175 build_module_importation(nmodule)
176 var mmodule = nmodule.mmodule
177 if mmodule == null then continue # Skip error
178 mmodules.add mmodule
179 end
180 var time1 = get_time
181 self.toolcontext.info("*** END PARSE: {time1-time0} ***", 2)
182
183 self.toolcontext.check_errors
184
185 if toolcontext.opt_only_parse.value then
186 self.toolcontext.info("*** ONLY PARSE...", 1)
187 exit(0)
188 end
189
190 return mmodules.to_a
191 end
192
193 # The list of directories to search for top level modules
194 # The list is initially set with:
195 #
196 # * the toolcontext --path option
197 # * the NIT_PATH environment variable
198 # * `toolcontext.nit_dir`
199 # Path can be added (or removed) by the client
200 var paths = new Array[String]
201
202 # Like (and used by) `get_mmodule_by_name` but just return the ModulePath
203 fun search_mmodule_by_name(anode: nullable ANode, mgroup: nullable MGroup, name: String): nullable ModulePath
204 do
205 # First, look in groups
206 var c = mgroup
207 if c != null then
208 var r = c.mproject.root
209 assert r != null
210 scan_group(r)
211 var res = r.mmodule_paths_by_name(name)
212 if res.not_empty then return res.first
213 end
214
215 # Look at some known directories
216 var lookpaths = self.paths
217
218 # Look in the directory of the group project also (even if not explicitly in the path)
219 if mgroup != null then
220 # path of the root group
221 var dirname = mgroup.mproject.root.filepath
222 if dirname != null then
223 dirname = dirname.join_path("..").simplify_path
224 if not lookpaths.has(dirname) and dirname.file_exists then
225 lookpaths = lookpaths.to_a
226 lookpaths.add(dirname)
227 end
228 end
229 end
230
231 var candidate = search_module_in_paths(anode.hot_location, name, lookpaths)
232
233 if candidate == null then
234 if mgroup != null then
235 error(anode, "Error: cannot find module `{name}` from `{mgroup.name}`. Tried: {lookpaths.join(", ")}.")
236 else
237 error(anode, "Error: cannot find module `{name}`. Tried: {lookpaths.join(", ")}.")
238 end
239 return null
240 end
241 return candidate
242 end
243
244 # Get a module by its short name; if required, the module is loaded, parsed and its hierarchies computed.
245 # If `mgroup` is set, then the module search starts from it up to the top level (see `paths`);
246 # if `mgroup` is null then the module is searched in the top level only.
247 # If no module exists or there is a name conflict, then an error on `anode` is displayed and null is returned.
248 fun get_mmodule_by_name(anode: nullable ANode, mgroup: nullable MGroup, name: String): nullable MModule
249 do
250 var path = search_mmodule_by_name(anode, mgroup, name)
251 if path == null then return null # Forward error
252 return load_module_path(path)
253 end
254
255 # Load and process importation of a given ModulePath.
256 #
257 # Basically chains `load_module` and `build_module_importation`.
258 fun load_module_path(path: ModulePath): nullable MModule
259 do
260 var res = self.load_module(path.filepath)
261 if res == null then return null # Forward error
262 # Load imported module
263 build_module_importation(res)
264 return res.mmodule
265 end
266
267 # Search a module `name` from path `lookpaths`.
268 # If found, the path of the file is returned
269 private fun search_module_in_paths(location: nullable Location, name: String, lookpaths: Collection[String]): nullable ModulePath
270 do
271 var res = new ArraySet[ModulePath]
272 for dirname in lookpaths do
273 # Try a single module file
274 var mp = identify_file((dirname/"{name}.nit").simplify_path)
275 if mp != null then res.add mp
276 # Try the default module of a group
277 var g = get_mgroup((dirname/name).simplify_path)
278 if g != null then
279 scan_group(g)
280 res.add_all g.mmodule_paths_by_name(name)
281 end
282 end
283 if res.is_empty then return null
284 if res.length > 1 then
285 toolcontext.error(location, "Error: conflicting module files for `{name}`: `{res.join(",")}`")
286 end
287 return res.first
288 end
289
290 # Cache for `identify_file` by realpath
291 private var identified_files_by_path = new HashMap[String, nullable ModulePath]
292
293 # All the currently identified modules.
294 # See `identify_file`.
295 var identified_files = new Array[ModulePath]
296
297 # Identify a source file and load the associated project and groups if required.
298 #
299 # This method does what the user expects when giving an argument to a Nit tool.
300 #
301 # * If `path` is an existing Nit source file (with the `.nit` extension),
302 # then the associated ModulePath is returned
303 # * If `path` is a directory (with a `/`),
304 # then the ModulePath of its default module is returned (if any)
305 # * If `path` is a simple identifier (eg. `digraph`),
306 # then the main module of the project `digraph` is searched in `paths` and returned.
307 #
308 # Silently return `null` if `path` does not exists or cannot be identified.
309 fun identify_file(path: String): nullable ModulePath
310 do
311 # special case for not a nit file
312 if path.file_extension != "nit" then
313 # search dirless files in known -I paths
314 if not path.chars.has('/') then
315 var res = search_module_in_paths(null, path, self.paths)
316 if res != null then return res
317 end
318
319 # Found nothing? maybe it is a group...
320 var candidate = null
321 if path.file_exists then
322 var mgroup = get_mgroup(path)
323 if mgroup != null then
324 var owner_path = mgroup.filepath.join_path(mgroup.name + ".nit")
325 if owner_path.file_exists then candidate = owner_path
326 end
327 end
328
329 if candidate == null then
330 return null
331 end
332 path = candidate
333 end
334
335 # Does the file exists?
336 if not path.file_exists then
337 return null
338 end
339
340 # Fast track, the path is already known
341 var pn = path.basename(".nit")
342 var rp = module_absolute_path(path)
343 if identified_files_by_path.has_key(rp) then return identified_files_by_path[rp]
344
345 # Search for a group
346 var mgrouppath = path.join_path("..").simplify_path
347 var mgroup = get_mgroup(mgrouppath)
348
349 if mgroup == null then
350 # singleton project
351 var mproject = new MProject(pn, model)
352 mgroup = new MGroup(pn, mproject, null) # same name for the root group
353 mgroup.filepath = path
354 mproject.root = mgroup
355 toolcontext.info("found singleton project `{pn}` at {path}", 2)
356
357 # Attach homonymous `ini` file to the project
358 var inipath = path.dirname / "{pn}.ini"
359 if inipath.file_exists then
360 var ini = new ConfigTree(inipath)
361 mproject.ini = ini
362 end
363 end
364
365 var res = new ModulePath(pn, path, mgroup)
366 mgroup.module_paths.add(res)
367
368 identified_files_by_path[rp] = res
369 identified_files.add(res)
370 return res
371 end
372
373 # Groups by path
374 private var mgroups = new HashMap[String, nullable MGroup]
375
376 # Return the mgroup associated to a directory path.
377 # If the directory is not a group null is returned.
378 #
379 # Note: `paths` is also used to look for mgroups
380 fun get_mgroup(dirpath: String): nullable MGroup
381 do
382 if not dirpath.file_exists then do
383 for p in paths do
384 var try = p / dirpath
385 if try.file_exists then
386 dirpath = try
387 break label
388 end
389 end
390 return null
391 end label
392
393 var rdp = module_absolute_path(dirpath)
394 if mgroups.has_key(rdp) then
395 return mgroups[rdp]
396 end
397
398 # Filter out non-directories
399 var stat = dirpath.file_stat
400 if stat == null or not stat.is_dir then
401 mgroups[rdp] = null
402 return null
403 end
404
405 # By default, the name of the project or group is the base_name of the directory
406 var pn = rdp.basename(".nit")
407
408 # Check `project.ini` that indicate a project
409 var ini = null
410 var parent = null
411 var inipath = dirpath / "project.ini"
412 if inipath.file_exists then
413 ini = new ConfigTree(inipath)
414 end
415
416 if ini == null then
417 # No ini, multiple course of action
418
419 # The root of the directory hierarchy in the file system.
420 if rdp == "/" then
421 mgroups[rdp] = null
422 return null
423 end
424
425 # Special stopper `projects.ini`
426 if (dirpath/"projects.ini").file_exists then
427 # dirpath cannot be a project since it is a project directory
428 mgroups[rdp] = null
429 return null
430 end
431
432 # check the parent directory (if it does not contain the stopper file)
433 var parentpath = dirpath.join_path("..").simplify_path
434 var stopper = parentpath / "projects.ini"
435 if not stopper.file_exists then
436 # Recursively get the parent group
437 parent = get_mgroup(parentpath)
438 if parent == null then
439 # Parent is not a group, thus we are not a group either
440 mgroups[rdp] = null
441 return null
442 end
443 end
444 end
445
446 var mgroup
447 if parent == null then
448 # no parent, thus new project
449 var namekey = "project.name"
450 if ini != null and ini.has_key(namekey) then pn = ini[namekey]
451 var mproject = new MProject(pn, model)
452 mgroup = new MGroup(pn, mproject, null) # same name for the root group
453 mproject.root = mgroup
454 toolcontext.info("found project `{mproject}` at {dirpath}", 2)
455 mproject.ini = ini
456 else
457 mgroup = new MGroup(pn, parent.mproject, parent)
458 toolcontext.info("found sub group `{mgroup.full_name}` at {dirpath}", 2)
459 end
460
461 # search documentation
462 # in src first so the documentation of the project code can be distinct for the documentation of the project usage
463 var readme = dirpath.join_path("README.md")
464 if not readme.file_exists then readme = dirpath.join_path("README")
465 if readme.file_exists then
466 var mdoc = load_markdown(readme)
467 mgroup.mdoc = mdoc
468 mdoc.original_mentity = mgroup
469 end
470
471 mgroup.filepath = dirpath
472 mgroups[rdp] = mgroup
473 return mgroup
474 end
475
476 # Load a markdown file as a documentation object
477 fun load_markdown(filepath: String): MDoc
478 do
479 var s = new FileReader.open(filepath)
480 var lines = new Array[String]
481 var line_starts = new Array[Int]
482 var len = 1
483 while not s.eof do
484 var line = s.read_line
485 lines.add(line)
486 line_starts.add(len)
487 len += line.length + 1
488 end
489 s.close
490 var source = new SourceFile.from_string(filepath, lines.join("\n"))
491 source.line_starts.add_all line_starts
492 var mdoc = new MDoc(new Location(source, 1, lines.length, 0, 0))
493 mdoc.content.add_all(lines)
494 return mdoc
495 end
496
497 # Force the identification of all ModulePath of the group and sub-groups in the file system.
498 #
499 # When a group is scanned, its sub-groups hierarchy is filled (see `MGroup::in_nesting`)
500 # and the potential modules (and nested modules) are identified (see `MGroup::module_paths`).
501 #
502 # Basically, this recursively call `get_mgroup` and `identify_file` on each directory entry.
503 #
504 # No-op if the group was already scanned (see `MGroup::scanned`).
505 fun scan_group(mgroup: MGroup) do
506 if mgroup.scanned then return
507 mgroup.scanned = true
508 var p = mgroup.filepath
509 # a virtual group has nothing to scan
510 if p == null then return
511 for f in p.files do
512 var fp = p/f
513 var g = get_mgroup(fp)
514 # Recursively scan for groups of the same project
515 if g != null and g.mproject == mgroup.mproject then
516 scan_group(g)
517 end
518 identify_file(fp)
519 end
520 end
521
522 # Transform relative paths (starting with '../') into absolute paths
523 private fun module_absolute_path(path: String): String do
524 return getcwd.join_path(path).simplify_path
525 end
526
527 # Try to load a module AST using a path.
528 # Display an error if there is a problem (IO / lexer / parser) and return null
529 fun load_module_ast(filename: String): nullable AModule
530 do
531 if filename.file_extension != "nit" then
532 self.toolcontext.error(null, "Error: file `{filename}` is not a valid nit module.")
533 return null
534 end
535 if not filename.file_exists then
536 self.toolcontext.error(null, "Error: file `{filename}` not found.")
537 return null
538 end
539
540 self.toolcontext.info("load module {filename}", 2)
541
542 # Load the file
543 var file = new FileReader.open(filename)
544 var lexer = new Lexer(new SourceFile(filename, file))
545 var parser = new Parser(lexer)
546 var tree = parser.parse
547 file.close
548
549 # Handle lexer and parser error
550 var nmodule = tree.n_base
551 if nmodule == null then
552 var neof = tree.n_eof
553 assert neof isa AError
554 error(neof, neof.message)
555 return null
556 end
557
558 return nmodule
559 end
560
561 # Remove Nit source files from a list of arguments.
562 #
563 # Items of `args` that can be loaded as a nit file will be removed from `args` and returned.
564 fun filter_nit_source(args: Array[String]): Array[String]
565 do
566 var keep = new Array[String]
567 var res = new Array[String]
568 for a in args do
569 var l = identify_file(a)
570 if l == null then
571 keep.add a
572 else
573 res.add a
574 end
575 end
576 args.clear
577 args.add_all(keep)
578 return res
579 end
580
581 # Try to load a module using a path.
582 # Display an error if there is a problem (IO / lexer / parser) and return null.
583 # Note: usually, you do not need this method, use `get_mmodule_by_name` instead.
584 #
585 # The MModule is created however, the importation is not performed,
586 # therefore you should call `build_module_importation`.
587 fun load_module(filename: String): nullable AModule
588 do
589 # Look for the module
590 var file = identify_file(filename)
591 if file == null then
592 if filename.file_exists then
593 toolcontext.error(null, "Error: `{filename}` is not a Nit source file.")
594 else
595 toolcontext.error(null, "Error: cannot find module `{filename}`.")
596 end
597 return null
598 end
599
600 # Already known and loaded? then return it
601 var mmodule = file.mmodule
602 if mmodule != null then
603 return mmodule2nmodule[mmodule]
604 end
605
606 # Load it manually
607 var nmodule = load_module_ast(file.filepath)
608 if nmodule == null then return null # forward error
609
610 # build the mmodule and load imported modules
611 mmodule = build_a_mmodule(file.mgroup, file.name, nmodule)
612
613 if mmodule == null then return null # forward error
614
615 # Update the file information
616 file.mmodule = mmodule
617
618 return nmodule
619 end
620
621 # Injection of a new module without source.
622 # Used by the interpreter.
623 fun load_rt_module(parent: nullable MModule, nmodule: AModule, mod_name: String): nullable AModule
624 do
625 # Create the module
626
627 var mgroup = null
628 if parent != null then mgroup = parent.mgroup
629 var mmodule = new MModule(model, mgroup, mod_name, nmodule.location)
630 nmodule.mmodule = mmodule
631 nmodules.add(nmodule)
632 self.mmodule2nmodule[mmodule] = nmodule
633
634 if parent!= null then
635 var imported_modules = new Array[MModule]
636 imported_modules.add(parent)
637 mmodule.set_visibility_for(parent, intrude_visibility)
638 mmodule.set_imported_mmodules(imported_modules)
639 else
640 build_module_importation(nmodule)
641 end
642
643 return nmodule
644 end
645
646 # Visit the AST and create the `MModule` object
647 private fun build_a_mmodule(mgroup: nullable MGroup, mod_name: String, nmodule: AModule): nullable MModule
648 do
649 # Check the module name
650 var decl = nmodule.n_moduledecl
651 if decl != null then
652 var decl_name = decl.n_name.n_id.text
653 if decl_name != mod_name then
654 error(decl.n_name, "Error: module name mismatch; declared {decl_name} file named {mod_name}.")
655 end
656 end
657
658 # Check for conflicting module names in the project
659 if mgroup != null then
660 var others = model.get_mmodules_by_name(mod_name)
661 if others != null then for other in others do
662 if other.mgroup!= null and other.mgroup.mproject == mgroup.mproject then
663 var node: ANode
664 if decl == null then node = nmodule else node = decl.n_name
665 error(node, "Error: a module named `{other.full_name}` already exists at {other.location}.")
666 break
667 end
668 end
669 end
670
671 # Create the module
672 var mmodule = new MModule(model, mgroup, mod_name, nmodule.location)
673 nmodule.mmodule = mmodule
674 nmodules.add(nmodule)
675 self.mmodule2nmodule[mmodule] = nmodule
676
677 var source = nmodule.location.file
678 if source != null then
679 assert source.mmodule == null
680 source.mmodule = mmodule
681 end
682
683 if decl != null then
684 # Extract documentation
685 var ndoc = decl.n_doc
686 if ndoc != null then
687 var mdoc = ndoc.to_mdoc
688 mmodule.mdoc = mdoc
689 mdoc.original_mentity = mmodule
690 else
691 advice(decl, "missing-doc", "Documentation warning: Undocumented module `{mmodule}`")
692 end
693 # Is the module a test suite?
694 mmodule.is_test_suite = not decl.get_annotations("test_suite").is_empty
695 end
696
697 return mmodule
698 end
699
700 # Resolve the module identification for a given `AModuleName`.
701 #
702 # This method handles qualified names as used in `AModuleName`.
703 fun seach_module_by_amodule_name(n_name: AModuleName, mgroup: nullable MGroup): nullable ModulePath
704 do
705 if n_name.n_quad != null then mgroup = null # Start from top level
706 for grp in n_name.n_path do
707 var path = search_mmodule_by_name(grp, mgroup, grp.text)
708 if path == null then return null # Forward error
709 mgroup = path.mgroup
710 end
711 var mod_name = n_name.n_id.text
712 return search_mmodule_by_name(n_name, mgroup, mod_name)
713 end
714
715 # Analyze the module importation and fill the module_importation_hierarchy
716 #
717 # Unless you used `load_module`, the importation is already done and this method does a no-op.
718 fun build_module_importation(nmodule: AModule)
719 do
720 if nmodule.is_importation_done then return
721 nmodule.is_importation_done = true
722 var mmodule = nmodule.mmodule.as(not null)
723 var stdimport = true
724 var imported_modules = new Array[MModule]
725 for aimport in nmodule.n_imports do
726 # Do not imports conditional
727 var atconditionals = aimport.get_annotations("conditional")
728 if atconditionals.not_empty then continue
729
730 stdimport = false
731 if not aimport isa AStdImport then
732 continue
733 end
734
735 # Load the imported module
736 var suppath = seach_module_by_amodule_name(aimport.n_name, mmodule.mgroup)
737 if suppath == null then
738 nmodule.mmodule = null # invalidate the module
739 continue # Skip error
740 end
741 var sup = load_module_path(suppath)
742 if sup == null then
743 nmodule.mmodule = null # invalidate the module
744 continue # Skip error
745 end
746
747 aimport.mmodule = sup
748 imported_modules.add(sup)
749 var mvisibility = aimport.n_visibility.mvisibility
750 if mvisibility == protected_visibility then
751 error(aimport.n_visibility, "Error: only properties can be protected.")
752 nmodule.mmodule = null # invalidate the module
753 return
754 end
755 if sup == mmodule then
756 error(aimport.n_name, "Error: dependency loop in module {mmodule}.")
757 nmodule.mmodule = null # invalidate the module
758 end
759 if sup.in_importation < mmodule then
760 error(aimport.n_name, "Error: dependency loop between modules {mmodule} and {sup}.")
761 nmodule.mmodule = null # invalidate the module
762 return
763 end
764 mmodule.set_visibility_for(sup, mvisibility)
765 end
766 if stdimport then
767 var mod_name = "core"
768 var sup = self.get_mmodule_by_name(nmodule, null, mod_name)
769 if sup == null then
770 nmodule.mmodule = null # invalidate the module
771 else # Skip error
772 imported_modules.add(sup)
773 mmodule.set_visibility_for(sup, public_visibility)
774 end
775 end
776
777 # Declare conditional importation
778 for aimport in nmodule.n_imports do
779 if not aimport isa AStdImport then continue
780 var atconditionals = aimport.get_annotations("conditional")
781 if atconditionals.is_empty then continue
782
783 var suppath = seach_module_by_amodule_name(aimport.n_name, mmodule.mgroup)
784 if suppath == null then continue # skip error
785
786 for atconditional in atconditionals do
787 var nargs = atconditional.n_args
788 if nargs.is_empty then
789 error(atconditional, "Syntax Error: `conditional` expects module identifiers as arguments.")
790 continue
791 end
792
793 # The rule
794 var rule = new Array[Object]
795
796 # First element is the goal, thus
797 rule.add suppath
798
799 # Second element is the first condition, that is to be a client of the current module
800 rule.add mmodule
801
802 # Other condition are to be also a client of each modules indicated as arguments of the annotation
803 for narg in nargs do
804 var id = narg.as_id
805 if id == null then
806 error(narg, "Syntax Error: `conditional` expects module identifier as arguments.")
807 continue
808 end
809
810 var mp = search_mmodule_by_name(narg, mmodule.mgroup, id)
811 if mp == null then continue
812
813 rule.add mp
814 end
815
816 conditional_importations.add rule
817 end
818 end
819
820 mmodule.set_imported_mmodules(imported_modules)
821
822 apply_conditional_importations(mmodule)
823
824 self.toolcontext.info("{mmodule} imports {mmodule.in_importation.direct_greaters.join(", ")}", 3)
825
826 # Force `core` to be public if imported
827 for sup in mmodule.in_importation.greaters do
828 if sup.name == "core" then
829 mmodule.set_visibility_for(sup, public_visibility)
830 end
831 end
832
833 # TODO: Correctly check for useless importation
834 # It is even doable?
835 var directs = mmodule.in_importation.direct_greaters
836 for nim in nmodule.n_imports do
837 if not nim isa AStdImport then continue
838 var im = nim.mmodule
839 if im == null then continue
840 if directs.has(im) then continue
841 # This generates so much noise that it is simpler to just comment it
842 #warning(nim, "Warning: possible useless importation of {im}")
843 end
844 end
845
846 # Global list of conditional importation rules.
847 #
848 # Each rule is a "Horn clause"-like sequence of modules.
849 # It means that the first module is the module to automatically import.
850 # The remaining modules are the conditions of the rule.
851 #
852 # Each module is either represented by a MModule (if the module is already loaded)
853 # or by a ModulePath (if the module is not yet loaded).
854 #
855 # Rules are declared by `build_module_importation` and are applied by `apply_conditional_importations`
856 # (and `build_module_importation` that calls it).
857 #
858 # TODO (when the loader will be rewritten): use a better representation and move up rules in the model.
859 private var conditional_importations = new Array[SequenceRead[Object]]
860
861 # Extends the current importations according to imported rules about conditional importation
862 fun apply_conditional_importations(mmodule: MModule)
863 do
864 # Because a conditional importation may cause additional conditional importation, use a fixed point
865 # The rules are checked naively because we assume that it does not worth to be optimized
866 var check_conditional_importations = true
867 while check_conditional_importations do
868 check_conditional_importations = false
869
870 for ci in conditional_importations do
871 # Check conditions
872 for i in [1..ci.length[ do
873 var rule_element = ci[i]
874 # An element of a rule is either a MModule or a ModulePath
875 # We need the mmodule to resonate on the importation
876 var m
877 if rule_element isa MModule then
878 m = rule_element
879 else if rule_element isa ModulePath then
880 m = rule_element.mmodule
881 # Is loaded?
882 if m == null then continue label
883 else
884 abort
885 end
886 # Is imported?
887 if not mmodule.in_importation.greaters.has(m) then continue label
888 end
889 # Still here? It means that all conditions modules are loaded and imported
890
891 # Identify the module to automatically import
892 var suppath = ci.first.as(ModulePath)
893 var sup = load_module_path(suppath)
894 if sup == null then continue
895
896 # Do nothing if already imported
897 if mmodule.in_importation.greaters.has(sup) then continue label
898
899 # Import it
900 self.toolcontext.info("{mmodule} conditionally imports {sup}", 3)
901 # TODO visibility rules (currently always public)
902 mmodule.set_visibility_for(sup, public_visibility)
903 # TODO linearization rules (currently added at the end in the order of the rules)
904 mmodule.set_imported_mmodules([sup])
905
906 # Prepare to reapply the rules
907 check_conditional_importations = true
908 end label
909 end
910 end
911
912 # All the loaded modules
913 var nmodules = new Array[AModule]
914
915 # Register the nmodule associated to each mmodule
916 #
917 # Public clients need to use `mmodule2node` to access stuff.
918 private var mmodule2nmodule = new HashMap[MModule, AModule]
919
920 # Retrieve the associated AST node of a mmodule.
921 # This method is used to associate model entity with syntactic entities.
922 #
923 # If the module is not associated with a node, returns null.
924 fun mmodule2node(mmodule: MModule): nullable AModule
925 do
926 return mmodule2nmodule.get_or_null(mmodule)
927 end
928 end
929
930 # File-system location of a module (file) that is identified but not always loaded.
931 class ModulePath
932 # The name of the module
933 # (it's the basename of the filepath)
934 var name: String
935
936 # The human path of the module
937 var filepath: String
938
939 # The group (and the project) of the possible module
940 var mgroup: MGroup
941
942 # The loaded module (if any)
943 var mmodule: nullable MModule = null
944
945 redef fun to_s do return filepath
946 end
947
948 redef class MProject
949 # The associated `.ini` file, if any
950 #
951 # The `ini` file is given as is and might contain invalid or missing information.
952 #
953 # Some projects, like stand-alone projects or virtual projects have no `ini` file associated.
954 var ini: nullable ConfigTree = null
955 end
956
957 redef class MGroup
958 # Modules paths associated with the group
959 var module_paths = new Array[ModulePath]
960
961 # Is the group interesting for a final user?
962 #
963 # Groups are mandatory in the model but for simple projects they are not
964 # always interesting.
965 #
966 # A interesting group has, at least, one of the following true:
967 #
968 # * it has 2 modules or more
969 # * it has a subgroup
970 # * it has a documentation
971 fun is_interesting: Bool
972 do
973 return module_paths.length > 1 or
974 mmodules.length > 1 or
975 not in_nesting.direct_smallers.is_empty or
976 mdoc != null or
977 (mmodules.length == 1 and default_mmodule == null)
978 end
979
980 # Are files and directories in self scanned?
981 #
982 # See `ModelBuilder::scan_group`.
983 var scanned = false
984
985 # Return the modules in self and subgroups named `name`.
986 #
987 # If `self` is not scanned (see `ModelBuilder::scan_group`) the
988 # results might be partial.
989 fun mmodule_paths_by_name(name: String): Array[ModulePath]
990 do
991 var res = new Array[ModulePath]
992 for g in in_nesting.smallers do
993 for mp in g.module_paths do
994 if mp.name == name then
995 res.add mp
996 end
997 end
998 end
999 return res
1000 end
1001 end
1002
1003 redef class SourceFile
1004 # Associated mmodule, once created
1005 var mmodule: nullable MModule = null
1006 end
1007
1008 redef class AStdImport
1009 # The imported module once determined
1010 var mmodule: nullable MModule = null
1011 end
1012
1013 redef class AModule
1014 # The associated MModule once build by a `ModelBuilder`
1015 var mmodule: nullable MModule
1016 # Flag that indicate if the importation is already completed
1017 var is_importation_done: Bool = false
1018 end