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