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