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