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