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