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