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