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