toolcontext: introduce ToolContext::make_main_module
[nit.git] / src / modelbuilder.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 # Load nit source files and build the associated model
18 #
19 # FIXME better doc
20 #
21 # FIXME split this module into submodules
22 # FIXME add missing error checks
23 module modelbuilder
24
25 import model
26 import phase
27
28 private import more_collections
29
30 ###
31
32 redef class ToolContext
33 # Option --path
34 var opt_path = new OptionArray("Set include path for loaders (may be used more than once)", "-I", "--path")
35
36 # Option --only-metamodel
37 var opt_only_metamodel = new OptionBool("Stop after meta-model processing", "--only-metamodel")
38
39 # Option --only-parse
40 var opt_only_parse = new OptionBool("Only proceed to parse step of loaders", "--only-parse")
41
42 # Option --ignore-visibility
43 var opt_ignore_visibility = new OptionBool("Do not check, and produce errors, on visibility issues.", "--ignore-visibility")
44
45 redef init
46 do
47 super
48 option_context.add_option(opt_path, opt_only_parse, opt_only_metamodel, opt_ignore_visibility)
49 end
50
51 # The modelbuilder 1-to-1 associated with the toolcontext
52 fun modelbuilder: ModelBuilder do return modelbuilder_real.as(not null)
53
54 private var modelbuilder_real: nullable ModelBuilder = null
55
56 # Combine module to make a single one if required.
57 fun make_main_module(mmodules: Array[MModule]): MModule
58 do
59 assert not mmodules.is_empty
60 var mainmodule
61 if mmodules.length == 1 then
62 mainmodule = mmodules.first
63 else
64 # We need a main module, so we build it by importing all modules
65 mainmodule = new MModule(modelbuilder.model, null, mmodules.first.name + "-m", new Location(mmodules.first.location.file, 0, 0, 0, 0))
66 mainmodule.is_fictive = true
67 mainmodule.set_imported_mmodules(mmodules)
68 end
69 return mainmodule
70 end
71
72 # Run `process_mainmodule` on all phases
73 fun run_global_phases(mmodules: Array[MModule])
74 do
75 var mainmodule = make_main_module(mmodules)
76 for phase in phases_list do
77 if phase.disabled then continue
78 phase.process_mainmodule(mainmodule, mmodules)
79 end
80 end
81 end
82
83 redef class Phase
84 # Specific action to execute on the whole program.
85 # Called by the `ToolContext::run_global_phases`.
86 #
87 # `mainmodule` is the main module of the program.
88 # It could be an implicit module (called like the first given_mmodules).
89 #
90 # `given_modules` is the list of explicitely requested modules.
91 # from the command-line for instance.
92 #
93 # REQUIRE: `not given_modules.is_empty`
94 # REQUIRE: `(given_modules.length == 1) == (mainmodule == given_modules.first)`
95 #
96 # @toimplement
97 fun process_mainmodule(mainmodule: MModule, given_mmodules: SequenceRead[MModule]) do end
98 end
99
100
101 # A model builder knows how to load nit source files and build the associated model
102 class ModelBuilder
103 # The model where new modules, classes and properties are added
104 var model: Model
105
106 # The toolcontext used to control the interaction with the user (getting options and displaying messages)
107 var toolcontext: ToolContext
108
109 # Run phases on all loaded modules
110 fun run_phases
111 do
112 var mmodules = model.mmodules.to_a
113 model.mmodule_importation_hierarchy.sort(mmodules)
114 var nmodules = new Array[AModule]
115 for mm in mmodules do
116 nmodules.add(mmodule2nmodule[mm])
117 end
118 toolcontext.run_phases(nmodules)
119
120 if toolcontext.opt_only_metamodel.value then
121 self.toolcontext.info("*** ONLY METAMODEL", 1)
122 exit(0)
123 end
124 end
125
126 # Instantiate a modelbuilder for a model and a toolcontext
127 # Important, the options of the toolcontext must be correctly set (parse_option already called)
128 init(model: Model, toolcontext: ToolContext)
129 do
130 self.model = model
131 self.toolcontext = toolcontext
132 assert toolcontext.modelbuilder_real == null
133 toolcontext.modelbuilder_real = self
134
135 # Setup the paths value
136 paths.append(toolcontext.opt_path.value)
137
138 var path_env = "NIT_PATH".environ
139 if not path_env.is_empty then
140 paths.append(path_env.split_with(':'))
141 end
142
143 var nit_dir = toolcontext.nit_dir
144 if nit_dir != null then
145 var libname = "{nit_dir}/lib"
146 if libname.file_exists then paths.add(libname)
147 end
148 end
149
150 # Load a bunch of modules.
151 # `modules` can contains filenames or module names.
152 # Imported modules are automatically loaded and modelized.
153 # The result is the corresponding model elements.
154 # Errors and warnings are printed with the toolcontext.
155 #
156 # Note: class and property model element are not analysed.
157 fun parse(modules: Sequence[String]): Array[MModule]
158 do
159 var time0 = get_time
160 # Parse and recursively load
161 self.toolcontext.info("*** PARSE ***", 1)
162 var mmodules = new ArraySet[MModule]
163 for a in modules do
164 var nmodule = self.load_module(a)
165 if nmodule == null then continue # Skip error
166 mmodules.add(nmodule.mmodule.as(not null))
167 end
168 var time1 = get_time
169 self.toolcontext.info("*** END PARSE: {time1-time0} ***", 2)
170
171 self.toolcontext.check_errors
172
173 if toolcontext.opt_only_parse.value then
174 self.toolcontext.info("*** ONLY PARSE...", 1)
175 exit(0)
176 end
177
178 return mmodules.to_a
179 end
180
181 # Return a class named `name` visible by the module `mmodule`.
182 # Visibility in modules is correctly handled.
183 # If no such a class exists, then null is returned.
184 # If more than one class exists, then an error on `anode` is displayed and null is returned.
185 # FIXME: add a way to handle class name conflict
186 fun try_get_mclass_by_name(anode: ANode, mmodule: MModule, name: String): nullable MClass
187 do
188 var classes = model.get_mclasses_by_name(name)
189 if classes == null then
190 return null
191 end
192
193 var res: nullable MClass = null
194 for mclass in classes do
195 if not mmodule.in_importation <= mclass.intro_mmodule then continue
196 if not mmodule.is_visible(mclass.intro_mmodule, mclass.visibility) then continue
197 if res == null then
198 res = mclass
199 else
200 error(anode, "Ambigous class name '{name}'; conflict between {mclass.full_name} and {res.full_name}")
201 return null
202 end
203 end
204 return res
205 end
206
207 # Return a property named `name` on the type `mtype` visible in the module `mmodule`.
208 # Visibility in modules is correctly handled.
209 # Protected properties are returned (it is up to the caller to check and reject protected properties).
210 # If no such a property exists, then null is returned.
211 # If more than one property exists, then an error on `anode` is displayed and null is returned.
212 # FIXME: add a way to handle property name conflict
213 fun try_get_mproperty_by_name2(anode: ANode, mmodule: MModule, mtype: MType, name: String): nullable MProperty
214 do
215 var props = self.model.get_mproperties_by_name(name)
216 if props == null then
217 return null
218 end
219
220 var cache = self.try_get_mproperty_by_name2_cache[mmodule, mtype, name]
221 if cache != null then return cache
222
223 var res: nullable MProperty = null
224 var ress: nullable Array[MProperty] = null
225 for mprop in props do
226 if not mtype.has_mproperty(mmodule, mprop) then continue
227 if not mmodule.is_visible(mprop.intro_mclassdef.mmodule, mprop.visibility) then continue
228 if res == null then
229 res = mprop
230 continue
231 end
232
233 # Two global properties?
234 # First, special case for init, keep the most specific ones
235 if res isa MMethod and mprop isa MMethod and res.is_init and mprop.is_init then
236 var restype = res.intro_mclassdef.bound_mtype
237 var mproptype = mprop.intro_mclassdef.bound_mtype
238 if mproptype.is_subtype(mmodule, null, restype) then
239 # found a most specific constructor, so keep it
240 res = mprop
241 continue
242 end
243 end
244
245 # Ok, just keep all prop in the ress table
246 if ress == null then
247 ress = new Array[MProperty]
248 ress.add(res)
249 end
250 ress.add(mprop)
251 end
252
253 # There is conflict?
254 if ress != null and res isa MMethod and res.is_init then
255 # special case forinit again
256 var restype = res.intro_mclassdef.bound_mtype
257 var ress2 = new Array[MProperty]
258 for mprop in ress do
259 var mproptype = mprop.intro_mclassdef.bound_mtype
260 if not restype.is_subtype(mmodule, null, mproptype) then
261 ress2.add(mprop)
262 else if not mprop isa MMethod or not mprop.is_init then
263 ress2.add(mprop)
264 end
265 end
266 if ress2.is_empty then
267 ress = null
268 else
269 ress = ress2
270 ress.add(res)
271 end
272 end
273
274 if ress != null then
275 assert ress.length > 1
276 var s = new Array[String]
277 for mprop in ress do s.add mprop.full_name
278 self.error(anode, "Ambigous property name '{name}' for {mtype}; conflict between {s.join(" and ")}")
279 end
280
281 self.try_get_mproperty_by_name2_cache[mmodule, mtype, name] = res
282 return res
283 end
284
285 private var try_get_mproperty_by_name2_cache = new HashMap3[MModule, MType, String, nullable MProperty]
286
287
288 # Alias for try_get_mproperty_by_name2(anode, mclassdef.mmodule, mclassdef.mtype, name)
289 fun try_get_mproperty_by_name(anode: ANode, mclassdef: MClassDef, name: String): nullable MProperty
290 do
291 return try_get_mproperty_by_name2(anode, mclassdef.mmodule, mclassdef.bound_mtype, name)
292 end
293
294 # The list of directories to search for top level modules
295 # The list is initially set with :
296 # * the toolcontext --path option
297 # * the NIT_PATH environment variable
298 # * `toolcontext.nit_dir`
299 # Path can be added (or removed) by the client
300 var paths = new Array[String]
301
302 # Like (an used by) `get_mmodule_by_name` but just return the ModulePath
303 private fun search_mmodule_by_name(anode: ANode, mgroup: nullable MGroup, name: String): nullable ModulePath
304 do
305 # First, look in groups
306 var c = mgroup
307 while c != null do
308 var dirname = c.filepath
309 if dirname == null then break # virtual group
310 if dirname.has_suffix(".nit") then break # singleton project
311
312 # Second, try the directory to find a file
313 var try_file = dirname + "/" + name + ".nit"
314 if try_file.file_exists then
315 var res = self.identify_file(try_file.simplify_path)
316 assert res != null
317 return res
318 end
319
320 # Third, try if the requested module is itself a group
321 try_file = dirname + "/" + name + "/" + name + ".nit"
322 if try_file.file_exists then
323 var res = self.identify_file(try_file.simplify_path)
324 assert res != null
325 return res
326 end
327
328 c = c.parent
329 end
330
331 # Look at some known directories
332 var lookpaths = self.paths
333
334 # Look in the directory of the group project also (even if not explicitely in the path)
335 if mgroup != null then
336 # path of the root group
337 var dirname = mgroup.mproject.root.filepath
338 if dirname != null then
339 dirname = dirname.join_path("..").simplify_path
340 if not lookpaths.has(dirname) and dirname.file_exists then
341 lookpaths = lookpaths.to_a
342 lookpaths.add(dirname)
343 end
344 end
345 end
346
347 var candidate = search_module_in_paths(anode.hot_location, name, lookpaths)
348
349 if candidate == null then
350 if mgroup != null then
351 error(anode, "Error: cannot find module {name} from {mgroup.name}. tried {lookpaths.join(", ")}")
352 else
353 error(anode, "Error: cannot find module {name}. tried {lookpaths.join(", ")}")
354 end
355 return null
356 end
357 return candidate
358 end
359
360 # Get a module by its short name; if required, the module is loaded, parsed and its hierarchies computed.
361 # If `mgroup` is set, then the module search starts from it up to the top level (see `paths`);
362 # if `mgroup` is null then the module is searched in the top level only.
363 # If no module exists or there is a name conflict, then an error on `anode` is displayed and null is returned.
364 fun get_mmodule_by_name(anode: ANode, mgroup: nullable MGroup, name: String): nullable MModule
365 do
366 var path = search_mmodule_by_name(anode, mgroup, name)
367 if path == null then return null # Forward error
368 var res = self.load_module(path.filepath)
369 if res == null then return null # Forward error
370 return res.mmodule.as(not null)
371 end
372
373 # Search a module `name` from path `lookpaths`.
374 # If found, the path of the file is returned
375 private fun search_module_in_paths(location: nullable Location, name: String, lookpaths: Collection[String]): nullable ModulePath
376 do
377 var candidate: nullable String = null
378 for dirname in lookpaths do
379 var try_file = (dirname + "/" + name + ".nit").simplify_path
380 if try_file.file_exists then
381 if candidate == null then
382 candidate = try_file
383 else if candidate != try_file then
384 # try to disambiguate conflicting modules
385 var abs_candidate = module_absolute_path(candidate)
386 var abs_try_file = module_absolute_path(try_file)
387 if abs_candidate != abs_try_file then
388 toolcontext.error(location, "Error: conflicting module file for {name}: {candidate} {try_file}")
389 end
390 end
391 end
392 try_file = (dirname + "/" + name + "/" + name + ".nit").simplify_path
393 if try_file.file_exists then
394 if candidate == null then
395 candidate = try_file
396 else if candidate != try_file then
397 # try to disambiguate conflicting modules
398 var abs_candidate = module_absolute_path(candidate)
399 var abs_try_file = module_absolute_path(try_file)
400 if abs_candidate != abs_try_file then
401 toolcontext.error(location, "Error: conflicting module file for {name}: {candidate} {try_file}")
402 end
403 end
404 end
405 end
406 if candidate == null then return null
407 return identify_file(candidate)
408 end
409
410 # cache for `identify_file` by realpath
411 private var identified_files = new HashMap[String, nullable ModulePath]
412
413 # Identify a source file
414 # Load the associated project and groups if required
415 private fun identify_file(path: String): nullable ModulePath
416 do
417 # special case for not a nit file
418 if path.file_extension != "nit" then
419 # search in known -I paths
420 var res = search_module_in_paths(null, path, self.paths)
421 if res != null then return res
422
423 # Found nothins? maybe it is a group...
424 var candidate = null
425 if path.file_exists then
426 var mgroup = get_mgroup(path)
427 if mgroup != null then
428 var owner_path = mgroup.filepath.join_path(mgroup.name + ".nit")
429 if owner_path.file_exists then candidate = owner_path
430 end
431 end
432
433 if candidate == null then
434 toolcontext.error(null, "Error: cannot find module `{path}`.")
435 return null
436 end
437 path = candidate
438 end
439
440 # Fast track, the path is already known
441 var pn = path.basename(".nit")
442 var rp = module_absolute_path(path)
443 if identified_files.has_key(rp) then return identified_files[rp]
444
445 # Search for a group
446 var mgrouppath = path.join_path("..").simplify_path
447 var mgroup = get_mgroup(mgrouppath)
448
449 if mgroup == null then
450 # singleton project
451 var mproject = new MProject(pn, model)
452 mgroup = new MGroup(pn, mproject, null) # same name for the root group
453 mgroup.filepath = path
454 mproject.root = mgroup
455 toolcontext.info("found project `{pn}` at {path}", 2)
456 end
457
458 var res = new ModulePath(pn, path, mgroup)
459 mgroup.module_paths.add(res)
460
461 identified_files[rp] = res
462 return res
463 end
464
465 # groups by path
466 private var mgroups = new HashMap[String, nullable MGroup]
467
468 # return the mgroup associated to a directory path
469 # if the directory is not a group null is returned
470 private fun get_mgroup(dirpath: String): nullable MGroup
471 do
472 var rdp = module_absolute_path(dirpath)
473 if mgroups.has_key(rdp) then
474 return mgroups[rdp]
475 end
476
477 # Hack, a group is determined by:
478 # * the presence of a honomymous nit file
479 # * the fact that the directory is named `src`
480 var pn = rdp.basename(".nit")
481 var mp = dirpath.join_path(pn + ".nit").simplify_path
482
483 var dirpath2 = dirpath
484 if not mp.file_exists then
485 if pn == "src" then
486 # With a src directory, the group name is the name of the parent directory
487 dirpath2 = rdp.dirname
488 pn = dirpath2.basename("")
489 else
490 return null
491 end
492 end
493
494 # check parent directory
495 var parentpath = dirpath.join_path("..").simplify_path
496 var parent = get_mgroup(parentpath)
497
498 var mgroup
499 if parent == null then
500 # no parent, thus new project
501 var mproject = new MProject(pn, model)
502 mgroup = new MGroup(pn, mproject, null) # same name for the root group
503 mproject.root = mgroup
504 toolcontext.info("found project `{mproject}` at {dirpath}", 2)
505 else
506 mgroup = new MGroup(pn, parent.mproject, parent)
507 toolcontext.info("found sub group `{mgroup.full_name}` at {dirpath}", 2)
508 end
509 var readme = dirpath2.join_path("README.md")
510 if not readme.file_exists then readme = dirpath2.join_path("README")
511 if readme.file_exists then
512 var mdoc = new MDoc
513 var s = new IFStream.open(readme)
514 while not s.eof do
515 mdoc.content.add(s.read_line)
516 end
517 mgroup.mdoc = mdoc
518 mdoc.original_mentity = mgroup
519 end
520 mgroup.filepath = dirpath
521 mgroups[rdp] = mgroup
522 return mgroup
523 end
524
525 # Transform relative paths (starting with '../') into absolute paths
526 private fun module_absolute_path(path: String): String do
527 return getcwd.join_path(path).simplify_path
528 end
529
530 # Try to load a module AST using a path.
531 # Display an error if there is a problem (IO / lexer / parser) and return null
532 fun load_module_ast(filename: String): nullable AModule
533 do
534 if filename.file_extension != "nit" then
535 self.toolcontext.error(null, "Error: file {filename} is not a valid nit module.")
536 return null
537 end
538 if not filename.file_exists then
539 self.toolcontext.error(null, "Error: file {filename} not found.")
540 return null
541 end
542
543 self.toolcontext.info("load module {filename}", 2)
544
545 # Load the file
546 var file = new IFStream.open(filename)
547 var lexer = new Lexer(new SourceFile(filename, file))
548 var parser = new Parser(lexer)
549 var tree = parser.parse
550 file.close
551
552 # Handle lexer and parser error
553 var nmodule = tree.n_base
554 if nmodule == null then
555 var neof = tree.n_eof
556 assert neof isa AError
557 error(neof, neof.message)
558 return null
559 end
560
561 return nmodule
562 end
563
564 # Try to load a module and its imported modules using a path.
565 # Display an error if there is a problem (IO / lexer / parser / importation) and return null
566 # Note: usually, you do not need this method, use `get_mmodule_by_name` instead.
567 fun load_module(filename: String): nullable AModule
568 do
569 # Look for the module
570 var file = identify_file(filename)
571 if file == null then return null # forward error
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 # Load imported module
592 build_module_importation(nmodule)
593
594 return nmodule
595 end
596
597 # Injection of a new module without source.
598 # Used by the interpreted
599 fun load_rt_module(parent: nullable MModule, nmodule: AModule, mod_name: String): nullable AModule
600 do
601 # Create the module
602
603 var mgroup = null
604 if parent != null then mgroup = parent.mgroup
605 var mmodule = new MModule(model, mgroup, mod_name, nmodule.location)
606 nmodule.mmodule = mmodule
607 nmodules.add(nmodule)
608 self.mmodule2nmodule[mmodule] = nmodule
609
610 if parent!= null then
611 var imported_modules = new Array[MModule]
612 imported_modules.add(parent)
613 mmodule.set_visibility_for(parent, intrude_visibility)
614 mmodule.set_imported_mmodules(imported_modules)
615 else
616 build_module_importation(nmodule)
617 end
618
619 return nmodule
620 end
621
622 # Visit the AST and create the `MModule` object
623 private fun build_a_mmodule(mgroup: nullable MGroup, mod_name: String, nmodule: AModule): nullable MModule
624 do
625 # Check the module name
626 var decl = nmodule.n_moduledecl
627 if decl == null then
628 #warning(nmodule, "Warning: Missing 'module' keyword") #FIXME: NOT YET FOR COMPATIBILITY
629 else
630 var decl_name = decl.n_name.n_id.text
631 if decl_name != mod_name then
632 error(decl.n_name, "Error: module name missmatch; declared {decl_name} file named {mod_name}")
633 end
634 end
635
636 # Create the module
637 var mmodule = new MModule(model, mgroup, mod_name, nmodule.location)
638 nmodule.mmodule = mmodule
639 nmodules.add(nmodule)
640 self.mmodule2nmodule[mmodule] = nmodule
641
642 if decl != null then
643 var ndoc = decl.n_doc
644 if ndoc != null then
645 var mdoc = ndoc.to_mdoc
646 mmodule.mdoc = mdoc
647 mdoc.original_mentity = mmodule
648 else
649 advice(decl, "missing-doc", "Documentation warning: Undocumented module `{mmodule}`")
650 end
651 end
652
653 return mmodule
654 end
655
656 # Analysis the module importation and fill the module_importation_hierarchy
657 private fun build_module_importation(nmodule: AModule)
658 do
659 if nmodule.is_importation_done then return
660 nmodule.is_importation_done = true
661 var mmodule = nmodule.mmodule.as(not null)
662 var stdimport = true
663 var imported_modules = new Array[MModule]
664 for aimport in nmodule.n_imports do
665 stdimport = false
666 if not aimport isa AStdImport then
667 continue
668 end
669 var mgroup = mmodule.mgroup
670 if aimport.n_name.n_quad != null then mgroup = null # Start from top level
671 for grp in aimport.n_name.n_path do
672 var path = search_mmodule_by_name(grp, mgroup, grp.text)
673 if path == null then return # Skip error
674 mgroup = path.mgroup
675 end
676 var mod_name = aimport.n_name.n_id.text
677 var sup = self.get_mmodule_by_name(aimport.n_name, mgroup, mod_name)
678 if sup == null then continue # Skip error
679 aimport.mmodule = sup
680 imported_modules.add(sup)
681 var mvisibility = aimport.n_visibility.mvisibility
682 if mvisibility == protected_visibility then
683 error(aimport.n_visibility, "Error: only properties can be protected.")
684 return
685 end
686 if sup == mmodule then
687 error(aimport.n_name, "Error: Dependency loop in module {mmodule}.")
688 end
689 if sup.in_importation < mmodule then
690 error(aimport.n_name, "Error: Dependency loop between modules {mmodule} and {sup}.")
691 return
692 end
693 mmodule.set_visibility_for(sup, mvisibility)
694 end
695 if stdimport then
696 var mod_name = "standard"
697 var sup = self.get_mmodule_by_name(nmodule, null, mod_name)
698 if sup != null then # Skip error
699 imported_modules.add(sup)
700 mmodule.set_visibility_for(sup, public_visibility)
701 end
702 end
703 self.toolcontext.info("{mmodule} imports {imported_modules.join(", ")}", 3)
704 mmodule.set_imported_mmodules(imported_modules)
705
706 # TODO: Correctly check for useless importation
707 # It is even doable?
708 var directs = mmodule.in_importation.direct_greaters
709 for nim in nmodule.n_imports do
710 if not nim isa AStdImport then continue
711 var im = nim.mmodule
712 if im == null then continue
713 if directs.has(im) then continue
714 # This generates so much noise that it is simpler to just comment it
715 #warning(nim, "Warning: possible useless importation of {im}")
716 end
717 end
718
719 # All the loaded modules
720 var nmodules = new Array[AModule]
721
722 # Register the nmodule associated to each mmodule
723 # FIXME: why not refine the `MModule` class with a nullable attribute?
724 var mmodule2nmodule = new HashMap[MModule, AModule]
725
726 # Helper function to display an error on a node.
727 # Alias for `self.toolcontext.error(n.hot_location, text)`
728 fun error(n: ANode, text: String)
729 do
730 self.toolcontext.error(n.hot_location, text)
731 end
732
733 # Helper function to display a warning on a node.
734 # Alias for: `self.toolcontext.warning(n.hot_location, text)`
735 fun warning(n: ANode, tag, text: String)
736 do
737 self.toolcontext.warning(n.hot_location, tag, text)
738 end
739
740 # Helper function to display an advice on a node.
741 # Alias for: `self.toolcontext.advice(n.hot_location, text)`
742 fun advice(n: ANode, tag, text: String)
743 do
744 self.toolcontext.advice(n.hot_location, tag, text)
745 end
746
747 # Force to get the primitive method named `name` on the type `recv` or do a fatal error on `n`
748 fun force_get_primitive_method(n: nullable ANode, name: String, recv: MClass, mmodule: MModule): MMethod
749 do
750 var res = mmodule.try_get_primitive_method(name, recv)
751 if res == null then
752 var l = null
753 if n != null then l = n.hot_location
754 self.toolcontext.fatal_error(l, "Fatal Error: {recv} must have a property named {name}.")
755 abort
756 end
757 return res
758 end
759 end
760
761 # placeholder to a module file identified but not always loaded in a project
762 private class ModulePath
763 # The name of the module
764 # (it's the basename of the filepath)
765 var name: String
766
767 # The human path of the module
768 var filepath: String
769
770 # The group (and the project) of the possible module
771 var mgroup: MGroup
772
773 # The loaded module (if any)
774 var mmodule: nullable MModule = null
775
776 redef fun to_s do return filepath
777 end
778
779 redef class MGroup
780 # modules paths associated with the group
781 private var module_paths = new Array[ModulePath]
782 end
783
784 redef class AStdImport
785 # The imported module once determined
786 var mmodule: nullable MModule = null
787 end
788
789 redef class AModule
790 # The associated MModule once build by a `ModelBuilder`
791 var mmodule: nullable MModule
792 # Flag that indicate if the importation is already completed
793 var is_importation_done: Bool = false
794 end
795
796 redef class AVisibility
797 # The visibility level associated with the AST node class
798 fun mvisibility: MVisibility is abstract
799 end
800 redef class AIntrudeVisibility
801 redef fun mvisibility do return intrude_visibility
802 end
803 redef class APublicVisibility
804 redef fun mvisibility do return public_visibility
805 end
806 redef class AProtectedVisibility
807 redef fun mvisibility do return protected_visibility
808 end
809 redef class APrivateVisibility
810 redef fun mvisibility do return private_visibility
811 end
812
813 redef class ADoc
814 private var mdoc_cache: nullable MDoc
815 fun to_mdoc: MDoc
816 do
817 var res = mdoc_cache
818 if res != null then return res
819 res = new MDoc
820 for c in n_comment do
821 var text = c.text
822 if text.length < 2 then
823 res.content.add ""
824 continue
825 end
826 assert text.chars[0] == '#'
827 if text.chars[1] == ' ' then
828 text = text.substring_from(2) # eat starting `#` and space
829 else
830 text = text.substring_from(1) # eat atarting `#` only
831 end
832 if text.chars.last == '\n' then text = text.substring(0, text.length-1) # drop \n
833 res.content.add(text)
834 end
835 mdoc_cache = res
836 return res
837 end
838 end