loader: add visit_group
[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 # Load nit source files and build the associated model
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 end
56
57 # Load a bunch of modules.
58 # `modules` can contains filenames or module names.
59 # Imported modules are automatically loaded and modelized.
60 # The result is the corresponding model elements.
61 # Errors and warnings are printed with the toolcontext.
62 #
63 # Note: class and property model element are not analysed.
64 fun parse(modules: Sequence[String]): Array[MModule]
65 do
66 var time0 = get_time
67 # Parse and recursively load
68 self.toolcontext.info("*** PARSE ***", 1)
69 var mmodules = new ArraySet[MModule]
70 for a in modules do
71 var nmodule = self.load_module(a)
72 if nmodule == null then continue # Skip error
73 # Load imported module
74 build_module_importation(nmodule)
75
76 mmodules.add(nmodule.mmodule.as(not null))
77 end
78 var time1 = get_time
79 self.toolcontext.info("*** END PARSE: {time1-time0} ***", 2)
80
81 self.toolcontext.check_errors
82
83 if toolcontext.opt_only_parse.value then
84 self.toolcontext.info("*** ONLY PARSE...", 1)
85 exit(0)
86 end
87
88 return mmodules.to_a
89 end
90
91 # The list of directories to search for top level modules
92 # The list is initially set with :
93 # * the toolcontext --path option
94 # * the NIT_PATH environment variable
95 # * `toolcontext.nit_dir`
96 # Path can be added (or removed) by the client
97 var paths = new Array[String]
98
99 # Like (an used by) `get_mmodule_by_name` but just return the ModulePath
100 private fun search_mmodule_by_name(anode: nullable ANode, mgroup: nullable MGroup, name: String): nullable ModulePath
101 do
102 # First, look in groups
103 var c = mgroup
104 while c != null do
105 var dirname = c.filepath
106 if dirname == null then break # virtual group
107 if dirname.has_suffix(".nit") then break # singleton project
108
109 # Second, try the directory to find a file
110 var try_file = dirname + "/" + name + ".nit"
111 if try_file.file_exists then
112 var res = self.identify_file(try_file.simplify_path)
113 assert res != null
114 return res
115 end
116
117 # Third, try if the requested module is itself a group
118 try_file = dirname + "/" + name + "/" + name + ".nit"
119 if try_file.file_exists then
120 var res = self.identify_file(try_file.simplify_path)
121 assert res != null
122 return res
123 end
124
125 c = c.parent
126 end
127
128 # Look at some known directories
129 var lookpaths = self.paths
130
131 # Look in the directory of the group project also (even if not explicitely in the path)
132 if mgroup != null then
133 # path of the root group
134 var dirname = mgroup.mproject.root.filepath
135 if dirname != null then
136 dirname = dirname.join_path("..").simplify_path
137 if not lookpaths.has(dirname) and dirname.file_exists then
138 lookpaths = lookpaths.to_a
139 lookpaths.add(dirname)
140 end
141 end
142 end
143
144 var candidate = search_module_in_paths(anode.hot_location, name, lookpaths)
145
146 if candidate == null then
147 if mgroup != null then
148 error(anode, "Error: cannot find module {name} from {mgroup.name}. tried {lookpaths.join(", ")}")
149 else
150 error(anode, "Error: cannot find module {name}. tried {lookpaths.join(", ")}")
151 end
152 return null
153 end
154 return candidate
155 end
156
157 # Get a module by its short name; if required, the module is loaded, parsed and its hierarchies computed.
158 # If `mgroup` is set, then the module search starts from it up to the top level (see `paths`);
159 # if `mgroup` is null then the module is searched in the top level only.
160 # If no module exists or there is a name conflict, then an error on `anode` is displayed and null is returned.
161 fun get_mmodule_by_name(anode: nullable ANode, mgroup: nullable MGroup, name: String): nullable MModule
162 do
163 var path = search_mmodule_by_name(anode, mgroup, name)
164 if path == null then return null # Forward error
165 var res = self.load_module(path.filepath)
166 if res == null then return null # Forward error
167 # Load imported module
168 build_module_importation(res)
169 return res.mmodule.as(not null)
170 end
171
172 # Search a module `name` from path `lookpaths`.
173 # If found, the path of the file is returned
174 private fun search_module_in_paths(location: nullable Location, name: String, lookpaths: Collection[String]): nullable ModulePath
175 do
176 var candidate: nullable String = null
177 for dirname in lookpaths do
178 var try_file = (dirname + "/" + name + ".nit").simplify_path
179 if try_file.file_exists then
180 if candidate == null then
181 candidate = try_file
182 else if candidate != try_file then
183 # try to disambiguate conflicting modules
184 var abs_candidate = module_absolute_path(candidate)
185 var abs_try_file = module_absolute_path(try_file)
186 if abs_candidate != abs_try_file then
187 toolcontext.error(location, "Error: conflicting module file for {name}: {candidate} {try_file}")
188 end
189 end
190 end
191 try_file = (dirname + "/" + name + "/" + name + ".nit").simplify_path
192 if try_file.file_exists then
193 if candidate == null then
194 candidate = try_file
195 else if candidate != try_file then
196 # try to disambiguate conflicting modules
197 var abs_candidate = module_absolute_path(candidate)
198 var abs_try_file = module_absolute_path(try_file)
199 if abs_candidate != abs_try_file then
200 toolcontext.error(location, "Error: conflicting module file for {name}: {candidate} {try_file}")
201 end
202 end
203 end
204 end
205 if candidate == null then return null
206 return identify_file(candidate)
207 end
208
209 # cache for `identify_file` by realpath
210 private var identified_files = new HashMap[String, nullable ModulePath]
211
212 # Identify a source file
213 # Load the associated project and groups if required
214 #
215 # Silently return `null` if `path` is not a valid module path.
216 private fun identify_file(path: String): nullable ModulePath
217 do
218 # special case for not a nit file
219 if path.file_extension != "nit" then
220 # search dirless files in known -I paths
221 if path.dirname == "" then
222 var res = search_module_in_paths(null, path, self.paths)
223 if res != null then return res
224 end
225
226 # Found nothins? maybe it is a group...
227 var candidate = null
228 if path.file_exists then
229 var mgroup = get_mgroup(path)
230 if mgroup != null then
231 var owner_path = mgroup.filepath.join_path(mgroup.name + ".nit")
232 if owner_path.file_exists then candidate = owner_path
233 end
234 end
235
236 if candidate == null then
237 return null
238 end
239 path = candidate
240 end
241
242 # Fast track, the path is already known
243 var pn = path.basename(".nit")
244 var rp = module_absolute_path(path)
245 if identified_files.has_key(rp) then return identified_files[rp]
246
247 # Search for a group
248 var mgrouppath = path.join_path("..").simplify_path
249 var mgroup = get_mgroup(mgrouppath)
250
251 if mgroup == null then
252 # singleton project
253 var mproject = new MProject(pn, model)
254 mgroup = new MGroup(pn, mproject, null) # same name for the root group
255 mgroup.filepath = path
256 mproject.root = mgroup
257 toolcontext.info("found project `{pn}` at {path}", 2)
258 end
259
260 var res = new ModulePath(pn, path, mgroup)
261 mgroup.module_paths.add(res)
262
263 identified_files[rp] = res
264 return res
265 end
266
267 # groups by path
268 private var mgroups = new HashMap[String, nullable MGroup]
269
270 # return the mgroup associated to a directory path
271 # if the directory is not a group null is returned
272 private fun get_mgroup(dirpath: String): nullable MGroup
273 do
274 var rdp = module_absolute_path(dirpath)
275 if mgroups.has_key(rdp) then
276 return mgroups[rdp]
277 end
278
279 # Hack, a group is determined by:
280 # * the presence of a honomymous nit file
281 # * the fact that the directory is named `src`
282 var pn = rdp.basename(".nit")
283 var mp = dirpath.join_path(pn + ".nit").simplify_path
284
285 var dirpath2 = dirpath
286 if not mp.file_exists then
287 if pn == "src" then
288 # With a src directory, the group name is the name of the parent directory
289 dirpath2 = rdp.dirname
290 pn = dirpath2.basename("")
291 else
292 return null
293 end
294 end
295
296 # check parent directory
297 var parentpath = dirpath.join_path("..").simplify_path
298 var parent = get_mgroup(parentpath)
299
300 var mgroup
301 if parent == null then
302 # no parent, thus new project
303 var mproject = new MProject(pn, model)
304 mgroup = new MGroup(pn, mproject, null) # same name for the root group
305 mproject.root = mgroup
306 toolcontext.info("found project `{mproject}` at {dirpath}", 2)
307 else
308 mgroup = new MGroup(pn, parent.mproject, parent)
309 toolcontext.info("found sub group `{mgroup.full_name}` at {dirpath}", 2)
310 end
311 var readme = dirpath2.join_path("README.md")
312 if not readme.file_exists then readme = dirpath2.join_path("README")
313 if readme.file_exists then
314 var mdoc = new MDoc
315 var s = new IFStream.open(readme)
316 while not s.eof do
317 mdoc.content.add(s.read_line)
318 end
319 mgroup.mdoc = mdoc
320 mdoc.original_mentity = mgroup
321 end
322 mgroup.filepath = dirpath
323 mgroups[rdp] = mgroup
324 return mgroup
325 end
326
327 # Force the identification of all ModulePath of the group and sub-groups.
328 fun visit_group(mgroup: MGroup) do
329 var p = mgroup.filepath
330 for f in p.files do
331 var fp = p/f
332 var g = get_mgroup(fp)
333 if g != null then visit_group(g)
334 identify_file(fp)
335 end
336 end
337
338 # Transform relative paths (starting with '../') into absolute paths
339 private fun module_absolute_path(path: String): String do
340 return getcwd.join_path(path).simplify_path
341 end
342
343 # Try to load a module AST using a path.
344 # Display an error if there is a problem (IO / lexer / parser) and return null
345 fun load_module_ast(filename: String): nullable AModule
346 do
347 if filename.file_extension != "nit" then
348 self.toolcontext.error(null, "Error: file {filename} is not a valid nit module.")
349 return null
350 end
351 if not filename.file_exists then
352 self.toolcontext.error(null, "Error: file {filename} not found.")
353 return null
354 end
355
356 self.toolcontext.info("load module {filename}", 2)
357
358 # Load the file
359 var file = new IFStream.open(filename)
360 var lexer = new Lexer(new SourceFile(filename, file))
361 var parser = new Parser(lexer)
362 var tree = parser.parse
363 file.close
364
365 # Handle lexer and parser error
366 var nmodule = tree.n_base
367 if nmodule == null then
368 var neof = tree.n_eof
369 assert neof isa AError
370 error(neof, neof.message)
371 return null
372 end
373
374 return nmodule
375 end
376
377 # Try to load a module modules using a path.
378 # Display an error if there is a problem (IO / lexer / parser) and return null.
379 # Note: usually, you do not need this method, use `get_mmodule_by_name` instead.
380 #
381 # The MModule is created however, the importation is not performed,
382 # therefore you should call `build_module_importation`.
383 fun load_module(filename: String): nullable AModule
384 do
385 # Look for the module
386 var file = identify_file(filename)
387 if file == null then
388 toolcontext.error(null, "Error: cannot find module `{filename}`.")
389 return null
390 end
391
392 # Already known and loaded? then return it
393 var mmodule = file.mmodule
394 if mmodule != null then
395 return mmodule2nmodule[mmodule]
396 end
397
398 # Load it manually
399 var nmodule = load_module_ast(file.filepath)
400 if nmodule == null then return null # forward error
401
402 # build the mmodule and load imported modules
403 mmodule = build_a_mmodule(file.mgroup, file.name, nmodule)
404
405 if mmodule == null then return null # forward error
406
407 # Update the file information
408 file.mmodule = mmodule
409
410 return nmodule
411 end
412
413 # Injection of a new module without source.
414 # Used by the interpreted
415 fun load_rt_module(parent: nullable MModule, nmodule: AModule, mod_name: String): nullable AModule
416 do
417 # Create the module
418
419 var mgroup = null
420 if parent != null then mgroup = parent.mgroup
421 var mmodule = new MModule(model, mgroup, mod_name, nmodule.location)
422 nmodule.mmodule = mmodule
423 nmodules.add(nmodule)
424 self.mmodule2nmodule[mmodule] = nmodule
425
426 if parent!= null then
427 var imported_modules = new Array[MModule]
428 imported_modules.add(parent)
429 mmodule.set_visibility_for(parent, intrude_visibility)
430 mmodule.set_imported_mmodules(imported_modules)
431 else
432 build_module_importation(nmodule)
433 end
434
435 return nmodule
436 end
437
438 # Visit the AST and create the `MModule` object
439 private fun build_a_mmodule(mgroup: nullable MGroup, mod_name: String, nmodule: AModule): nullable MModule
440 do
441 # Check the module name
442 var decl = nmodule.n_moduledecl
443 if decl == null then
444 #warning(nmodule, "Warning: Missing 'module' keyword") #FIXME: NOT YET FOR COMPATIBILITY
445 else
446 var decl_name = decl.n_name.n_id.text
447 if decl_name != mod_name then
448 error(decl.n_name, "Error: module name missmatch; declared {decl_name} file named {mod_name}")
449 end
450 end
451
452 # Create the module
453 var mmodule = new MModule(model, mgroup, mod_name, nmodule.location)
454 nmodule.mmodule = mmodule
455 nmodules.add(nmodule)
456 self.mmodule2nmodule[mmodule] = nmodule
457
458 if decl != null then
459 var ndoc = decl.n_doc
460 if ndoc != null then
461 var mdoc = ndoc.to_mdoc
462 mmodule.mdoc = mdoc
463 mdoc.original_mentity = mmodule
464 else
465 advice(decl, "missing-doc", "Documentation warning: Undocumented module `{mmodule}`")
466 end
467 end
468
469 return mmodule
470 end
471
472 # Analysis the module importation and fill the module_importation_hierarchy
473 #
474 # Unless you used `load_module`, the importation is already done and this method does a no-op.
475 fun build_module_importation(nmodule: AModule)
476 do
477 if nmodule.is_importation_done then return
478 nmodule.is_importation_done = true
479 var mmodule = nmodule.mmodule.as(not null)
480 var stdimport = true
481 var imported_modules = new Array[MModule]
482 for aimport in nmodule.n_imports do
483 stdimport = false
484 if not aimport isa AStdImport then
485 continue
486 end
487 var mgroup = mmodule.mgroup
488 if aimport.n_name.n_quad != null then mgroup = null # Start from top level
489 for grp in aimport.n_name.n_path do
490 var path = search_mmodule_by_name(grp, mgroup, grp.text)
491 if path == null then return # Skip error
492 mgroup = path.mgroup
493 end
494 var mod_name = aimport.n_name.n_id.text
495 var sup = self.get_mmodule_by_name(aimport.n_name, mgroup, mod_name)
496 if sup == null then continue # Skip error
497 aimport.mmodule = sup
498 imported_modules.add(sup)
499 var mvisibility = aimport.n_visibility.mvisibility
500 if mvisibility == protected_visibility then
501 error(aimport.n_visibility, "Error: only properties can be protected.")
502 return
503 end
504 if sup == mmodule then
505 error(aimport.n_name, "Error: Dependency loop in module {mmodule}.")
506 end
507 if sup.in_importation < mmodule then
508 error(aimport.n_name, "Error: Dependency loop between modules {mmodule} and {sup}.")
509 return
510 end
511 mmodule.set_visibility_for(sup, mvisibility)
512 end
513 if stdimport then
514 var mod_name = "standard"
515 var sup = self.get_mmodule_by_name(nmodule, null, mod_name)
516 if sup != null then # Skip error
517 imported_modules.add(sup)
518 mmodule.set_visibility_for(sup, public_visibility)
519 end
520 end
521 self.toolcontext.info("{mmodule} imports {imported_modules.join(", ")}", 3)
522 mmodule.set_imported_mmodules(imported_modules)
523
524 # Force standard to be public if imported
525 for sup in mmodule.in_importation.greaters do
526 if sup.name == "standard" then
527 mmodule.set_visibility_for(sup, public_visibility)
528 end
529 end
530
531 # TODO: Correctly check for useless importation
532 # It is even doable?
533 var directs = mmodule.in_importation.direct_greaters
534 for nim in nmodule.n_imports do
535 if not nim isa AStdImport then continue
536 var im = nim.mmodule
537 if im == null then continue
538 if directs.has(im) then continue
539 # This generates so much noise that it is simpler to just comment it
540 #warning(nim, "Warning: possible useless importation of {im}")
541 end
542 end
543
544 # All the loaded modules
545 var nmodules = new Array[AModule]
546
547 # Register the nmodule associated to each mmodule
548 # FIXME: why not refine the `MModule` class with a nullable attribute?
549 var mmodule2nmodule = new HashMap[MModule, AModule]
550 end
551
552 # placeholder to a module file identified but not always loaded in a project
553 private class ModulePath
554 # The name of the module
555 # (it's the basename of the filepath)
556 var name: String
557
558 # The human path of the module
559 var filepath: String
560
561 # The group (and the project) of the possible module
562 var mgroup: MGroup
563
564 # The loaded module (if any)
565 var mmodule: nullable MModule = null
566
567 redef fun to_s do return filepath
568 end
569
570 redef class MGroup
571 # modules paths associated with the group
572 private var module_paths = new Array[ModulePath]
573
574 # Is the group interesting for a final user?
575 #
576 # groups are mandatory in the model but for simple projects they are not
577 # always interesting.
578 #
579 # A interesting group has, at least, one of the following true:
580 #
581 # * it has 2 modules or more
582 # * it has a subgroup
583 # * it has a documentation
584 fun is_interesting: Bool
585 do
586 return module_paths.length > 1 or mmodules.length > 1 or not in_nesting.direct_smallers.is_empty or mdoc != null
587 end
588
589 end
590
591 redef class AStdImport
592 # The imported module once determined
593 var mmodule: nullable MModule = null
594 end
595
596 redef class AModule
597 # The associated MModule once build by a `ModelBuilder`
598 var mmodule: nullable MModule
599 # Flag that indicate if the importation is already completed
600 var is_importation_done: Bool = false
601 end