model: `new` factories are named "new", not init.
[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
229 # new-factories are invisible outside of the class
230 if mprop isa MMethod and mprop.is_new and (not mtype isa MClassType or mprop.intro_mclassdef.mclass != mtype.mclass) then
231 continue
232 end
233
234 if res == null then
235 res = mprop
236 continue
237 end
238
239 # Two global properties?
240 # First, special case for init, keep the most specific ones
241 if res isa MMethod and mprop isa MMethod and res.is_init and mprop.is_init then
242 var restype = res.intro_mclassdef.bound_mtype
243 var mproptype = mprop.intro_mclassdef.bound_mtype
244 if mproptype.is_subtype(mmodule, null, restype) then
245 # found a most specific constructor, so keep it
246 res = mprop
247 continue
248 end
249 end
250
251 # Ok, just keep all prop in the ress table
252 if ress == null then
253 ress = new Array[MProperty]
254 ress.add(res)
255 end
256 ress.add(mprop)
257 end
258
259 # There is conflict?
260 if ress != null and res isa MMethod and res.is_init then
261 # special case forinit again
262 var restype = res.intro_mclassdef.bound_mtype
263 var ress2 = new Array[MProperty]
264 for mprop in ress do
265 var mproptype = mprop.intro_mclassdef.bound_mtype
266 if not restype.is_subtype(mmodule, null, mproptype) then
267 ress2.add(mprop)
268 else if not mprop isa MMethod or not mprop.is_init then
269 ress2.add(mprop)
270 end
271 end
272 if ress2.is_empty then
273 ress = null
274 else
275 ress = ress2
276 ress.add(res)
277 end
278 end
279
280 if ress != null then
281 assert ress.length > 1
282 var s = new Array[String]
283 for mprop in ress do s.add mprop.full_name
284 self.error(anode, "Ambigous property name '{name}' for {mtype}; conflict between {s.join(" and ")}")
285 end
286
287 self.try_get_mproperty_by_name2_cache[mmodule, mtype, name] = res
288 return res
289 end
290
291 private var try_get_mproperty_by_name2_cache = new HashMap3[MModule, MType, String, nullable MProperty]
292
293
294 # Alias for try_get_mproperty_by_name2(anode, mclassdef.mmodule, mclassdef.mtype, name)
295 fun try_get_mproperty_by_name(anode: ANode, mclassdef: MClassDef, name: String): nullable MProperty
296 do
297 return try_get_mproperty_by_name2(anode, mclassdef.mmodule, mclassdef.bound_mtype, name)
298 end
299
300 # The list of directories to search for top level modules
301 # The list is initially set with :
302 # * the toolcontext --path option
303 # * the NIT_PATH environment variable
304 # * `toolcontext.nit_dir`
305 # Path can be added (or removed) by the client
306 var paths = new Array[String]
307
308 # Like (an used by) `get_mmodule_by_name` but just return the ModulePath
309 private fun search_mmodule_by_name(anode: ANode, mgroup: nullable MGroup, name: String): nullable ModulePath
310 do
311 # First, look in groups
312 var c = mgroup
313 while c != null do
314 var dirname = c.filepath
315 if dirname == null then break # virtual group
316 if dirname.has_suffix(".nit") then break # singleton project
317
318 # Second, try the directory to find a file
319 var try_file = dirname + "/" + name + ".nit"
320 if try_file.file_exists then
321 var res = self.identify_file(try_file.simplify_path)
322 assert res != null
323 return res
324 end
325
326 # Third, try if the requested module is itself a group
327 try_file = dirname + "/" + name + "/" + name + ".nit"
328 if try_file.file_exists then
329 var res = self.identify_file(try_file.simplify_path)
330 assert res != null
331 return res
332 end
333
334 c = c.parent
335 end
336
337 # Look at some known directories
338 var lookpaths = self.paths
339
340 # Look in the directory of the group project also (even if not explicitely in the path)
341 if mgroup != null then
342 # path of the root group
343 var dirname = mgroup.mproject.root.filepath
344 if dirname != null then
345 dirname = dirname.join_path("..").simplify_path
346 if not lookpaths.has(dirname) and dirname.file_exists then
347 lookpaths = lookpaths.to_a
348 lookpaths.add(dirname)
349 end
350 end
351 end
352
353 var candidate = search_module_in_paths(anode.hot_location, name, lookpaths)
354
355 if candidate == null then
356 if mgroup != null then
357 error(anode, "Error: cannot find module {name} from {mgroup.name}. tried {lookpaths.join(", ")}")
358 else
359 error(anode, "Error: cannot find module {name}. tried {lookpaths.join(", ")}")
360 end
361 return null
362 end
363 return candidate
364 end
365
366 # Get a module by its short name; if required, the module is loaded, parsed and its hierarchies computed.
367 # If `mgroup` is set, then the module search starts from it up to the top level (see `paths`);
368 # if `mgroup` is null then the module is searched in the top level only.
369 # If no module exists or there is a name conflict, then an error on `anode` is displayed and null is returned.
370 fun get_mmodule_by_name(anode: ANode, mgroup: nullable MGroup, name: String): nullable MModule
371 do
372 var path = search_mmodule_by_name(anode, mgroup, name)
373 if path == null then return null # Forward error
374 var res = self.load_module(path.filepath)
375 if res == null then return null # Forward error
376 return res.mmodule.as(not null)
377 end
378
379 # Search a module `name` from path `lookpaths`.
380 # If found, the path of the file is returned
381 private fun search_module_in_paths(location: nullable Location, name: String, lookpaths: Collection[String]): nullable ModulePath
382 do
383 var candidate: nullable String = null
384 for dirname in lookpaths do
385 var try_file = (dirname + "/" + name + ".nit").simplify_path
386 if try_file.file_exists then
387 if candidate == null then
388 candidate = try_file
389 else if candidate != try_file then
390 # try to disambiguate conflicting modules
391 var abs_candidate = module_absolute_path(candidate)
392 var abs_try_file = module_absolute_path(try_file)
393 if abs_candidate != abs_try_file then
394 toolcontext.error(location, "Error: conflicting module file for {name}: {candidate} {try_file}")
395 end
396 end
397 end
398 try_file = (dirname + "/" + name + "/" + name + ".nit").simplify_path
399 if try_file.file_exists then
400 if candidate == null then
401 candidate = try_file
402 else if candidate != try_file then
403 # try to disambiguate conflicting modules
404 var abs_candidate = module_absolute_path(candidate)
405 var abs_try_file = module_absolute_path(try_file)
406 if abs_candidate != abs_try_file then
407 toolcontext.error(location, "Error: conflicting module file for {name}: {candidate} {try_file}")
408 end
409 end
410 end
411 end
412 if candidate == null then return null
413 return identify_file(candidate)
414 end
415
416 # cache for `identify_file` by realpath
417 private var identified_files = new HashMap[String, nullable ModulePath]
418
419 # Identify a source file
420 # Load the associated project and groups if required
421 private fun identify_file(path: String): nullable ModulePath
422 do
423 # special case for not a nit file
424 if path.file_extension != "nit" then
425 # search in known -I paths
426 var res = search_module_in_paths(null, path, self.paths)
427 if res != null then return res
428
429 # Found nothins? maybe it is a group...
430 var candidate = null
431 if path.file_exists then
432 var mgroup = get_mgroup(path)
433 if mgroup != null then
434 var owner_path = mgroup.filepath.join_path(mgroup.name + ".nit")
435 if owner_path.file_exists then candidate = owner_path
436 end
437 end
438
439 if candidate == null then
440 toolcontext.error(null, "Error: cannot find module `{path}`.")
441 return null
442 end
443 path = candidate
444 end
445
446 # Fast track, the path is already known
447 var pn = path.basename(".nit")
448 var rp = module_absolute_path(path)
449 if identified_files.has_key(rp) then return identified_files[rp]
450
451 # Search for a group
452 var mgrouppath = path.join_path("..").simplify_path
453 var mgroup = get_mgroup(mgrouppath)
454
455 if mgroup == null then
456 # singleton project
457 var mproject = new MProject(pn, model)
458 mgroup = new MGroup(pn, mproject, null) # same name for the root group
459 mgroup.filepath = path
460 mproject.root = mgroup
461 toolcontext.info("found project `{pn}` at {path}", 2)
462 end
463
464 var res = new ModulePath(pn, path, mgroup)
465 mgroup.module_paths.add(res)
466
467 identified_files[rp] = res
468 return res
469 end
470
471 # groups by path
472 private var mgroups = new HashMap[String, nullable MGroup]
473
474 # return the mgroup associated to a directory path
475 # if the directory is not a group null is returned
476 private fun get_mgroup(dirpath: String): nullable MGroup
477 do
478 var rdp = module_absolute_path(dirpath)
479 if mgroups.has_key(rdp) then
480 return mgroups[rdp]
481 end
482
483 # Hack, a group is determined by:
484 # * the presence of a honomymous nit file
485 # * the fact that the directory is named `src`
486 var pn = rdp.basename(".nit")
487 var mp = dirpath.join_path(pn + ".nit").simplify_path
488
489 var dirpath2 = dirpath
490 if not mp.file_exists then
491 if pn == "src" then
492 # With a src directory, the group name is the name of the parent directory
493 dirpath2 = rdp.dirname
494 pn = dirpath2.basename("")
495 else
496 return null
497 end
498 end
499
500 # check parent directory
501 var parentpath = dirpath.join_path("..").simplify_path
502 var parent = get_mgroup(parentpath)
503
504 var mgroup
505 if parent == null then
506 # no parent, thus new project
507 var mproject = new MProject(pn, model)
508 mgroup = new MGroup(pn, mproject, null) # same name for the root group
509 mproject.root = mgroup
510 toolcontext.info("found project `{mproject}` at {dirpath}", 2)
511 else
512 mgroup = new MGroup(pn, parent.mproject, parent)
513 toolcontext.info("found sub group `{mgroup.full_name}` at {dirpath}", 2)
514 end
515 var readme = dirpath2.join_path("README.md")
516 if not readme.file_exists then readme = dirpath2.join_path("README")
517 if readme.file_exists then
518 var mdoc = new MDoc
519 var s = new IFStream.open(readme)
520 while not s.eof do
521 mdoc.content.add(s.read_line)
522 end
523 mgroup.mdoc = mdoc
524 mdoc.original_mentity = mgroup
525 end
526 mgroup.filepath = dirpath
527 mgroups[rdp] = mgroup
528 return mgroup
529 end
530
531 # Transform relative paths (starting with '../') into absolute paths
532 private fun module_absolute_path(path: String): String do
533 return getcwd.join_path(path).simplify_path
534 end
535
536 # Try to load a module AST using a path.
537 # Display an error if there is a problem (IO / lexer / parser) and return null
538 fun load_module_ast(filename: String): nullable AModule
539 do
540 if filename.file_extension != "nit" then
541 self.toolcontext.error(null, "Error: file {filename} is not a valid nit module.")
542 return null
543 end
544 if not filename.file_exists then
545 self.toolcontext.error(null, "Error: file {filename} not found.")
546 return null
547 end
548
549 self.toolcontext.info("load module {filename}", 2)
550
551 # Load the file
552 var file = new IFStream.open(filename)
553 var lexer = new Lexer(new SourceFile(filename, file))
554 var parser = new Parser(lexer)
555 var tree = parser.parse
556 file.close
557
558 # Handle lexer and parser error
559 var nmodule = tree.n_base
560 if nmodule == null then
561 var neof = tree.n_eof
562 assert neof isa AError
563 error(neof, neof.message)
564 return null
565 end
566
567 return nmodule
568 end
569
570 # Try to load a module and its imported modules using a path.
571 # Display an error if there is a problem (IO / lexer / parser / importation) and return null
572 # Note: usually, you do not need this method, use `get_mmodule_by_name` instead.
573 fun load_module(filename: String): nullable AModule
574 do
575 # Look for the module
576 var file = identify_file(filename)
577 if file == null then return null # forward error
578
579 # Already known and loaded? then return it
580 var mmodule = file.mmodule
581 if mmodule != null then
582 return mmodule2nmodule[mmodule]
583 end
584
585 # Load it manually
586 var nmodule = load_module_ast(file.filepath)
587 if nmodule == null then return null # forward error
588
589 # build the mmodule and load imported modules
590 mmodule = build_a_mmodule(file.mgroup, file.name, nmodule)
591
592 if mmodule == null then return null # forward error
593
594 # Update the file information
595 file.mmodule = mmodule
596
597 # Load imported module
598 build_module_importation(nmodule)
599
600 return nmodule
601 end
602
603 # Injection of a new module without source.
604 # Used by the interpreted
605 fun load_rt_module(parent: nullable MModule, nmodule: AModule, mod_name: String): nullable AModule
606 do
607 # Create the module
608
609 var mgroup = null
610 if parent != null then mgroup = parent.mgroup
611 var mmodule = new MModule(model, mgroup, mod_name, nmodule.location)
612 nmodule.mmodule = mmodule
613 nmodules.add(nmodule)
614 self.mmodule2nmodule[mmodule] = nmodule
615
616 if parent!= null then
617 var imported_modules = new Array[MModule]
618 imported_modules.add(parent)
619 mmodule.set_visibility_for(parent, intrude_visibility)
620 mmodule.set_imported_mmodules(imported_modules)
621 else
622 build_module_importation(nmodule)
623 end
624
625 return nmodule
626 end
627
628 # Visit the AST and create the `MModule` object
629 private fun build_a_mmodule(mgroup: nullable MGroup, mod_name: String, nmodule: AModule): nullable MModule
630 do
631 # Check the module name
632 var decl = nmodule.n_moduledecl
633 if decl == null then
634 #warning(nmodule, "Warning: Missing 'module' keyword") #FIXME: NOT YET FOR COMPATIBILITY
635 else
636 var decl_name = decl.n_name.n_id.text
637 if decl_name != mod_name then
638 error(decl.n_name, "Error: module name missmatch; declared {decl_name} file named {mod_name}")
639 end
640 end
641
642 # Create the module
643 var mmodule = new MModule(model, mgroup, mod_name, nmodule.location)
644 nmodule.mmodule = mmodule
645 nmodules.add(nmodule)
646 self.mmodule2nmodule[mmodule] = nmodule
647
648 if decl != null then
649 var ndoc = decl.n_doc
650 if ndoc != null then
651 var mdoc = ndoc.to_mdoc
652 mmodule.mdoc = mdoc
653 mdoc.original_mentity = mmodule
654 else
655 advice(decl, "missing-doc", "Documentation warning: Undocumented module `{mmodule}`")
656 end
657 end
658
659 return mmodule
660 end
661
662 # Analysis the module importation and fill the module_importation_hierarchy
663 private fun build_module_importation(nmodule: AModule)
664 do
665 if nmodule.is_importation_done then return
666 nmodule.is_importation_done = true
667 var mmodule = nmodule.mmodule.as(not null)
668 var stdimport = true
669 var imported_modules = new Array[MModule]
670 for aimport in nmodule.n_imports do
671 stdimport = false
672 if not aimport isa AStdImport then
673 continue
674 end
675 var mgroup = mmodule.mgroup
676 if aimport.n_name.n_quad != null then mgroup = null # Start from top level
677 for grp in aimport.n_name.n_path do
678 var path = search_mmodule_by_name(grp, mgroup, grp.text)
679 if path == null then return # Skip error
680 mgroup = path.mgroup
681 end
682 var mod_name = aimport.n_name.n_id.text
683 var sup = self.get_mmodule_by_name(aimport.n_name, mgroup, mod_name)
684 if sup == null then continue # Skip error
685 aimport.mmodule = sup
686 imported_modules.add(sup)
687 var mvisibility = aimport.n_visibility.mvisibility
688 if mvisibility == protected_visibility then
689 error(aimport.n_visibility, "Error: only properties can be protected.")
690 return
691 end
692 if sup == mmodule then
693 error(aimport.n_name, "Error: Dependency loop in module {mmodule}.")
694 end
695 if sup.in_importation < mmodule then
696 error(aimport.n_name, "Error: Dependency loop between modules {mmodule} and {sup}.")
697 return
698 end
699 mmodule.set_visibility_for(sup, mvisibility)
700 end
701 if stdimport then
702 var mod_name = "standard"
703 var sup = self.get_mmodule_by_name(nmodule, null, mod_name)
704 if sup != null then # Skip error
705 imported_modules.add(sup)
706 mmodule.set_visibility_for(sup, public_visibility)
707 end
708 end
709 self.toolcontext.info("{mmodule} imports {imported_modules.join(", ")}", 3)
710 mmodule.set_imported_mmodules(imported_modules)
711
712 # TODO: Correctly check for useless importation
713 # It is even doable?
714 var directs = mmodule.in_importation.direct_greaters
715 for nim in nmodule.n_imports do
716 if not nim isa AStdImport then continue
717 var im = nim.mmodule
718 if im == null then continue
719 if directs.has(im) then continue
720 # This generates so much noise that it is simpler to just comment it
721 #warning(nim, "Warning: possible useless importation of {im}")
722 end
723 end
724
725 # All the loaded modules
726 var nmodules = new Array[AModule]
727
728 # Register the nmodule associated to each mmodule
729 # FIXME: why not refine the `MModule` class with a nullable attribute?
730 var mmodule2nmodule = new HashMap[MModule, AModule]
731
732 # Helper function to display an error on a node.
733 # Alias for `self.toolcontext.error(n.hot_location, text)`
734 fun error(n: ANode, text: String)
735 do
736 self.toolcontext.error(n.hot_location, text)
737 end
738
739 # Helper function to display a warning on a node.
740 # Alias for: `self.toolcontext.warning(n.hot_location, text)`
741 fun warning(n: ANode, tag, text: String)
742 do
743 self.toolcontext.warning(n.hot_location, tag, text)
744 end
745
746 # Helper function to display an advice on a node.
747 # Alias for: `self.toolcontext.advice(n.hot_location, text)`
748 fun advice(n: ANode, tag, text: String)
749 do
750 self.toolcontext.advice(n.hot_location, tag, text)
751 end
752
753 # Force to get the primitive method named `name` on the type `recv` or do a fatal error on `n`
754 fun force_get_primitive_method(n: nullable ANode, name: String, recv: MClass, mmodule: MModule): MMethod
755 do
756 var res = mmodule.try_get_primitive_method(name, recv)
757 if res == null then
758 var l = null
759 if n != null then l = n.hot_location
760 self.toolcontext.fatal_error(l, "Fatal Error: {recv} must have a property named {name}.")
761 abort
762 end
763 return res
764 end
765 end
766
767 # placeholder to a module file identified but not always loaded in a project
768 private class ModulePath
769 # The name of the module
770 # (it's the basename of the filepath)
771 var name: String
772
773 # The human path of the module
774 var filepath: String
775
776 # The group (and the project) of the possible module
777 var mgroup: MGroup
778
779 # The loaded module (if any)
780 var mmodule: nullable MModule = null
781
782 redef fun to_s do return filepath
783 end
784
785 redef class MGroup
786 # modules paths associated with the group
787 private var module_paths = new Array[ModulePath]
788 end
789
790 redef class AStdImport
791 # The imported module once determined
792 var mmodule: nullable MModule = null
793 end
794
795 redef class AModule
796 # The associated MModule once build by a `ModelBuilder`
797 var mmodule: nullable MModule
798 # Flag that indicate if the importation is already completed
799 var is_importation_done: Bool = false
800 end
801
802 redef class AVisibility
803 # The visibility level associated with the AST node class
804 fun mvisibility: MVisibility is abstract
805 end
806 redef class AIntrudeVisibility
807 redef fun mvisibility do return intrude_visibility
808 end
809 redef class APublicVisibility
810 redef fun mvisibility do return public_visibility
811 end
812 redef class AProtectedVisibility
813 redef fun mvisibility do return protected_visibility
814 end
815 redef class APrivateVisibility
816 redef fun mvisibility do return private_visibility
817 end
818
819 redef class ADoc
820 private var mdoc_cache: nullable MDoc
821 fun to_mdoc: MDoc
822 do
823 var res = mdoc_cache
824 if res != null then return res
825 res = new MDoc
826 for c in n_comment do
827 var text = c.text
828 if text.length < 2 then
829 res.content.add ""
830 continue
831 end
832 assert text.chars[0] == '#'
833 if text.chars[1] == ' ' then
834 text = text.substring_from(2) # eat starting `#` and space
835 else
836 text = text.substring_from(1) # eat atarting `#` only
837 end
838 if text.chars.last == '\n' then text = text.substring(0, text.length-1) # drop \n
839 res.content.add(text)
840 end
841 mdoc_cache = res
842 return res
843 end
844 end