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