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