1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2012 Jean Privat <jean@pryen.org>
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 # Loading of Nit source files
20 import modelbuilder_base
22 redef class ToolContext
24 var opt_path
= new OptionArray("Set include path for loaders (may be used more than once)", "-I", "--path")
26 # Option --only-metamodel
27 var opt_only_metamodel
= new OptionBool("Stop after meta-model processing", "--only-metamodel")
30 var opt_only_parse
= new OptionBool("Only proceed to parse step of loaders", "--only-parse")
35 option_context
.add_option
(opt_path
, opt_only_parse
, opt_only_metamodel
)
39 redef class ModelBuilder
44 # Setup the paths value
45 paths
.append
(toolcontext
.opt_path
.value
)
47 var path_env
= "NIT_PATH".environ
48 if not path_env
.is_empty
then
49 paths
.append
(path_env
.split_with
(':'))
52 var nit_dir
= toolcontext
.nit_dir
53 var libname
= "{nit_dir}/lib"
54 if libname
.file_exists
then paths
.add
(libname
)
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.
63 # Note: class and property model elements are not analysed.
64 fun parse
(modules
: Sequence[String]): Array[MModule]
67 # Parse and recursively load
68 self.toolcontext
.info
("*** PARSE ***", 1)
69 var mmodules
= new ArraySet[MModule]
71 var nmodule
= self.load_module
(a
)
72 if nmodule
== null then continue # Skip error
73 # Load imported module
74 build_module_importation
(nmodule
)
76 mmodules
.add
(nmodule
.mmodule
.as(not null))
79 self.toolcontext
.info
("*** END PARSE: {time1-time0} ***", 2)
81 self.toolcontext
.check_errors
83 if toolcontext
.opt_only_parse
.value
then
84 self.toolcontext
.info
("*** ONLY PARSE...", 1)
91 # Load recursively all modules of the group `mgroup`.
92 # See `parse` for details.
93 fun parse_group
(mgroup
: MGroup): Array[MModule]
95 var res
= new Array[MModule]
97 for mg
in mgroup
.in_nesting
.smallers
do
98 for mp
in mg
.module_paths
do
99 var nmodule
= self.load_module
(mp
.filepath
)
100 if nmodule
== null then continue # Skip error
101 # Load imported module
102 build_module_importation
(nmodule
)
104 res
.add
(nmodule
.mmodule
.as(not null))
110 # Load a bunch of modules and groups.
111 # Each name can be a module or a group.
112 # If it is a group then recursively all its modules are parsed.
113 # See `parse` for details.
114 fun parse_full
(names
: Sequence[String]): Array[MModule]
117 # Parse and recursively load
118 self.toolcontext
.info
("*** PARSE ***", 1)
119 var mmodules
= new ArraySet[MModule]
121 var mgroup
= self.get_mgroup
(a
)
122 if mgroup
!= null then
123 mmodules
.add_all parse_group
(mgroup
)
126 var nmodule
= self.load_module
(a
)
127 if nmodule
== null then continue # Skip error
128 # Load imported module
129 build_module_importation
(nmodule
)
131 mmodules
.add
(nmodule
.mmodule
.as(not null))
134 self.toolcontext
.info
("*** END PARSE: {time1-time0} ***", 2)
136 self.toolcontext
.check_errors
138 if toolcontext
.opt_only_parse
.value
then
139 self.toolcontext
.info
("*** ONLY PARSE...", 1)
146 # The list of directories to search for top level modules
147 # The list is initially set with:
149 # * the toolcontext --path option
150 # * the NIT_PATH environment variable
151 # * `toolcontext.nit_dir`
152 # Path can be added (or removed) by the client
153 var paths
= new Array[String]
155 # Like (and used by) `get_mmodule_by_name` but just return the ModulePath
156 fun search_mmodule_by_name
(anode
: nullable ANode, mgroup
: nullable MGroup, name
: String): nullable ModulePath
158 # First, look in groups
161 var dirname
= c
.filepath
162 if dirname
== null then break # virtual group
163 if dirname
.has_suffix
(".nit") then break # singleton project
165 # Second, try the directory to find a file
166 var try_file
= dirname
+ "/" + name
+ ".nit"
167 if try_file
.file_exists
then
168 var res
= self.identify_file
(try_file
.simplify_path
)
173 # Third, try if the requested module is itself a group
174 try_file
= dirname
+ "/" + name
+ "/" + name
+ ".nit"
175 if try_file
.file_exists
then
176 var res
= self.identify_file
(try_file
.simplify_path
)
184 # Look at some known directories
185 var lookpaths
= self.paths
187 # Look in the directory of the group project also (even if not explicitly in the path)
188 if mgroup
!= null then
189 # path of the root group
190 var dirname
= mgroup
.mproject
.root
.filepath
191 if dirname
!= null then
192 dirname
= dirname
.join_path
("..").simplify_path
193 if not lookpaths
.has
(dirname
) and dirname
.file_exists
then
194 lookpaths
= lookpaths
.to_a
195 lookpaths
.add
(dirname
)
200 var candidate
= search_module_in_paths
(anode
.hot_location
, name
, lookpaths
)
202 if candidate
== null then
203 if mgroup
!= null then
204 error
(anode
, "Error: cannot find module {name} from {mgroup.name}. tried {lookpaths.join(", ")}")
206 error
(anode
, "Error: cannot find module {name}. tried {lookpaths.join(", ")}")
213 # Get a module by its short name; if required, the module is loaded, parsed and its hierarchies computed.
214 # If `mgroup` is set, then the module search starts from it up to the top level (see `paths`);
215 # if `mgroup` is null then the module is searched in the top level only.
216 # If no module exists or there is a name conflict, then an error on `anode` is displayed and null is returned.
217 fun get_mmodule_by_name
(anode
: nullable ANode, mgroup
: nullable MGroup, name
: String): nullable MModule
219 var path
= search_mmodule_by_name
(anode
, mgroup
, name
)
220 if path
== null then return null # Forward error
221 var res
= self.load_module
(path
.filepath
)
222 if res
== null then return null # Forward error
223 # Load imported module
224 build_module_importation
(res
)
225 return res
.mmodule
.as(not null)
228 # Search a module `name` from path `lookpaths`.
229 # If found, the path of the file is returned
230 private fun search_module_in_paths
(location
: nullable Location, name
: String, lookpaths
: Collection[String]): nullable ModulePath
232 var candidate
: nullable String = null
233 for dirname
in lookpaths
do
234 var try_file
= (dirname
+ "/" + name
+ ".nit").simplify_path
235 if try_file
.file_exists
then
236 if candidate
== null then
238 else if candidate
!= try_file
then
239 # try to disambiguate conflicting modules
240 var abs_candidate
= module_absolute_path
(candidate
)
241 var abs_try_file
= module_absolute_path
(try_file
)
242 if abs_candidate
!= abs_try_file
then
243 toolcontext
.error
(location
, "Error: conflicting module file for {name}: {candidate} {try_file}")
247 try_file
= (dirname
+ "/" + name
+ "/" + name
+ ".nit").simplify_path
248 if try_file
.file_exists
then
249 if candidate
== null then
251 else if candidate
!= try_file
then
252 # try to disambiguate conflicting modules
253 var abs_candidate
= module_absolute_path
(candidate
)
254 var abs_try_file
= module_absolute_path
(try_file
)
255 if abs_candidate
!= abs_try_file
then
256 toolcontext
.error
(location
, "Error: conflicting module file for {name}: {candidate} {try_file}")
261 if candidate
== null then return null
262 return identify_file
(candidate
)
265 # Cache for `identify_file` by realpath
266 private var identified_files_by_path
= new HashMap[String, nullable ModulePath]
268 # All the currently identified modules.
269 # See `identify_file`.
270 var identified_files
= new Array[ModulePath]
272 # Identify a source file
273 # Load the associated project and groups if required
275 # Silently return `null` if `path` is not a valid module path.
276 fun identify_file
(path
: String): nullable ModulePath
278 # special case for not a nit file
279 if path
.file_extension
!= "nit" then
280 # search dirless files in known -I paths
281 if path
.dirname
== "" then
282 var res
= search_module_in_paths
(null, path
, self.paths
)
283 if res
!= null then return res
286 # Found nothing? maybe it is a group...
288 if path
.file_exists
then
289 var mgroup
= get_mgroup
(path
)
290 if mgroup
!= null then
291 var owner_path
= mgroup
.filepath
.join_path
(mgroup
.name
+ ".nit")
292 if owner_path
.file_exists
then candidate
= owner_path
296 if candidate
== null then
302 # Fast track, the path is already known
303 var pn
= path
.basename
(".nit")
304 var rp
= module_absolute_path
(path
)
305 if identified_files_by_path
.has_key
(rp
) then return identified_files_by_path
[rp
]
308 var mgrouppath
= path
.join_path
("..").simplify_path
309 var mgroup
= get_mgroup
(mgrouppath
)
311 if mgroup
== null then
313 var mproject
= new MProject(pn
, model
)
314 mgroup
= new MGroup(pn
, mproject
, null) # same name for the root group
315 mgroup
.filepath
= path
316 mproject
.root
= mgroup
317 toolcontext
.info
("found project `{pn}` at {path}", 2)
320 var res
= new ModulePath(pn
, path
, mgroup
)
321 mgroup
.module_paths
.add
(res
)
323 identified_files_by_path
[rp
] = res
324 identified_files
.add
(res
)
329 private var mgroups
= new HashMap[String, nullable MGroup]
331 # Return the mgroup associated to a directory path.
332 # If the directory is not a group null is returned.
333 fun get_mgroup
(dirpath
: String): nullable MGroup
335 var rdp
= module_absolute_path
(dirpath
)
336 if mgroups
.has_key
(rdp
) then
340 # Hack, a group is determined by:
341 # * the presence of a honomymous nit file
342 # * the fact that the directory is named `src`
343 var pn
= rdp
.basename
(".nit")
344 var mp
= dirpath
.join_path
(pn
+ ".nit").simplify_path
346 var dirpath2
= dirpath
347 if not mp
.file_exists
then
349 # With a src directory, the group name is the name of the parent directory
350 dirpath2
= rdp
.dirname
351 pn
= dirpath2
.basename
("")
357 # check parent directory
358 var parentpath
= dirpath
.join_path
("..").simplify_path
359 var parent
= get_mgroup
(parentpath
)
362 if parent
== null then
363 # no parent, thus new project
364 var mproject
= new MProject(pn
, model
)
365 mgroup
= new MGroup(pn
, mproject
, null) # same name for the root group
366 mproject
.root
= mgroup
367 toolcontext
.info
("found project `{mproject}` at {dirpath}", 2)
369 mgroup
= new MGroup(pn
, parent
.mproject
, parent
)
370 toolcontext
.info
("found sub group `{mgroup.full_name}` at {dirpath}", 2)
372 var readme
= dirpath2
.join_path
("README.md")
373 if not readme
.file_exists
then readme
= dirpath2
.join_path
("README")
374 if readme
.file_exists
then
376 var s
= new IFStream.open
(readme
)
378 mdoc
.content
.add
(s
.read_line
)
381 mdoc
.original_mentity
= mgroup
383 mgroup
.filepath
= dirpath
384 mgroups
[rdp
] = mgroup
388 # Force the identification of all ModulePath of the group and sub-groups.
389 fun visit_group
(mgroup
: MGroup) do
390 var p
= mgroup
.filepath
393 var g
= get_mgroup
(fp
)
394 if g
!= null then visit_group
(g
)
399 # Transform relative paths (starting with '../') into absolute paths
400 private fun module_absolute_path
(path
: String): String do
401 return getcwd
.join_path
(path
).simplify_path
404 # Try to load a module AST using a path.
405 # Display an error if there is a problem (IO / lexer / parser) and return null
406 fun load_module_ast
(filename
: String): nullable AModule
408 if filename
.file_extension
!= "nit" then
409 self.toolcontext
.error
(null, "Error: file {filename} is not a valid nit module.")
412 if not filename
.file_exists
then
413 self.toolcontext
.error
(null, "Error: file {filename} not found.")
417 self.toolcontext
.info
("load module {filename}", 2)
420 var file
= new IFStream.open
(filename
)
421 var lexer
= new Lexer(new SourceFile(filename
, file
))
422 var parser
= new Parser(lexer
)
423 var tree
= parser
.parse
426 # Handle lexer and parser error
427 var nmodule
= tree
.n_base
428 if nmodule
== null then
429 var neof
= tree
.n_eof
430 assert neof
isa AError
431 error
(neof
, neof
.message
)
438 # Try to load a module using a path.
439 # Display an error if there is a problem (IO / lexer / parser) and return null.
440 # Note: usually, you do not need this method, use `get_mmodule_by_name` instead.
442 # The MModule is created however, the importation is not performed,
443 # therefore you should call `build_module_importation`.
444 fun load_module
(filename
: String): nullable AModule
446 # Look for the module
447 var file
= identify_file
(filename
)
449 toolcontext
.error
(null, "Error: cannot find module `{filename}`.")
453 # Already known and loaded? then return it
454 var mmodule
= file
.mmodule
455 if mmodule
!= null then
456 return mmodule2nmodule
[mmodule
]
460 var nmodule
= load_module_ast
(file
.filepath
)
461 if nmodule
== null then return null # forward error
463 # build the mmodule and load imported modules
464 mmodule
= build_a_mmodule
(file
.mgroup
, file
.name
, nmodule
)
466 if mmodule
== null then return null # forward error
468 # Update the file information
469 file
.mmodule
= mmodule
474 # Injection of a new module without source.
475 # Used by the interpreter.
476 fun load_rt_module
(parent
: nullable MModule, nmodule
: AModule, mod_name
: String): nullable AModule
481 if parent
!= null then mgroup
= parent
.mgroup
482 var mmodule
= new MModule(model
, mgroup
, mod_name
, nmodule
.location
)
483 nmodule
.mmodule
= mmodule
484 nmodules
.add
(nmodule
)
485 self.mmodule2nmodule
[mmodule
] = nmodule
487 if parent
!= null then
488 var imported_modules
= new Array[MModule]
489 imported_modules
.add
(parent
)
490 mmodule
.set_visibility_for
(parent
, intrude_visibility
)
491 mmodule
.set_imported_mmodules
(imported_modules
)
493 build_module_importation
(nmodule
)
499 # Visit the AST and create the `MModule` object
500 private fun build_a_mmodule
(mgroup
: nullable MGroup, mod_name
: String, nmodule
: AModule): nullable MModule
502 # Check the module name
503 var decl
= nmodule
.n_moduledecl
505 var decl_name
= decl
.n_name
.n_id
.text
506 if decl_name
!= mod_name
then
507 error
(decl
.n_name
, "Error: module name missmatch; declared {decl_name} file named {mod_name}")
511 # Check for conflicting module names in the project
512 if mgroup
!= null then
513 var others
= model
.get_mmodules_by_name
(mod_name
)
514 if others
!= null then for other
in others
do
515 if other
.mgroup
!= null and other
.mgroup
.mproject
== mgroup
.mproject
then
517 if decl
== null then node
= nmodule
else node
= decl
.n_name
518 error
(node
, "Error: A module named `{other.full_name}` already exists at {other.location}")
525 var mmodule
= new MModule(model
, mgroup
, mod_name
, nmodule
.location
)
526 nmodule
.mmodule
= mmodule
527 nmodules
.add
(nmodule
)
528 self.mmodule2nmodule
[mmodule
] = nmodule
531 var ndoc
= decl
.n_doc
533 var mdoc
= ndoc
.to_mdoc
535 mdoc
.original_mentity
= mmodule
537 advice
(decl
, "missing-doc", "Documentation warning: Undocumented module `{mmodule}`")
544 # Analyze the module importation and fill the module_importation_hierarchy
546 # Unless you used `load_module`, the importation is already done and this method does a no-op.
547 fun build_module_importation
(nmodule
: AModule)
549 if nmodule
.is_importation_done
then return
550 nmodule
.is_importation_done
= true
551 var mmodule
= nmodule
.mmodule
.as(not null)
553 var imported_modules
= new Array[MModule]
554 for aimport
in nmodule
.n_imports
do
556 if not aimport
isa AStdImport then
559 var mgroup
= mmodule
.mgroup
560 if aimport
.n_name
.n_quad
!= null then mgroup
= null # Start from top level
561 for grp
in aimport
.n_name
.n_path
do
562 var path
= search_mmodule_by_name
(grp
, mgroup
, grp
.text
)
563 if path
== null then return # Skip error
566 var mod_name
= aimport
.n_name
.n_id
.text
567 var sup
= self.get_mmodule_by_name
(aimport
.n_name
, mgroup
, mod_name
)
568 if sup
== null then continue # Skip error
569 aimport
.mmodule
= sup
570 imported_modules
.add
(sup
)
571 var mvisibility
= aimport
.n_visibility
.mvisibility
572 if mvisibility
== protected_visibility
then
573 error
(aimport
.n_visibility
, "Error: only properties can be protected.")
576 if sup
== mmodule
then
577 error
(aimport
.n_name
, "Error: Dependency loop in module {mmodule}.")
579 if sup
.in_importation
< mmodule
then
580 error
(aimport
.n_name
, "Error: Dependency loop between modules {mmodule} and {sup}.")
583 mmodule
.set_visibility_for
(sup
, mvisibility
)
586 var mod_name
= "standard"
587 var sup
= self.get_mmodule_by_name
(nmodule
, null, mod_name
)
588 if sup
!= null then # Skip error
589 imported_modules
.add
(sup
)
590 mmodule
.set_visibility_for
(sup
, public_visibility
)
593 self.toolcontext
.info
("{mmodule} imports {imported_modules.join(", ")}", 3)
594 mmodule
.set_imported_mmodules
(imported_modules
)
596 # Force standard to be public if imported
597 for sup
in mmodule
.in_importation
.greaters
do
598 if sup
.name
== "standard" then
599 mmodule
.set_visibility_for
(sup
, public_visibility
)
603 # TODO: Correctly check for useless importation
605 var directs
= mmodule
.in_importation
.direct_greaters
606 for nim
in nmodule
.n_imports
do
607 if not nim
isa AStdImport then continue
609 if im
== null then continue
610 if directs
.has
(im
) then continue
611 # This generates so much noise that it is simpler to just comment it
612 #warning(nim, "Warning: possible useless importation of {im}")
616 # All the loaded modules
617 var nmodules
= new Array[AModule]
619 # Register the nmodule associated to each mmodule
621 # Public clients need to use `mmodule2node` to access stuff.
622 private var mmodule2nmodule
= new HashMap[MModule, AModule]
624 # Retrieve the associated AST node of a mmodule.
625 # This method is used to associate model entity with syntactic entities.
627 # If the module is not associated with a node, returns null.
628 fun mmodule2node
(mmodule
: MModule): nullable AModule
630 return mmodule2nmodule
.get_or_null
(mmodule
)
634 # File-system location of a module (file) that is identified but not always loaded.
636 # The name of the module
637 # (it's the basename of the filepath)
640 # The human path of the module
643 # The group (and the project) of the possible module
646 # The loaded module (if any)
647 var mmodule
: nullable MModule = null
649 redef fun to_s
do return filepath
653 # Modules paths associated with the group
654 var module_paths
= new Array[ModulePath]
656 # Is the group interesting for a final user?
658 # Groups are mandatory in the model but for simple projects they are not
659 # always interesting.
661 # A interesting group has, at least, one of the following true:
663 # * it has 2 modules or more
664 # * it has a subgroup
665 # * it has a documentation
666 fun is_interesting
: Bool
668 return module_paths
.length
> 1 or mmodules
.length
> 1 or not in_nesting
.direct_smallers
.is_empty
or mdoc
!= null
673 redef class AStdImport
674 # The imported module once determined
675 var mmodule
: nullable MModule = null
679 # The associated MModule once build by a `ModelBuilder`
680 var mmodule
: nullable MModule
681 # Flag that indicate if the importation is already completed
682 var is_importation_done
: Bool = false