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