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