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