loader: get_mgroup check and assign the `project.ini` file to projects
[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 end
357
358 var res = new ModulePath(pn, path, mgroup)
359 mgroup.module_paths.add(res)
360
361 identified_files_by_path[rp] = res
362 identified_files.add(res)
363 return res
364 end
365
366 # Groups by path
367 private var mgroups = new HashMap[String, nullable MGroup]
368
369 # Return the mgroup associated to a directory path.
370 # If the directory is not a group null is returned.
371 #
372 # Note: `paths` is also used to look for mgroups
373 fun get_mgroup(dirpath: String): nullable MGroup
374 do
375 if not dirpath.file_exists then do
376 for p in paths do
377 var try = p / dirpath
378 if try.file_exists then
379 dirpath = try
380 break label
381 end
382 end
383 return null
384 end label
385
386 var rdp = module_absolute_path(dirpath)
387 if mgroups.has_key(rdp) then
388 return mgroups[rdp]
389 end
390
391 # Filter out non-directories
392 var stat = dirpath.file_stat
393 if stat == null or not stat.is_dir then
394 mgroups[rdp] = null
395 return null
396 end
397
398 # Hack, a group is determined by one of the following:
399 # * the presence of a honomymous nit file
400 # * the fact that the directory is named `src`
401 # * the fact that there is a sub-directory named `src`
402 var pn = rdp.basename(".nit")
403 var mp = dirpath.join_path(pn + ".nit").simplify_path
404
405 # Check `project.ini` that indicate a project
406 var ini = null
407 var parent = null
408 var inipath = dirpath / "project.ini"
409 if inipath.file_exists then
410 ini = new ConfigTree(inipath)
411 end
412
413 # dirpath2 is the root directory
414 # dirpath is the src subdirectory directory, if any, else it is the same that dirpath2
415 var dirpath2 = dirpath
416 if not mp.file_exists then
417 if pn == "src" then
418 # With a src directory, the group name is the name of the parent directory
419 dirpath2 = rdp.dirname
420 pn = dirpath2.basename
421 else
422 # Check a `src` subdirectory
423 dirpath = dirpath2 / "src"
424 if not dirpath.file_exists then
425 # All rules failed, so return null
426 return null
427 end
428 end
429 end
430
431 # check parent directory
432 var parentpath = dirpath2.join_path("..").simplify_path
433 var parent = get_mgroup(parentpath)
434
435 var mgroup
436 if parent == null then
437 # no parent, thus new project
438 if ini != null and ini.has_key("name") then pn = ini["name"]
439 var mproject = new MProject(pn, model)
440 mgroup = new MGroup(pn, mproject, null) # same name for the root group
441 mproject.root = mgroup
442 toolcontext.info("found project `{mproject}` at {dirpath}", 2)
443 mproject.ini = ini
444 else
445 mgroup = new MGroup(pn, parent.mproject, parent)
446 toolcontext.info("found sub group `{mgroup.full_name}` at {dirpath}", 2)
447 end
448
449 # search documentation
450 # in src first so the documentation of the project code can be distinct for the documentation of the project usage
451 var readme = dirpath.join_path("README.md")
452 if not readme.file_exists then readme = dirpath.join_path("README")
453 if not readme.file_exists then readme = dirpath2.join_path("README.md")
454 if not readme.file_exists then readme = dirpath2.join_path("README")
455 if readme.file_exists then
456 var mdoc = load_markdown(readme)
457 mgroup.mdoc = mdoc
458 mdoc.original_mentity = mgroup
459 end
460
461 mgroup.filepath = dirpath
462 mgroups[module_absolute_path(dirpath)] = mgroup
463 mgroups[module_absolute_path(dirpath2)] = mgroup
464 return mgroup
465 end
466
467 # Load a markdown file as a documentation object
468 fun load_markdown(filepath: String): MDoc
469 do
470 var s = new FileReader.open(filepath)
471 var lines = new Array[String]
472 var line_starts = new Array[Int]
473 var len = 1
474 while not s.eof do
475 var line = s.read_line
476 lines.add(line)
477 line_starts.add(len)
478 len += line.length + 1
479 end
480 s.close
481 var source = new SourceFile.from_string(filepath, lines.join("\n"))
482 source.line_starts.add_all line_starts
483 var mdoc = new MDoc(new Location(source, 1, lines.length, 0, 0))
484 mdoc.content.add_all(lines)
485 return mdoc
486 end
487
488 # Force the identification of all ModulePath of the group and sub-groups in the file system.
489 #
490 # When a group is scanned, its sub-groups hierarchy is filled (see `MGroup::in_nesting`)
491 # and the potential modules (and nested modules) are identified (see `MGroup::module_paths`).
492 #
493 # Basically, this recursively call `get_mgroup` and `identify_file` on each directory entry.
494 #
495 # No-op if the group was already scanned (see `MGroup::scanned`).
496 fun scan_group(mgroup: MGroup) do
497 if mgroup.scanned then return
498 mgroup.scanned = true
499 var p = mgroup.filepath
500 # a virtual group has nothing to scan
501 if p == null then return
502 for f in p.files do
503 var fp = p/f
504 var g = get_mgroup(fp)
505 # Recursively scan for groups of the same project
506 if g != null and g.mproject == mgroup.mproject then
507 scan_group(g)
508 end
509 identify_file(fp)
510 end
511 end
512
513 # Transform relative paths (starting with '../') into absolute paths
514 private fun module_absolute_path(path: String): String do
515 return getcwd.join_path(path).simplify_path
516 end
517
518 # Try to load a module AST using a path.
519 # Display an error if there is a problem (IO / lexer / parser) and return null
520 fun load_module_ast(filename: String): nullable AModule
521 do
522 if filename.file_extension != "nit" then
523 self.toolcontext.error(null, "Error: file `{filename}` is not a valid nit module.")
524 return null
525 end
526 if not filename.file_exists then
527 self.toolcontext.error(null, "Error: file `{filename}` not found.")
528 return null
529 end
530
531 self.toolcontext.info("load module {filename}", 2)
532
533 # Load the file
534 var file = new FileReader.open(filename)
535 var lexer = new Lexer(new SourceFile(filename, file))
536 var parser = new Parser(lexer)
537 var tree = parser.parse
538 file.close
539
540 # Handle lexer and parser error
541 var nmodule = tree.n_base
542 if nmodule == null then
543 var neof = tree.n_eof
544 assert neof isa AError
545 error(neof, neof.message)
546 return null
547 end
548
549 return nmodule
550 end
551
552 # Remove Nit source files from a list of arguments.
553 #
554 # Items of `args` that can be loaded as a nit file will be removed from `args` and returned.
555 fun filter_nit_source(args: Array[String]): Array[String]
556 do
557 var keep = new Array[String]
558 var res = new Array[String]
559 for a in args do
560 var l = identify_file(a)
561 if l == null then
562 keep.add a
563 else
564 res.add a
565 end
566 end
567 args.clear
568 args.add_all(keep)
569 return res
570 end
571
572 # Try to load a module using a path.
573 # Display an error if there is a problem (IO / lexer / parser) and return null.
574 # Note: usually, you do not need this method, use `get_mmodule_by_name` instead.
575 #
576 # The MModule is created however, the importation is not performed,
577 # therefore you should call `build_module_importation`.
578 fun load_module(filename: String): nullable AModule
579 do
580 # Look for the module
581 var file = identify_file(filename)
582 if file == null then
583 if filename.file_exists then
584 toolcontext.error(null, "Error: `{filename}` is not a Nit source file.")
585 else
586 toolcontext.error(null, "Error: cannot find module `{filename}`.")
587 end
588 return null
589 end
590
591 # Already known and loaded? then return it
592 var mmodule = file.mmodule
593 if mmodule != null then
594 return mmodule2nmodule[mmodule]
595 end
596
597 # Load it manually
598 var nmodule = load_module_ast(file.filepath)
599 if nmodule == null then return null # forward error
600
601 # build the mmodule and load imported modules
602 mmodule = build_a_mmodule(file.mgroup, file.name, nmodule)
603
604 if mmodule == null then return null # forward error
605
606 # Update the file information
607 file.mmodule = mmodule
608
609 return nmodule
610 end
611
612 # Injection of a new module without source.
613 # Used by the interpreter.
614 fun load_rt_module(parent: nullable MModule, nmodule: AModule, mod_name: String): nullable AModule
615 do
616 # Create the module
617
618 var mgroup = null
619 if parent != null then mgroup = parent.mgroup
620 var mmodule = new MModule(model, mgroup, mod_name, nmodule.location)
621 nmodule.mmodule = mmodule
622 nmodules.add(nmodule)
623 self.mmodule2nmodule[mmodule] = nmodule
624
625 if parent!= null then
626 var imported_modules = new Array[MModule]
627 imported_modules.add(parent)
628 mmodule.set_visibility_for(parent, intrude_visibility)
629 mmodule.set_imported_mmodules(imported_modules)
630 else
631 build_module_importation(nmodule)
632 end
633
634 return nmodule
635 end
636
637 # Visit the AST and create the `MModule` object
638 private fun build_a_mmodule(mgroup: nullable MGroup, mod_name: String, nmodule: AModule): nullable MModule
639 do
640 # Check the module name
641 var decl = nmodule.n_moduledecl
642 if decl != null then
643 var decl_name = decl.n_name.n_id.text
644 if decl_name != mod_name then
645 error(decl.n_name, "Error: module name mismatch; declared {decl_name} file named {mod_name}.")
646 end
647 end
648
649 # Check for conflicting module names in the project
650 if mgroup != null then
651 var others = model.get_mmodules_by_name(mod_name)
652 if others != null then for other in others do
653 if other.mgroup!= null and other.mgroup.mproject == mgroup.mproject then
654 var node: ANode
655 if decl == null then node = nmodule else node = decl.n_name
656 error(node, "Error: a module named `{other.full_name}` already exists at {other.location}.")
657 break
658 end
659 end
660 end
661
662 # Create the module
663 var mmodule = new MModule(model, mgroup, mod_name, nmodule.location)
664 nmodule.mmodule = mmodule
665 nmodules.add(nmodule)
666 self.mmodule2nmodule[mmodule] = nmodule
667
668 var source = nmodule.location.file
669 if source != null then
670 assert source.mmodule == null
671 source.mmodule = mmodule
672 end
673
674 if decl != null then
675 # Extract documentation
676 var ndoc = decl.n_doc
677 if ndoc != null then
678 var mdoc = ndoc.to_mdoc
679 mmodule.mdoc = mdoc
680 mdoc.original_mentity = mmodule
681 else
682 advice(decl, "missing-doc", "Documentation warning: Undocumented module `{mmodule}`")
683 end
684 # Is the module a test suite?
685 mmodule.is_test_suite = not decl.get_annotations("test_suite").is_empty
686 end
687
688 return mmodule
689 end
690
691 # Resolve the module identification for a given `AModuleName`.
692 #
693 # This method handles qualified names as used in `AModuleName`.
694 fun seach_module_by_amodule_name(n_name: AModuleName, mgroup: nullable MGroup): nullable ModulePath
695 do
696 if n_name.n_quad != null then mgroup = null # Start from top level
697 for grp in n_name.n_path do
698 var path = search_mmodule_by_name(grp, mgroup, grp.text)
699 if path == null then return null # Forward error
700 mgroup = path.mgroup
701 end
702 var mod_name = n_name.n_id.text
703 return search_mmodule_by_name(n_name, mgroup, mod_name)
704 end
705
706 # Analyze the module importation and fill the module_importation_hierarchy
707 #
708 # Unless you used `load_module`, the importation is already done and this method does a no-op.
709 fun build_module_importation(nmodule: AModule)
710 do
711 if nmodule.is_importation_done then return
712 nmodule.is_importation_done = true
713 var mmodule = nmodule.mmodule.as(not null)
714 var stdimport = true
715 var imported_modules = new Array[MModule]
716 for aimport in nmodule.n_imports do
717 # Do not imports conditional
718 var atconditionals = aimport.get_annotations("conditional")
719 if atconditionals.not_empty then continue
720
721 stdimport = false
722 if not aimport isa AStdImport then
723 continue
724 end
725
726 # Load the imported module
727 var suppath = seach_module_by_amodule_name(aimport.n_name, mmodule.mgroup)
728 if suppath == null then
729 nmodule.mmodule = null # invalidate the module
730 continue # Skip error
731 end
732 var sup = load_module_path(suppath)
733 if sup == null then
734 nmodule.mmodule = null # invalidate the module
735 continue # Skip error
736 end
737
738 aimport.mmodule = sup
739 imported_modules.add(sup)
740 var mvisibility = aimport.n_visibility.mvisibility
741 if mvisibility == protected_visibility then
742 error(aimport.n_visibility, "Error: only properties can be protected.")
743 nmodule.mmodule = null # invalidate the module
744 return
745 end
746 if sup == mmodule then
747 error(aimport.n_name, "Error: dependency loop in module {mmodule}.")
748 nmodule.mmodule = null # invalidate the module
749 end
750 if sup.in_importation < mmodule then
751 error(aimport.n_name, "Error: dependency loop between modules {mmodule} and {sup}.")
752 nmodule.mmodule = null # invalidate the module
753 return
754 end
755 mmodule.set_visibility_for(sup, mvisibility)
756 end
757 if stdimport then
758 var mod_name = "standard"
759 var sup = self.get_mmodule_by_name(nmodule, null, mod_name)
760 if sup == null then
761 nmodule.mmodule = null # invalidate the module
762 else # Skip error
763 imported_modules.add(sup)
764 mmodule.set_visibility_for(sup, public_visibility)
765 end
766 end
767
768 # Declare conditional importation
769 for aimport in nmodule.n_imports do
770 if not aimport isa AStdImport then continue
771 var atconditionals = aimport.get_annotations("conditional")
772 if atconditionals.is_empty then continue
773
774 var suppath = seach_module_by_amodule_name(aimport.n_name, mmodule.mgroup)
775 if suppath == null then continue # skip error
776
777 for atconditional in atconditionals do
778 var nargs = atconditional.n_args
779 if nargs.is_empty then
780 error(atconditional, "Syntax Error: `conditional` expects module identifiers as arguments.")
781 continue
782 end
783
784 # The rule
785 var rule = new Array[Object]
786
787 # First element is the goal, thus
788 rule.add suppath
789
790 # Second element is the first condition, that is to be a client of the current module
791 rule.add mmodule
792
793 # Other condition are to be also a client of each modules indicated as arguments of the annotation
794 for narg in nargs do
795 var id = narg.as_id
796 if id == null then
797 error(narg, "Syntax Error: `conditional` expects module identifier as arguments.")
798 continue
799 end
800
801 var mp = search_mmodule_by_name(narg, mmodule.mgroup, id)
802 if mp == null then continue
803
804 rule.add mp
805 end
806
807 conditional_importations.add rule
808 end
809 end
810
811 mmodule.set_imported_mmodules(imported_modules)
812
813 apply_conditional_importations(mmodule)
814
815 self.toolcontext.info("{mmodule} imports {mmodule.in_importation.direct_greaters.join(", ")}", 3)
816
817 # Force standard to be public if imported
818 for sup in mmodule.in_importation.greaters do
819 if sup.name == "standard" then
820 mmodule.set_visibility_for(sup, public_visibility)
821 end
822 end
823
824 # TODO: Correctly check for useless importation
825 # It is even doable?
826 var directs = mmodule.in_importation.direct_greaters
827 for nim in nmodule.n_imports do
828 if not nim isa AStdImport then continue
829 var im = nim.mmodule
830 if im == null then continue
831 if directs.has(im) then continue
832 # This generates so much noise that it is simpler to just comment it
833 #warning(nim, "Warning: possible useless importation of {im}")
834 end
835 end
836
837 # Global list of conditional importation rules.
838 #
839 # Each rule is a "Horn clause"-like sequence of modules.
840 # It means that the first module is the module to automatically import.
841 # The remaining modules are the conditions of the rule.
842 #
843 # Each module is either represented by a MModule (if the module is already loaded)
844 # or by a ModulePath (if the module is not yet loaded).
845 #
846 # Rules are declared by `build_module_importation` and are applied by `apply_conditional_importations`
847 # (and `build_module_importation` that calls it).
848 #
849 # TODO (when the loader will be rewritten): use a better representation and move up rules in the model.
850 private var conditional_importations = new Array[SequenceRead[Object]]
851
852 # Extends the current importations according to imported rules about conditional importation
853 fun apply_conditional_importations(mmodule: MModule)
854 do
855 # Because a conditional importation may cause additional conditional importation, use a fixed point
856 # The rules are checked naively because we assume that it does not worth to be optimized
857 var check_conditional_importations = true
858 while check_conditional_importations do
859 check_conditional_importations = false
860
861 for ci in conditional_importations do
862 # Check conditions
863 for i in [1..ci.length[ do
864 var rule_element = ci[i]
865 # An element of a rule is either a MModule or a ModulePath
866 # We need the mmodule to resonate on the importation
867 var m
868 if rule_element isa MModule then
869 m = rule_element
870 else if rule_element isa ModulePath then
871 m = rule_element.mmodule
872 # Is loaded?
873 if m == null then continue label
874 else
875 abort
876 end
877 # Is imported?
878 if not mmodule.in_importation.greaters.has(m) then continue label
879 end
880 # Still here? It means that all conditions modules are loaded and imported
881
882 # Identify the module to automatically import
883 var suppath = ci.first.as(ModulePath)
884 var sup = load_module_path(suppath)
885 if sup == null then continue
886
887 # Do nothing if already imported
888 if mmodule.in_importation.greaters.has(sup) then continue label
889
890 # Import it
891 self.toolcontext.info("{mmodule} conditionally imports {sup}", 3)
892 # TODO visibility rules (currently always public)
893 mmodule.set_visibility_for(sup, public_visibility)
894 # TODO linearization rules (currently added at the end in the order of the rules)
895 mmodule.set_imported_mmodules([sup])
896
897 # Prepare to reapply the rules
898 check_conditional_importations = true
899 end label
900 end
901 end
902
903 # All the loaded modules
904 var nmodules = new Array[AModule]
905
906 # Register the nmodule associated to each mmodule
907 #
908 # Public clients need to use `mmodule2node` to access stuff.
909 private var mmodule2nmodule = new HashMap[MModule, AModule]
910
911 # Retrieve the associated AST node of a mmodule.
912 # This method is used to associate model entity with syntactic entities.
913 #
914 # If the module is not associated with a node, returns null.
915 fun mmodule2node(mmodule: MModule): nullable AModule
916 do
917 return mmodule2nmodule.get_or_null(mmodule)
918 end
919 end
920
921 # File-system location of a module (file) that is identified but not always loaded.
922 class ModulePath
923 # The name of the module
924 # (it's the basename of the filepath)
925 var name: String
926
927 # The human path of the module
928 var filepath: String
929
930 # The group (and the project) of the possible module
931 var mgroup: MGroup
932
933 # The loaded module (if any)
934 var mmodule: nullable MModule = null
935
936 redef fun to_s do return filepath
937 end
938
939 redef class MProject
940 # The associated `.ini` file, if any
941 #
942 # The `ini` file is given as is and might contain invalid or missing information.
943 #
944 # Some projects, like stand-alone projects or virtual projects have no `ini` file associated.
945 var ini: nullable ConfigTree = null
946 end
947
948 redef class MGroup
949 # Modules paths associated with the group
950 var module_paths = new Array[ModulePath]
951
952 # Is the group interesting for a final user?
953 #
954 # Groups are mandatory in the model but for simple projects they are not
955 # always interesting.
956 #
957 # A interesting group has, at least, one of the following true:
958 #
959 # * it has 2 modules or more
960 # * it has a subgroup
961 # * it has a documentation
962 fun is_interesting: Bool
963 do
964 return module_paths.length > 1 or
965 mmodules.length > 1 or
966 not in_nesting.direct_smallers.is_empty or
967 mdoc != null or
968 (mmodules.length == 1 and default_mmodule == null)
969 end
970
971 # Are files and directories in self scanned?
972 #
973 # See `ModelBuilder::scan_group`.
974 var scanned = false
975
976 # Return the modules in self and subgroups named `name`.
977 #
978 # If `self` is not scanned (see `ModelBuilder::scan_group`) the
979 # results might be partial.
980 fun mmodule_paths_by_name(name: String): Array[ModulePath]
981 do
982 var res = new Array[ModulePath]
983 for g in in_nesting.smallers do
984 for mp in g.module_paths do
985 if mp.name == name then
986 res.add mp
987 end
988 end
989 end
990 return res
991 end
992 end
993
994 redef class SourceFile
995 # Associated mmodule, once created
996 var mmodule: nullable MModule = null
997 end
998
999 redef class AStdImport
1000 # The imported module once determined
1001 var mmodule: nullable MModule = null
1002 end
1003
1004 redef class AModule
1005 # The associated MModule once build by a `ModelBuilder`
1006 var mmodule: nullable MModule
1007 # Flag that indicate if the importation is already completed
1008 var is_importation_done: Bool = false
1009 end