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