loader: identify_file distinguishes singleton projects in the verbose message
[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 module loader
19
20 import modelbuilder_base
21
22 redef class ToolContext
23 # Option --path
24 var opt_path = new OptionArray("Set include path for loaders (may be used more than once)", "-I", "--path")
25
26 # Option --only-metamodel
27 var opt_only_metamodel = new OptionBool("Stop after meta-model processing", "--only-metamodel")
28
29 # Option --only-parse
30 var opt_only_parse = new OptionBool("Only proceed to parse step of loaders", "--only-parse")
31
32 redef init
33 do
34 super
35 option_context.add_option(opt_path, opt_only_parse, opt_only_metamodel)
36 end
37 end
38
39 redef class ModelBuilder
40 redef init
41 do
42 super
43
44 # Setup the paths value
45 paths.append(toolcontext.opt_path.value)
46
47 var path_env = "NIT_PATH".environ
48 if not path_env.is_empty then
49 paths.append(path_env.split_with(':'))
50 end
51
52 var nit_dir = toolcontext.nit_dir
53 var libname = nit_dir/"lib"
54 if libname.file_exists then paths.add(libname)
55 libname = nit_dir/"contrib"
56 if libname.file_exists then paths.add(libname)
57 end
58
59 # Load a bunch of modules.
60 # `modules` can contains filenames or module names.
61 # Imported modules are automatically loaded and modelized.
62 # The result is the corresponding model elements.
63 # Errors and warnings are printed with the toolcontext.
64 #
65 # Note: class and property model elements are not analysed.
66 fun parse(modules: Sequence[String]): Array[MModule]
67 do
68 var time0 = get_time
69 # Parse and recursively load
70 self.toolcontext.info("*** PARSE ***", 1)
71 var mmodules = new ArraySet[MModule]
72 for a in modules do
73 var nmodule = self.load_module(a)
74 if nmodule == null then continue # Skip error
75 # Load imported module
76 build_module_importation(nmodule)
77 var mmodule = nmodule.mmodule
78 if mmodule == null then continue # skip error
79 mmodules.add mmodule
80 end
81 var time1 = get_time
82 self.toolcontext.info("*** END PARSE: {time1-time0} ***", 2)
83
84 self.toolcontext.check_errors
85
86 if toolcontext.opt_only_parse.value then
87 self.toolcontext.info("*** ONLY PARSE...", 1)
88 exit(0)
89 end
90
91 return mmodules.to_a
92 end
93
94 # Load recursively all modules of the group `mgroup`.
95 # See `parse` for details.
96 fun parse_group(mgroup: MGroup): Array[MModule]
97 do
98 var res = new Array[MModule]
99 scan_group(mgroup)
100 for mg in mgroup.in_nesting.smallers do
101 for mp in mg.module_paths do
102 var nmodule = self.load_module(mp.filepath)
103 if nmodule == null then continue # Skip error
104 # Load imported module
105 build_module_importation(nmodule)
106 var mmodule = nmodule.mmodule
107 if mmodule == null then continue # Skip error
108 res.add mmodule
109 end
110 end
111 return res
112 end
113
114 # Load a bunch of modules and groups.
115 #
116 # Each name can be:
117 #
118 # * a path to a module, a group or a directory of projects.
119 # * a short name of a module or a group that are looked in the `paths` (-I)
120 #
121 # Then, for each entry, if it is:
122 #
123 # * a module, then is it parser and returned.
124 # * a group then recursively all its modules are parsed.
125 # * a directory of projects then all the modules of all projects are parsed.
126 # * else an error is displayed.
127 #
128 # See `parse` for details.
129 fun parse_full(names: Sequence[String]): Array[MModule]
130 do
131 var time0 = get_time
132 # Parse and recursively load
133 self.toolcontext.info("*** PARSE ***", 1)
134 var mmodules = new ArraySet[MModule]
135 for a in names do
136 # Case of a group
137 var mgroup = self.get_mgroup(a)
138 if mgroup != null then
139 mmodules.add_all parse_group(mgroup)
140 continue
141 end
142
143 # Case of a directory that is not a group
144 var stat = a.to_path.stat
145 if stat != null and stat.is_dir then
146 self.toolcontext.info("look in directory {a}", 2)
147 var fs = a.files
148 # Try each entry as a group or a module
149 for f in fs do
150 var af = a/f
151 mgroup = get_mgroup(af)
152 if mgroup != null then
153 mmodules.add_all parse_group(mgroup)
154 continue
155 end
156 var mp = identify_file(af)
157 if mp != null then
158 var nmodule = self.load_module(af)
159 if nmodule == null then continue # Skip error
160 build_module_importation(nmodule)
161 var mmodule = nmodule.mmodule
162 if mmodule == null then continue # Skip error
163 mmodules.add mmodule
164 else
165 self.toolcontext.info("ignore file {af}", 2)
166 end
167 end
168 continue
169 end
170
171 var nmodule = self.load_module(a)
172 if nmodule == null then continue # Skip error
173 # Load imported module
174 build_module_importation(nmodule)
175 var mmodule = nmodule.mmodule
176 if mmodule == null then continue # Skip error
177 mmodules.add mmodule
178 end
179 var time1 = get_time
180 self.toolcontext.info("*** END PARSE: {time1-time0} ***", 2)
181
182 self.toolcontext.check_errors
183
184 if toolcontext.opt_only_parse.value then
185 self.toolcontext.info("*** ONLY PARSE...", 1)
186 exit(0)
187 end
188
189 return mmodules.to_a
190 end
191
192 # The list of directories to search for top level modules
193 # The list is initially set with:
194 #
195 # * the toolcontext --path option
196 # * the NIT_PATH environment variable
197 # * `toolcontext.nit_dir`
198 # Path can be added (or removed) by the client
199 var paths = new Array[String]
200
201 # Like (and used by) `get_mmodule_by_name` but just return the ModulePath
202 fun search_mmodule_by_name(anode: nullable ANode, mgroup: nullable MGroup, name: String): nullable ModulePath
203 do
204 # First, look in groups
205 var c = mgroup
206 if c != null then
207 var r = c.mproject.root
208 assert r != null
209 scan_group(r)
210 var res = r.mmodule_paths_by_name(name)
211 if res.not_empty then return res.first
212 end
213
214 # Look at some known directories
215 var lookpaths = self.paths
216
217 # Look in the directory of the group project also (even if not explicitly in the path)
218 if mgroup != null then
219 # path of the root group
220 var dirname = mgroup.mproject.root.filepath
221 if dirname != null then
222 dirname = dirname.join_path("..").simplify_path
223 if not lookpaths.has(dirname) and dirname.file_exists then
224 lookpaths = lookpaths.to_a
225 lookpaths.add(dirname)
226 end
227 end
228 end
229
230 var candidate = search_module_in_paths(anode.hot_location, name, lookpaths)
231
232 if candidate == null then
233 if mgroup != null then
234 error(anode, "Error: cannot find module `{name}` from `{mgroup.name}`. Tried: {lookpaths.join(", ")}.")
235 else
236 error(anode, "Error: cannot find module `{name}`. Tried: {lookpaths.join(", ")}.")
237 end
238 return null
239 end
240 return candidate
241 end
242
243 # Get a module by its short name; if required, the module is loaded, parsed and its hierarchies computed.
244 # If `mgroup` is set, then the module search starts from it up to the top level (see `paths`);
245 # if `mgroup` is null then the module is searched in the top level only.
246 # If no module exists or there is a name conflict, then an error on `anode` is displayed and null is returned.
247 fun get_mmodule_by_name(anode: nullable ANode, mgroup: nullable MGroup, name: String): nullable MModule
248 do
249 var path = search_mmodule_by_name(anode, mgroup, name)
250 if path == null then return null # Forward error
251 return load_module_path(path)
252 end
253
254 # Load and process importation of a given ModulePath.
255 #
256 # Basically chains `load_module` and `build_module_importation`.
257 fun load_module_path(path: ModulePath): nullable MModule
258 do
259 var res = self.load_module(path.filepath)
260 if res == null then return null # Forward error
261 # Load imported module
262 build_module_importation(res)
263 return res.mmodule
264 end
265
266 # Search a module `name` from path `lookpaths`.
267 # If found, the path of the file is returned
268 private fun search_module_in_paths(location: nullable Location, name: String, lookpaths: Collection[String]): nullable ModulePath
269 do
270 var res = new ArraySet[ModulePath]
271 for dirname in lookpaths do
272 # Try a single module file
273 var mp = identify_file((dirname/"{name}.nit").simplify_path)
274 if mp != null then res.add mp
275 # Try the default module of a group
276 var g = get_mgroup((dirname/name).simplify_path)
277 if g != null then
278 scan_group(g)
279 res.add_all g.mmodule_paths_by_name(name)
280 end
281 end
282 if res.is_empty then return null
283 if res.length > 1 then
284 toolcontext.error(location, "Error: conflicting module files for `{name}`: `{res.join(",")}`")
285 end
286 return res.first
287 end
288
289 # Cache for `identify_file` by realpath
290 private var identified_files_by_path = new HashMap[String, nullable ModulePath]
291
292 # All the currently identified modules.
293 # See `identify_file`.
294 var identified_files = new Array[ModulePath]
295
296 # Identify a source file and load the associated project and groups if required.
297 #
298 # This method does what the user expects when giving an argument to a Nit tool.
299 #
300 # * If `path` is an existing Nit source file (with the `.nit` extension),
301 # then the associated ModulePath is returned
302 # * If `path` is a directory (with a `/`),
303 # then the ModulePath of its default module is returned (if any)
304 # * If `path` is a simple identifier (eg. `digraph`),
305 # then the main module of the project `digraph` is searched in `paths` and returned.
306 #
307 # Silently return `null` if `path` does not exists or cannot be identified.
308 fun identify_file(path: String): nullable ModulePath
309 do
310 # special case for not a nit file
311 if path.file_extension != "nit" then
312 # search dirless files in known -I paths
313 if not path.chars.has('/') then
314 var res = search_module_in_paths(null, path, self.paths)
315 if res != null then return res
316 end
317
318 # Found nothing? maybe it is a group...
319 var candidate = null
320 if path.file_exists then
321 var mgroup = get_mgroup(path)
322 if mgroup != null then
323 var owner_path = mgroup.filepath.join_path(mgroup.name + ".nit")
324 if owner_path.file_exists then candidate = owner_path
325 end
326 end
327
328 if candidate == null then
329 return null
330 end
331 path = candidate
332 end
333
334 # Does the file exists?
335 if not path.file_exists then
336 return null
337 end
338
339 # Fast track, the path is already known
340 var pn = path.basename(".nit")
341 var rp = module_absolute_path(path)
342 if identified_files_by_path.has_key(rp) then return identified_files_by_path[rp]
343
344 # Search for a group
345 var mgrouppath = path.join_path("..").simplify_path
346 var mgroup = get_mgroup(mgrouppath)
347
348 if mgroup == null then
349 # singleton project
350 var mproject = new MProject(pn, model)
351 mgroup = new MGroup(pn, mproject, null) # same name for the root group
352 mgroup.filepath = path
353 mproject.root = mgroup
354 toolcontext.info("found singleton project `{pn}` at {path}", 2)
355 end
356
357 var res = new ModulePath(pn, path, mgroup)
358 mgroup.module_paths.add(res)
359
360 identified_files_by_path[rp] = res
361 identified_files.add(res)
362 return res
363 end
364
365 # Groups by path
366 private var mgroups = new HashMap[String, nullable MGroup]
367
368 # Return the mgroup associated to a directory path.
369 # If the directory is not a group null is returned.
370 #
371 # Note: `paths` is also used to look for mgroups
372 fun get_mgroup(dirpath: String): nullable MGroup
373 do
374 if not dirpath.file_exists then do
375 for p in paths do
376 var try = p / dirpath
377 if try.file_exists then
378 dirpath = try
379 break label
380 end
381 end
382 return null
383 end label
384
385 var rdp = module_absolute_path(dirpath)
386 if mgroups.has_key(rdp) then
387 return mgroups[rdp]
388 end
389
390 # Hack, a group is determined by one of the following:
391 # * the presence of a honomymous nit file
392 # * the fact that the directory is named `src`
393 # * the fact that there is a sub-directory named `src`
394 var pn = rdp.basename(".nit")
395 var mp = dirpath.join_path(pn + ".nit").simplify_path
396
397 # dirpath2 is the root directory
398 # dirpath is the src subdirectory directory, if any, else it is the same that dirpath2
399 var dirpath2 = dirpath
400 if not mp.file_exists then
401 if pn == "src" then
402 # With a src directory, the group name is the name of the parent directory
403 dirpath2 = rdp.dirname
404 pn = dirpath2.basename
405 else
406 # Check a `src` subdirectory
407 dirpath = dirpath2 / "src"
408 if not dirpath.file_exists then
409 # All rules failed, so return null
410 return null
411 end
412 end
413 end
414
415 # check parent directory
416 var parentpath = dirpath2.join_path("..").simplify_path
417 var parent = get_mgroup(parentpath)
418
419 var mgroup
420 if parent == null then
421 # no parent, thus new project
422 var mproject = new MProject(pn, model)
423 mgroup = new MGroup(pn, mproject, null) # same name for the root group
424 mproject.root = mgroup
425 toolcontext.info("found project `{mproject}` at {dirpath}", 2)
426 else
427 mgroup = new MGroup(pn, parent.mproject, parent)
428 toolcontext.info("found sub group `{mgroup.full_name}` at {dirpath}", 2)
429 end
430
431 # search documentation
432 # in src first so the documentation of the project code can be distinct for the documentation of the project usage
433 var readme = dirpath.join_path("README.md")
434 if not readme.file_exists then readme = dirpath.join_path("README")
435 if not readme.file_exists then readme = dirpath2.join_path("README.md")
436 if not readme.file_exists then readme = dirpath2.join_path("README")
437 if readme.file_exists then
438 var mdoc = load_markdown(readme)
439 mgroup.mdoc = mdoc
440 mdoc.original_mentity = mgroup
441 end
442
443 mgroup.filepath = dirpath
444 mgroups[module_absolute_path(dirpath)] = mgroup
445 mgroups[module_absolute_path(dirpath2)] = mgroup
446 return mgroup
447 end
448
449 # Load a markdown file as a documentation object
450 fun load_markdown(filepath: String): MDoc
451 do
452 var s = new FileReader.open(filepath)
453 var lines = new Array[String]
454 var line_starts = new Array[Int]
455 var len = 1
456 while not s.eof do
457 var line = s.read_line
458 lines.add(line)
459 line_starts.add(len)
460 len += line.length + 1
461 end
462 s.close
463 var source = new SourceFile.from_string(filepath, lines.join("\n"))
464 source.line_starts.add_all line_starts
465 var mdoc = new MDoc(new Location(source, 1, lines.length, 0, 0))
466 mdoc.content.add_all(lines)
467 return mdoc
468 end
469
470 # Force the identification of all ModulePath of the group and sub-groups in the file system.
471 #
472 # When a group is scanned, its sub-groups hierarchy is filled (see `MGroup::in_nesting`)
473 # and the potential modules (and nested modules) are identified (see `MGroup::module_paths`).
474 #
475 # Basically, this recursively call `get_mgroup` and `identify_file` on each directory entry.
476 #
477 # No-op if the group was already scanned (see `MGroup::scanned`).
478 fun scan_group(mgroup: MGroup) do
479 if mgroup.scanned then return
480 mgroup.scanned = true
481 var p = mgroup.filepath
482 # a virtual group has nothing to scan
483 if p == null then return
484 for f in p.files do
485 var fp = p/f
486 var g = get_mgroup(fp)
487 # Recursively scan for groups of the same project
488 if g != null and g.mproject == mgroup.mproject then
489 scan_group(g)
490 end
491 identify_file(fp)
492 end
493 end
494
495 # Transform relative paths (starting with '../') into absolute paths
496 private fun module_absolute_path(path: String): String do
497 return getcwd.join_path(path).simplify_path
498 end
499
500 # Try to load a module AST using a path.
501 # Display an error if there is a problem (IO / lexer / parser) and return null
502 fun load_module_ast(filename: String): nullable AModule
503 do
504 if filename.file_extension != "nit" then
505 self.toolcontext.error(null, "Error: file `{filename}` is not a valid nit module.")
506 return null
507 end
508 if not filename.file_exists then
509 self.toolcontext.error(null, "Error: file `{filename}` not found.")
510 return null
511 end
512
513 self.toolcontext.info("load module {filename}", 2)
514
515 # Load the file
516 var file = new FileReader.open(filename)
517 var lexer = new Lexer(new SourceFile(filename, file))
518 var parser = new Parser(lexer)
519 var tree = parser.parse
520 file.close
521
522 # Handle lexer and parser error
523 var nmodule = tree.n_base
524 if nmodule == null then
525 var neof = tree.n_eof
526 assert neof isa AError
527 error(neof, neof.message)
528 return null
529 end
530
531 return nmodule
532 end
533
534 # Remove Nit source files from a list of arguments.
535 #
536 # Items of `args` that can be loaded as a nit file will be removed from `args` and returned.
537 fun filter_nit_source(args: Array[String]): Array[String]
538 do
539 var keep = new Array[String]
540 var res = new Array[String]
541 for a in args do
542 var l = identify_file(a)
543 if l == null then
544 keep.add a
545 else
546 res.add a
547 end
548 end
549 args.clear
550 args.add_all(keep)
551 return res
552 end
553
554 # Try to load a module using a path.
555 # Display an error if there is a problem (IO / lexer / parser) and return null.
556 # Note: usually, you do not need this method, use `get_mmodule_by_name` instead.
557 #
558 # The MModule is created however, the importation is not performed,
559 # therefore you should call `build_module_importation`.
560 fun load_module(filename: String): nullable AModule
561 do
562 # Look for the module
563 var file = identify_file(filename)
564 if file == null then
565 if filename.file_exists then
566 toolcontext.error(null, "Error: `{filename}` is not a Nit source file.")
567 else
568 toolcontext.error(null, "Error: cannot find module `{filename}`.")
569 end
570 return null
571 end
572
573 # Already known and loaded? then return it
574 var mmodule = file.mmodule
575 if mmodule != null then
576 return mmodule2nmodule[mmodule]
577 end
578
579 # Load it manually
580 var nmodule = load_module_ast(file.filepath)
581 if nmodule == null then return null # forward error
582
583 # build the mmodule and load imported modules
584 mmodule = build_a_mmodule(file.mgroup, file.name, nmodule)
585
586 if mmodule == null then return null # forward error
587
588 # Update the file information
589 file.mmodule = mmodule
590
591 return nmodule
592 end
593
594 # Injection of a new module without source.
595 # Used by the interpreter.
596 fun load_rt_module(parent: nullable MModule, nmodule: AModule, mod_name: String): nullable AModule
597 do
598 # Create the module
599
600 var mgroup = null
601 if parent != null then mgroup = parent.mgroup
602 var mmodule = new MModule(model, mgroup, mod_name, nmodule.location)
603 nmodule.mmodule = mmodule
604 nmodules.add(nmodule)
605 self.mmodule2nmodule[mmodule] = nmodule
606
607 if parent!= null then
608 var imported_modules = new Array[MModule]
609 imported_modules.add(parent)
610 mmodule.set_visibility_for(parent, intrude_visibility)
611 mmodule.set_imported_mmodules(imported_modules)
612 else
613 build_module_importation(nmodule)
614 end
615
616 return nmodule
617 end
618
619 # Visit the AST and create the `MModule` object
620 private fun build_a_mmodule(mgroup: nullable MGroup, mod_name: String, nmodule: AModule): nullable MModule
621 do
622 # Check the module name
623 var decl = nmodule.n_moduledecl
624 if decl != null then
625 var decl_name = decl.n_name.n_id.text
626 if decl_name != mod_name then
627 error(decl.n_name, "Error: module name mismatch; declared {decl_name} file named {mod_name}.")
628 end
629 end
630
631 # Check for conflicting module names in the project
632 if mgroup != null then
633 var others = model.get_mmodules_by_name(mod_name)
634 if others != null then for other in others do
635 if other.mgroup!= null and other.mgroup.mproject == mgroup.mproject then
636 var node: ANode
637 if decl == null then node = nmodule else node = decl.n_name
638 error(node, "Error: a module named `{other.full_name}` already exists at {other.location}.")
639 break
640 end
641 end
642 end
643
644 # Create the module
645 var mmodule = new MModule(model, mgroup, mod_name, nmodule.location)
646 nmodule.mmodule = mmodule
647 nmodules.add(nmodule)
648 self.mmodule2nmodule[mmodule] = nmodule
649
650 var source = nmodule.location.file
651 if source != null then
652 assert source.mmodule == null
653 source.mmodule = mmodule
654 end
655
656 if decl != null then
657 # Extract documentation
658 var ndoc = decl.n_doc
659 if ndoc != null then
660 var mdoc = ndoc.to_mdoc
661 mmodule.mdoc = mdoc
662 mdoc.original_mentity = mmodule
663 else
664 advice(decl, "missing-doc", "Documentation warning: Undocumented module `{mmodule}`")
665 end
666 # Is the module a test suite?
667 mmodule.is_test_suite = not decl.get_annotations("test_suite").is_empty
668 end
669
670 return mmodule
671 end
672
673 # Resolve the module identification for a given `AModuleName`.
674 #
675 # This method handles qualified names as used in `AModuleName`.
676 fun seach_module_by_amodule_name(n_name: AModuleName, mgroup: nullable MGroup): nullable ModulePath
677 do
678 if n_name.n_quad != null then mgroup = null # Start from top level
679 for grp in n_name.n_path do
680 var path = search_mmodule_by_name(grp, mgroup, grp.text)
681 if path == null then return null # Forward error
682 mgroup = path.mgroup
683 end
684 var mod_name = n_name.n_id.text
685 return search_mmodule_by_name(n_name, mgroup, mod_name)
686 end
687
688 # Analyze the module importation and fill the module_importation_hierarchy
689 #
690 # Unless you used `load_module`, the importation is already done and this method does a no-op.
691 fun build_module_importation(nmodule: AModule)
692 do
693 if nmodule.is_importation_done then return
694 nmodule.is_importation_done = true
695 var mmodule = nmodule.mmodule.as(not null)
696 var stdimport = true
697 var imported_modules = new Array[MModule]
698 for aimport in nmodule.n_imports do
699 # Do not imports conditional
700 var atconditionals = aimport.get_annotations("conditional")
701 if atconditionals.not_empty then continue
702
703 stdimport = false
704 if not aimport isa AStdImport then
705 continue
706 end
707
708 # Load the imported module
709 var suppath = seach_module_by_amodule_name(aimport.n_name, mmodule.mgroup)
710 if suppath == null then
711 nmodule.mmodule = null # invalidate the module
712 continue # Skip error
713 end
714 var sup = load_module_path(suppath)
715 if sup == null then
716 nmodule.mmodule = null # invalidate the module
717 continue # Skip error
718 end
719
720 aimport.mmodule = sup
721 imported_modules.add(sup)
722 var mvisibility = aimport.n_visibility.mvisibility
723 if mvisibility == protected_visibility then
724 error(aimport.n_visibility, "Error: only properties can be protected.")
725 nmodule.mmodule = null # invalidate the module
726 return
727 end
728 if sup == mmodule then
729 error(aimport.n_name, "Error: dependency loop in module {mmodule}.")
730 nmodule.mmodule = null # invalidate the module
731 end
732 if sup.in_importation < mmodule then
733 error(aimport.n_name, "Error: dependency loop between modules {mmodule} and {sup}.")
734 nmodule.mmodule = null # invalidate the module
735 return
736 end
737 mmodule.set_visibility_for(sup, mvisibility)
738 end
739 if stdimport then
740 var mod_name = "standard"
741 var sup = self.get_mmodule_by_name(nmodule, null, mod_name)
742 if sup == null then
743 nmodule.mmodule = null # invalidate the module
744 else # Skip error
745 imported_modules.add(sup)
746 mmodule.set_visibility_for(sup, public_visibility)
747 end
748 end
749
750 # Declare conditional importation
751 for aimport in nmodule.n_imports do
752 if not aimport isa AStdImport then continue
753 var atconditionals = aimport.get_annotations("conditional")
754 if atconditionals.is_empty then continue
755
756 var suppath = seach_module_by_amodule_name(aimport.n_name, mmodule.mgroup)
757 if suppath == null then continue # skip error
758
759 for atconditional in atconditionals do
760 var nargs = atconditional.n_args
761 if nargs.is_empty then
762 error(atconditional, "Syntax Error: `conditional` expects module identifiers as arguments.")
763 continue
764 end
765
766 # The rule
767 var rule = new Array[Object]
768
769 # First element is the goal, thus
770 rule.add suppath
771
772 # Second element is the first condition, that is to be a client of the current module
773 rule.add mmodule
774
775 # Other condition are to be also a client of each modules indicated as arguments of the annotation
776 for narg in nargs do
777 var id = narg.as_id
778 if id == null then
779 error(narg, "Syntax Error: `conditional` expects module identifier as arguments.")
780 continue
781 end
782
783 var mp = search_mmodule_by_name(narg, mmodule.mgroup, id)
784 if mp == null then continue
785
786 rule.add mp
787 end
788
789 conditional_importations.add rule
790 end
791 end
792
793 mmodule.set_imported_mmodules(imported_modules)
794
795 apply_conditional_importations(mmodule)
796
797 self.toolcontext.info("{mmodule} imports {mmodule.in_importation.direct_greaters.join(", ")}", 3)
798
799 # Force standard to be public if imported
800 for sup in mmodule.in_importation.greaters do
801 if sup.name == "standard" then
802 mmodule.set_visibility_for(sup, public_visibility)
803 end
804 end
805
806 # TODO: Correctly check for useless importation
807 # It is even doable?
808 var directs = mmodule.in_importation.direct_greaters
809 for nim in nmodule.n_imports do
810 if not nim isa AStdImport then continue
811 var im = nim.mmodule
812 if im == null then continue
813 if directs.has(im) then continue
814 # This generates so much noise that it is simpler to just comment it
815 #warning(nim, "Warning: possible useless importation of {im}")
816 end
817 end
818
819 # Global list of conditional importation rules.
820 #
821 # Each rule is a "Horn clause"-like sequence of modules.
822 # It means that the first module is the module to automatically import.
823 # The remaining modules are the conditions of the rule.
824 #
825 # Each module is either represented by a MModule (if the module is already loaded)
826 # or by a ModulePath (if the module is not yet loaded).
827 #
828 # Rules are declared by `build_module_importation` and are applied by `apply_conditional_importations`
829 # (and `build_module_importation` that calls it).
830 #
831 # TODO (when the loader will be rewritten): use a better representation and move up rules in the model.
832 private var conditional_importations = new Array[SequenceRead[Object]]
833
834 # Extends the current importations according to imported rules about conditional importation
835 fun apply_conditional_importations(mmodule: MModule)
836 do
837 # Because a conditional importation may cause additional conditional importation, use a fixed point
838 # The rules are checked naively because we assume that it does not worth to be optimized
839 var check_conditional_importations = true
840 while check_conditional_importations do
841 check_conditional_importations = false
842
843 for ci in conditional_importations do
844 # Check conditions
845 for i in [1..ci.length[ do
846 var rule_element = ci[i]
847 # An element of a rule is either a MModule or a ModulePath
848 # We need the mmodule to resonate on the importation
849 var m
850 if rule_element isa MModule then
851 m = rule_element
852 else if rule_element isa ModulePath then
853 m = rule_element.mmodule
854 # Is loaded?
855 if m == null then continue label
856 else
857 abort
858 end
859 # Is imported?
860 if not mmodule.in_importation.greaters.has(m) then continue label
861 end
862 # Still here? It means that all conditions modules are loaded and imported
863
864 # Identify the module to automatically import
865 var suppath = ci.first.as(ModulePath)
866 var sup = load_module_path(suppath)
867 if sup == null then continue
868
869 # Do nothing if already imported
870 if mmodule.in_importation.greaters.has(sup) then continue label
871
872 # Import it
873 self.toolcontext.info("{mmodule} conditionally imports {sup}", 3)
874 # TODO visibility rules (currently always public)
875 mmodule.set_visibility_for(sup, public_visibility)
876 # TODO linearization rules (currently added at the end in the order of the rules)
877 mmodule.set_imported_mmodules([sup])
878
879 # Prepare to reapply the rules
880 check_conditional_importations = true
881 end label
882 end
883 end
884
885 # All the loaded modules
886 var nmodules = new Array[AModule]
887
888 # Register the nmodule associated to each mmodule
889 #
890 # Public clients need to use `mmodule2node` to access stuff.
891 private var mmodule2nmodule = new HashMap[MModule, AModule]
892
893 # Retrieve the associated AST node of a mmodule.
894 # This method is used to associate model entity with syntactic entities.
895 #
896 # If the module is not associated with a node, returns null.
897 fun mmodule2node(mmodule: MModule): nullable AModule
898 do
899 return mmodule2nmodule.get_or_null(mmodule)
900 end
901 end
902
903 # File-system location of a module (file) that is identified but not always loaded.
904 class ModulePath
905 # The name of the module
906 # (it's the basename of the filepath)
907 var name: String
908
909 # The human path of the module
910 var filepath: String
911
912 # The group (and the project) of the possible module
913 var mgroup: MGroup
914
915 # The loaded module (if any)
916 var mmodule: nullable MModule = null
917
918 redef fun to_s do return filepath
919 end
920
921 redef class MGroup
922 # Modules paths associated with the group
923 var module_paths = new Array[ModulePath]
924
925 # Is the group interesting for a final user?
926 #
927 # Groups are mandatory in the model but for simple projects they are not
928 # always interesting.
929 #
930 # A interesting group has, at least, one of the following true:
931 #
932 # * it has 2 modules or more
933 # * it has a subgroup
934 # * it has a documentation
935 fun is_interesting: Bool
936 do
937 return module_paths.length > 1 or
938 mmodules.length > 1 or
939 not in_nesting.direct_smallers.is_empty or
940 mdoc != null or
941 (mmodules.length == 1 and default_mmodule == null)
942 end
943
944 # Are files and directories in self scanned?
945 #
946 # See `ModelBuilder::scan_group`.
947 var scanned = false
948
949 # Return the modules in self and subgroups named `name`.
950 #
951 # If `self` is not scanned (see `ModelBuilder::scan_group`) the
952 # results might be partial.
953 fun mmodule_paths_by_name(name: String): Array[ModulePath]
954 do
955 var res = new Array[ModulePath]
956 for g in in_nesting.smallers do
957 for mp in g.module_paths do
958 if mp.name == name then
959 res.add mp
960 end
961 end
962 end
963 return res
964 end
965 end
966
967 redef class SourceFile
968 # Associated mmodule, once created
969 var mmodule: nullable MModule = null
970 end
971
972 redef class AStdImport
973 # The imported module once determined
974 var mmodule: nullable MModule = null
975 end
976
977 redef class AModule
978 # The associated MModule once build by a `ModelBuilder`
979 var mmodule: nullable MModule
980 # Flag that indicate if the importation is already completed
981 var is_importation_done: Bool = false
982 end