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