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