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