modulebuilder: module_absolute_path does always its job
[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 parser
26 import model
27 import poset
28 import opts
29 import toolcontext
30 import phase
31
32 private import more_collections
33
34 ###
35
36 redef class ToolContext
37 # Option --path
38 var opt_path: OptionArray = new OptionArray("Set include path for loaders (may be used more than once)", "-I", "--path")
39
40 # Option --only-metamodel
41 var opt_only_metamodel: OptionBool = new OptionBool("Stop after meta-model processing", "--only-metamodel")
42
43 # Option --only-parse
44 var opt_only_parse: OptionBool = new OptionBool("Only proceed to parse step of loaders", "--only-parse")
45
46 redef init
47 do
48 super
49 option_context.add_option(opt_path, opt_only_parse, opt_only_metamodel)
50 end
51
52 fun modelbuilder: ModelBuilder do return modelbuilder_real.as(not null)
53 private var modelbuilder_real: nullable ModelBuilder = null
54
55 fun run_global_phases(mainmodule: MModule)
56 do
57 for phase in phases_list do
58 phase.process_mainmodule(mainmodule)
59 end
60 end
61 end
62
63 redef class Phase
64 # Specific action to execute on the whole program
65 # Called by the `ToolContext::run_global_phases`
66 # @toimplement
67 fun process_mainmodule(mainmodule: MModule) do end
68 end
69
70
71 # A model builder knows how to load nit source files and build the associated model
72 class ModelBuilder
73 # The model where new modules, classes and properties are added
74 var model: Model
75
76 # The toolcontext used to control the interaction with the user (getting options and displaying messages)
77 var toolcontext: ToolContext
78
79 # Run phases on all loaded modules
80 fun run_phases
81 do
82 var mmodules = model.mmodules.to_a
83 model.mmodule_importation_hierarchy.sort(mmodules)
84 var nmodules = new Array[AModule]
85 for mm in mmodules do
86 nmodules.add(mmodule2nmodule[mm])
87 end
88 toolcontext.run_phases(nmodules)
89
90 if toolcontext.opt_only_metamodel.value then
91 self.toolcontext.info("*** ONLY METAMODEL", 1)
92 exit(0)
93 end
94 end
95
96 # Instantiate a modelbuilder for a model and a toolcontext
97 # Important, the options of the toolcontext must be correctly set (parse_option already called)
98 init(model: Model, toolcontext: ToolContext)
99 do
100 self.model = model
101 self.toolcontext = toolcontext
102 assert toolcontext.modelbuilder_real == null
103 toolcontext.modelbuilder_real = self
104
105 # Setup the paths value
106 paths.append(toolcontext.opt_path.value)
107
108 var path_env = "NIT_PATH".environ
109 if not path_env.is_empty then
110 paths.append(path_env.split_with(':'))
111 end
112
113 path_env = "NIT_DIR".environ
114 if not path_env.is_empty then
115 var libname = "{path_env}/lib"
116 if libname.file_exists then paths.add(libname)
117 end
118
119 var libname = "{sys.program_name.dirname}/../lib"
120 if libname.file_exists then paths.add(libname.simplify_path)
121 end
122
123 # Load a bunch of modules.
124 # `modules` can contains filenames or module names.
125 # Imported modules are automatically loaded and modelized.
126 # The result is the corresponding model elements.
127 # Errors and warnings are printed with the toolcontext.
128 #
129 # Note: class and property model element are not analysed.
130 fun parse(modules: Sequence[String]): Array[MModule]
131 do
132 var time0 = get_time
133 # Parse and recursively load
134 self.toolcontext.info("*** PARSE ***", 1)
135 var mmodules = new ArraySet[MModule]
136 for a in modules do
137 var nmodule = self.load_module(a)
138 if nmodule == null then continue # Skip error
139 mmodules.add(nmodule.mmodule.as(not null))
140 end
141 var time1 = get_time
142 self.toolcontext.info("*** END PARSE: {time1-time0} ***", 2)
143
144 self.toolcontext.check_errors
145
146 if toolcontext.opt_only_parse.value then
147 self.toolcontext.info("*** ONLY PARSE...", 1)
148 exit(0)
149 end
150
151 return mmodules.to_a
152 end
153
154 # Return a class named `name` visible by the module `mmodule`.
155 # Visibility in modules is correctly handled.
156 # If no such a class exists, then null is returned.
157 # If more than one class exists, then an error on `anode` is displayed and null is returned.
158 # FIXME: add a way to handle class name conflict
159 fun try_get_mclass_by_name(anode: ANode, mmodule: MModule, name: String): nullable MClass
160 do
161 var classes = model.get_mclasses_by_name(name)
162 if classes == null then
163 return null
164 end
165
166 var res: nullable MClass = null
167 for mclass in classes do
168 if not mmodule.in_importation <= mclass.intro_mmodule then continue
169 if not mmodule.is_visible(mclass.intro_mmodule, mclass.visibility) then continue
170 if res == null then
171 res = mclass
172 else
173 error(anode, "Ambigous class name '{name}'; conflict between {mclass.full_name} and {res.full_name}")
174 return null
175 end
176 end
177 return res
178 end
179
180 # Return a property named `name` on the type `mtype` visible in the module `mmodule`.
181 # Visibility in modules is correctly handled.
182 # Protected properties are returned (it is up to the caller to check and reject protected properties).
183 # If no such a property exists, then null is returned.
184 # If more than one property exists, then an error on `anode` is displayed and null is returned.
185 # FIXME: add a way to handle property name conflict
186 fun try_get_mproperty_by_name2(anode: ANode, mmodule: MModule, mtype: MType, name: String): nullable MProperty
187 do
188 var props = self.model.get_mproperties_by_name(name)
189 if props == null then
190 return null
191 end
192
193 var cache = self.try_get_mproperty_by_name2_cache[mmodule, mtype, name]
194 if cache != null then return cache
195
196 var res: nullable MProperty = null
197 var ress: nullable Array[MProperty] = null
198 for mprop in props do
199 if not mtype.has_mproperty(mmodule, mprop) then continue
200 if not mmodule.is_visible(mprop.intro_mclassdef.mmodule, mprop.visibility) then continue
201 if res == null then
202 res = mprop
203 else
204 var restype = res.intro_mclassdef.bound_mtype
205 var mproptype = mprop.intro_mclassdef.bound_mtype
206 if restype.is_subtype(mmodule, null, mproptype) then
207 # we keep res
208 else if mproptype.is_subtype(mmodule, null, restype) then
209 res = mprop
210 else
211 if ress == null then ress = new Array[MProperty]
212 ress.add(mprop)
213 end
214 end
215 end
216 if ress != null then
217 var restype = res.intro_mclassdef.bound_mtype
218 for mprop in ress do
219 var mproptype = mprop.intro_mclassdef.bound_mtype
220 if not restype.is_subtype(mmodule, null, mproptype) then
221 self.error(anode, "Ambigous property name '{name}' for {mtype}; conflict between {mprop.full_name} and {res.full_name}")
222 return null
223 end
224 end
225 end
226
227 self.try_get_mproperty_by_name2_cache[mmodule, mtype, name] = res
228 return res
229 end
230
231 private var try_get_mproperty_by_name2_cache: HashMap3[MModule, MType, String, nullable MProperty] = new HashMap3[MModule, MType, String, nullable MProperty]
232
233
234 # Alias for try_get_mproperty_by_name2(anode, mclassdef.mmodule, mclassdef.mtype, name)
235 fun try_get_mproperty_by_name(anode: ANode, mclassdef: MClassDef, name: String): nullable MProperty
236 do
237 return try_get_mproperty_by_name2(anode, mclassdef.mmodule, mclassdef.bound_mtype, name)
238 end
239
240 # The list of directories to search for top level modules
241 # The list is initially set with :
242 # * the toolcontext --path option
243 # * the NIT_PATH environment variable
244 # * some heuristics including the NIT_DIR environment variable and the progname of the process
245 # Path can be added (or removed) by the client
246 var paths: Array[String] = new Array[String]
247
248 # Get a module by its short name; if required, the module is loaded, parsed and its hierarchies computed.
249 # If `mmodule` is set, then the module search starts from it up to the top level (see `paths`);
250 # if `mmodule` is null then the module is searched in the top level only.
251 # If no module exists or there is a name conflict, then an error on `anode` is displayed and null is returned.
252 # FIXME: add a way to handle module name conflict
253 fun get_mmodule_by_name(anode: ANode, mmodule: nullable MModule, name: String): nullable MModule
254 do
255 # what path where tried to display on error message
256 var tries = new Array[String]
257
258 # First, look in groups of the module
259 if mmodule != null then
260 var mgroup = mmodule.mgroup
261 while mgroup != null do
262 var dirname = mgroup.filepath
263 if dirname == null then break # virtual group
264 if dirname.has_suffix(".nit") then break # singleton project
265
266 # Second, try the directory to find a file
267 var try_file = dirname + "/" + name + ".nit"
268 tries.add try_file
269 if try_file.file_exists then
270 var res = self.load_module(try_file.simplify_path)
271 if res == null then return null # Forward error
272 return res.mmodule.as(not null)
273 end
274
275 # Third, try if the requested module is itself a group
276 try_file = dirname + "/" + name + "/" + name + ".nit"
277 if try_file.file_exists then
278 mgroup = get_mgroup(dirname + "/" + name)
279 var res = self.load_module(try_file.simplify_path)
280 if res == null then return null # Forward error
281 return res.mmodule.as(not null)
282 end
283
284 mgroup = mgroup.parent
285 end
286 end
287
288 # Look at some known directories
289 var lookpaths = self.paths
290
291 # Look in the directory of module project also (even if not explicitely in the path)
292 if mmodule != null and mmodule.mgroup != null then
293 # path of the root group
294 var dirname = mmodule.mgroup.mproject.root.filepath
295 if dirname != null then
296 dirname = dirname.join_path("..").simplify_path
297 if not lookpaths.has(dirname) and dirname.file_exists then
298 lookpaths = lookpaths.to_a
299 lookpaths.add(dirname)
300 end
301 end
302 end
303
304 var candidate: nullable String = null
305 for dirname in lookpaths do
306 var try_file = (dirname + "/" + name + ".nit").simplify_path
307 tries.add try_file
308 if try_file.file_exists then
309 if candidate == null then
310 candidate = try_file
311 else if candidate != try_file then
312 # try to disambiguate conflicting modules
313 var abs_candidate = module_absolute_path(candidate)
314 var abs_try_file = module_absolute_path(try_file)
315 if abs_candidate != abs_try_file then
316 error(anode, "Error: conflicting module file for {name}: {candidate} {try_file}")
317 end
318 end
319 end
320 try_file = (dirname + "/" + name + "/" + name + ".nit").simplify_path
321 if try_file.file_exists then
322 if candidate == null then
323 candidate = try_file
324 else if candidate != try_file then
325 # try to disambiguate conflicting modules
326 var abs_candidate = module_absolute_path(candidate)
327 var abs_try_file = module_absolute_path(try_file)
328 if abs_candidate != abs_try_file then
329 error(anode, "Error: conflicting module file for {name}: {candidate} {try_file}")
330 end
331 end
332 end
333 end
334 if candidate == null then
335 if mmodule != null then
336 error(anode, "Error: cannot find module {name} from {mmodule}. tried {tries.join(", ")}")
337 else
338 error(anode, "Error: cannot find module {name}. tried {tries.join(", ")}")
339 end
340 return null
341 end
342 var res = self.load_module(candidate)
343 if res == null then return null # Forward error
344 return res.mmodule.as(not null)
345 end
346
347 # cache for `identify_file` by realpath
348 private var identified_files = new HashMap[String, nullable ModulePath]
349
350 # Identify a source file
351 # Load the associated project and groups if required
352 private fun identify_file(path: String): nullable ModulePath
353 do
354 if not path.file_exists then
355 toolcontext.error(null, "Error: `{path}` does not exists")
356 return null
357 end
358
359 # Fast track, the path is already known
360 var pn = path.basename(".nit")
361 var rp = module_absolute_path(path)
362 if identified_files.has_key(rp) then return identified_files[rp]
363
364 # Search for a group
365 var mgrouppath = path.join_path("..").simplify_path
366 var mgroup = get_mgroup(mgrouppath)
367
368 if mgroup == null then
369 # singleton project
370 var mproject = new MProject(pn, model)
371 mgroup = new MGroup(pn, mproject, null) # same name for the root group
372 mgroup.filepath = path
373 mproject.root = mgroup
374 toolcontext.info("found project `{pn}` at {path}", 2)
375 end
376
377 var res = new ModulePath(pn, path, mgroup)
378
379 identified_files[rp] = res
380 return res
381 end
382
383 # groups by path
384 private var mgroups = new HashMap[String, nullable MGroup]
385
386 # return the mgroup associated to a directory path
387 # if the directory is not a group null is returned
388 private fun get_mgroup(dirpath: String): nullable MGroup
389 do
390 var rdp = module_absolute_path(dirpath)
391 if mgroups.has_key(rdp) then
392 return mgroups[rdp]
393 end
394
395 # Hack, a dir is determined by the presence of a honomymous nit file
396 var pn = rdp.basename(".nit")
397 var mp = dirpath.join_path(pn + ".nit").simplify_path
398
399 if not mp.file_exists then return null
400
401 # check parent directory
402 var parentpath = dirpath.join_path("..").simplify_path
403 var parent = get_mgroup(parentpath)
404
405 var mgroup
406 if parent == null then
407 # no parent, thus new project
408 var mproject = new MProject(pn, model)
409 mgroup = new MGroup(pn, mproject, null) # same name for the root group
410 mproject.root = mgroup
411 toolcontext.info("found project `{mproject}` at {dirpath}", 2)
412 else
413 mgroup = new MGroup(pn, parent.mproject, parent)
414 toolcontext.info("found sub group `{mgroup.full_name}` at {dirpath}", 2)
415 end
416 mgroup.filepath = dirpath
417 mgroups[rdp] = mgroup
418 return mgroup
419 end
420
421 # Transform relative paths (starting with '../') into absolute paths
422 private fun module_absolute_path(path: String): String do
423 return getcwd.join_path(path).simplify_path
424 end
425
426 # loaded module by absolute path
427 private var loaded_nmodules = new HashMap[String, AModule]
428
429 # Try to load a module AST using a path.
430 # Display an error if there is a problem (IO / lexer / parser) and return null
431 fun load_module_ast(filename: String): nullable AModule
432 do
433 if filename.file_extension != "nit" then
434 self.toolcontext.error(null, "Error: file {filename} is not a valid nit module.")
435 return null
436 end
437 if not filename.file_exists then
438 self.toolcontext.error(null, "Error: file {filename} not found.")
439 return null
440 end
441
442 var module_path = module_absolute_path(filename)
443 if loaded_nmodules.keys.has(module_path) then
444 return loaded_nmodules[module_path]
445 end
446
447 self.toolcontext.info("load module {filename}", 2)
448
449 # Load the file
450 var file = new IFStream.open(filename)
451 var lexer = new Lexer(new SourceFile(filename, file))
452 var parser = new Parser(lexer)
453 var tree = parser.parse
454 file.close
455 var mod_name = filename.basename(".nit")
456
457 # Handle lexer and parser error
458 var nmodule = tree.n_base
459 if nmodule == null then
460 var neof = tree.n_eof
461 assert neof isa AError
462 error(neof, neof.message)
463 return null
464 end
465
466 loaded_nmodules[module_path] = nmodule
467 return nmodule
468 end
469
470 # Try to load a module and its imported modules using a path.
471 # Display an error if there is a problem (IO / lexer / parser / importation) and return null
472 # Note: usually, you do not need this method, use `get_mmodule_by_name` instead.
473 fun load_module(filename: String): nullable AModule
474 do
475 # Look for the module
476 var file = identify_file(filename)
477 if file == null then return null # forward error
478
479 # Already known and loaded? then return it
480 var mmodule = file.mmodule
481 if mmodule != null then
482 return mmodule2nmodule[mmodule]
483 end
484
485 # Load it manually
486 var nmodule = load_module_ast(filename)
487 if nmodule == null then return null # forward error
488
489 # build the mmodule and load imported modules
490 mmodule = build_a_mmodule(file.mgroup, file.name, nmodule)
491
492 if mmodule == null then return null # forward error
493
494 # Update the file information
495 file.mmodule = mmodule
496
497 return nmodule
498 end
499
500 fun load_rt_module(parent: MModule, nmodule: AModule, mod_name: String): nullable AModule
501 do
502 # Create the module
503 var mmodule = new MModule(model, parent.mgroup, mod_name, nmodule.location)
504 nmodule.mmodule = mmodule
505 nmodules.add(nmodule)
506 self.mmodule2nmodule[mmodule] = nmodule
507
508 var imported_modules = new Array[MModule]
509
510 imported_modules.add(parent)
511 mmodule.set_visibility_for(parent, intrude_visibility)
512
513 mmodule.set_imported_mmodules(imported_modules)
514
515 return nmodule
516 end
517
518 # Visit the AST and create the `MModule` object
519 # Then, recursively load imported modules
520 private fun build_a_mmodule(mgroup: nullable MGroup, mod_name: String, nmodule: AModule): nullable MModule
521 do
522 # Check the module name
523 var decl = nmodule.n_moduledecl
524 if decl == null then
525 #warning(nmodule, "Warning: Missing 'module' keyword") #FIXME: NOT YET FOR COMPATIBILITY
526 else
527 var decl_name = decl.n_name.n_id.text
528 if decl_name != mod_name then
529 error(decl.n_name, "Error: module name missmatch; declared {decl_name} file named {mod_name}")
530 end
531 end
532
533 # Create the module
534 var mmodule = new MModule(model, mgroup, mod_name, nmodule.location)
535 nmodule.mmodule = mmodule
536 nmodules.add(nmodule)
537 self.mmodule2nmodule[mmodule] = nmodule
538
539 build_module_importation(nmodule)
540
541 return mmodule
542 end
543
544 # Analysis the module importation and fill the module_importation_hierarchy
545 private fun build_module_importation(nmodule: AModule)
546 do
547 if nmodule.is_importation_done then return
548 nmodule.is_importation_done = true
549 var mmodule = nmodule.mmodule.as(not null)
550 var stdimport = true
551 var imported_modules = new Array[MModule]
552 for aimport in nmodule.n_imports do
553 stdimport = false
554 if not aimport isa AStdImport then
555 continue
556 end
557 var mod_name = aimport.n_name.n_id.text
558 var sup = self.get_mmodule_by_name(aimport.n_name, mmodule, mod_name)
559 if sup == null then continue # Skip error
560 aimport.mmodule = sup
561 imported_modules.add(sup)
562 var mvisibility = aimport.n_visibility.mvisibility
563 if mvisibility == protected_visibility then
564 error(aimport.n_visibility, "Error: only properties can be protected.")
565 return
566 end
567 mmodule.set_visibility_for(sup, mvisibility)
568 end
569 if stdimport then
570 var mod_name = "standard"
571 var sup = self.get_mmodule_by_name(nmodule, null, mod_name)
572 if sup != null then # Skip error
573 imported_modules.add(sup)
574 mmodule.set_visibility_for(sup, public_visibility)
575 end
576 end
577 self.toolcontext.info("{mmodule} imports {imported_modules.join(", ")}", 3)
578 mmodule.set_imported_mmodules(imported_modules)
579 end
580
581 # All the loaded modules
582 var nmodules: Array[AModule] = new Array[AModule]
583
584 # Register the nmodule associated to each mmodule
585 # FIXME: why not refine the `MModule` class with a nullable attribute?
586 var mmodule2nmodule: HashMap[MModule, AModule] = new HashMap[MModule, AModule]
587
588 # Helper function to display an error on a node.
589 # Alias for `self.toolcontext.error(n.hot_location, text)`
590 fun error(n: ANode, text: String)
591 do
592 self.toolcontext.error(n.hot_location, text)
593 end
594
595 # Helper function to display a warning on a node.
596 # Alias for: `self.toolcontext.warning(n.hot_location, text)`
597 fun warning(n: ANode, text: String)
598 do
599 self.toolcontext.warning(n.hot_location, text)
600 end
601
602 # Force to get the primitive method named `name` on the type `recv` or do a fatal error on `n`
603 fun force_get_primitive_method(n: ANode, name: String, recv: MClass, mmodule: MModule): MMethod
604 do
605 var res = mmodule.try_get_primitive_method(name, recv)
606 if res == null then
607 self.toolcontext.fatal_error(n.hot_location, "Fatal Error: {recv} must have a property named {name}.")
608 abort
609 end
610 return res
611 end
612 end
613
614 # placeholder to a module file identified but not always loaded in a project
615 private class ModulePath
616 # The name of the module
617 # (it's the basename of the filepath)
618 var name: String
619
620 # The human path of the module
621 var filepath: String
622
623 # The group (and the project) of the possible module
624 var mgroup: MGroup
625
626 # The loaded module (if any)
627 var mmodule: nullable MModule = null
628
629 redef fun to_s do return filepath
630 end
631
632
633 redef class AStdImport
634 # The imported module once determined
635 var mmodule: nullable MModule = null
636 end
637
638 redef class AModule
639 # The associated MModule once build by a `ModelBuilder`
640 var mmodule: nullable MModule
641 # Flag that indicate if the importation is already completed
642 var is_importation_done: Bool = false
643 end
644
645 redef class AVisibility
646 # The visibility level associated with the AST node class
647 fun mvisibility: MVisibility is abstract
648 end
649 redef class AIntrudeVisibility
650 redef fun mvisibility do return intrude_visibility
651 end
652 redef class APublicVisibility
653 redef fun mvisibility do return public_visibility
654 end
655 redef class AProtectedVisibility
656 redef fun mvisibility do return protected_visibility
657 end
658 redef class APrivateVisibility
659 redef fun mvisibility do return private_visibility
660 end