9d1297bbca4f499a2f324d45507c1b74cee4ed20
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.
114 # * a path to a module, a group or a directory of projects.
115 # * a short name of a module or a group that are looked in the `paths` (-I)
117 # Then, for each entry, if it is:
119 # * a module, then is it parser and returned.
120 # * a group then recursively all its modules are parsed.
121 # * a directory of projects then all the modules of all projects are parsed.
122 # * else an error is displayed.
124 # See `parse` for details.
125 fun parse_full
(names
: Sequence[String]): Array[MModule]
128 # Parse and recursively load
129 self.toolcontext
.info
("*** PARSE ***", 1)
130 var mmodules
= new ArraySet[MModule]
133 var mgroup
= self.get_mgroup
(a
)
134 if mgroup
!= null then
135 mmodules
.add_all parse_group
(mgroup
)
139 # Case of a directory that is not a group
140 var stat
= a
.to_path
.stat
141 if stat
!= null and stat
.is_dir
then
142 self.toolcontext
.info
("look in directory {a}", 2)
144 # Try each entry as a group or a module
147 mgroup
= get_mgroup
(af
)
148 if mgroup
!= null then
149 mmodules
.add_all parse_group
(mgroup
)
152 var mp
= identify_file
(af
)
154 var nmodule
= self.load_module
(af
)
155 if nmodule
== null then continue # Skip error
156 build_module_importation
(nmodule
)
157 mmodules
.add
(nmodule
.mmodule
.as(not null))
159 self.toolcontext
.info
("ignore file {af}", 2)
165 var nmodule
= self.load_module
(a
)
166 if nmodule
== null then continue # Skip error
167 # Load imported module
168 build_module_importation
(nmodule
)
170 mmodules
.add
(nmodule
.mmodule
.as(not null))
173 self.toolcontext
.info
("*** END PARSE: {time1-time0} ***", 2)
175 self.toolcontext
.check_errors
177 if toolcontext
.opt_only_parse
.value
then
178 self.toolcontext
.info
("*** ONLY PARSE...", 1)
185 # The list of directories to search for top level modules
186 # The list is initially set with:
188 # * the toolcontext --path option
189 # * the NIT_PATH environment variable
190 # * `toolcontext.nit_dir`
191 # Path can be added (or removed) by the client
192 var paths
= new Array[String]
194 # Like (and used by) `get_mmodule_by_name` but just return the ModulePath
195 fun search_mmodule_by_name
(anode
: nullable ANode, mgroup
: nullable MGroup, name
: String): nullable ModulePath
197 # First, look in groups
200 var dirname
= c
.filepath
201 if dirname
== null then break # virtual group
202 if dirname
.has_suffix
(".nit") then break # singleton project
204 # Second, try the directory to find a file
205 var try_file
= dirname
+ "/" + name
+ ".nit"
206 if try_file
.file_exists
then
207 var res
= self.identify_file
(try_file
.simplify_path
)
212 # Third, try if the requested module is itself a group
213 try_file
= dirname
+ "/" + name
+ "/" + name
+ ".nit"
214 if try_file
.file_exists
then
215 var res
= self.identify_file
(try_file
.simplify_path
)
223 # Look at some known directories
224 var lookpaths
= self.paths
226 # Look in the directory of the group project also (even if not explicitly in the path)
227 if mgroup
!= null then
228 # path of the root group
229 var dirname
= mgroup
.mproject
.root
.filepath
230 if dirname
!= null then
231 dirname
= dirname
.join_path
("..").simplify_path
232 if not lookpaths
.has
(dirname
) and dirname
.file_exists
then
233 lookpaths
= lookpaths
.to_a
234 lookpaths
.add
(dirname
)
239 var candidate
= search_module_in_paths
(anode
.hot_location
, name
, lookpaths
)
241 if candidate
== null then
242 if mgroup
!= null then
243 error
(anode
, "Error: cannot find module {name} from {mgroup.name}. tried {lookpaths.join(", ")}")
245 error
(anode
, "Error: cannot find module {name}. tried {lookpaths.join(", ")}")
252 # Get a module by its short name; if required, the module is loaded, parsed and its hierarchies computed.
253 # If `mgroup` is set, then the module search starts from it up to the top level (see `paths`);
254 # if `mgroup` is null then the module is searched in the top level only.
255 # If no module exists or there is a name conflict, then an error on `anode` is displayed and null is returned.
256 fun get_mmodule_by_name
(anode
: nullable ANode, mgroup
: nullable MGroup, name
: String): nullable MModule
258 var path
= search_mmodule_by_name
(anode
, mgroup
, name
)
259 if path
== null then return null # Forward error
260 var res
= self.load_module
(path
.filepath
)
261 if res
== null then return null # Forward error
262 # Load imported module
263 build_module_importation
(res
)
264 return res
.mmodule
.as(not null)
267 # Search a module `name` from path `lookpaths`.
268 # If found, the path of the file is returned
269 private fun search_module_in_paths
(location
: nullable Location, name
: String, lookpaths
: Collection[String]): nullable ModulePath
271 var candidate
: nullable String = null
272 for dirname
in lookpaths
do
273 var try_file
= (dirname
+ "/" + name
+ ".nit").simplify_path
274 if try_file
.file_exists
then
275 if candidate
== null then
277 else if candidate
!= try_file
then
278 # try to disambiguate conflicting modules
279 var abs_candidate
= module_absolute_path
(candidate
)
280 var abs_try_file
= module_absolute_path
(try_file
)
281 if abs_candidate
!= abs_try_file
then
282 toolcontext
.error
(location
, "Error: conflicting module file for {name}: {candidate} {try_file}")
286 try_file
= (dirname
+ "/" + name
+ "/" + name
+ ".nit").simplify_path
287 if try_file
.file_exists
then
288 if candidate
== null then
290 else if candidate
!= try_file
then
291 # try to disambiguate conflicting modules
292 var abs_candidate
= module_absolute_path
(candidate
)
293 var abs_try_file
= module_absolute_path
(try_file
)
294 if abs_candidate
!= abs_try_file
then
295 toolcontext
.error
(location
, "Error: conflicting module file for {name}: {candidate} {try_file}")
300 if candidate
== null then return null
301 return identify_file
(candidate
)
304 # Cache for `identify_file` by realpath
305 private var identified_files_by_path
= new HashMap[String, nullable ModulePath]
307 # All the currently identified modules.
308 # See `identify_file`.
309 var identified_files
= new Array[ModulePath]
311 # Identify a source file
312 # Load the associated project and groups if required
314 # Silently return `null` if `path` is not a valid module path.
315 fun identify_file
(path
: String): nullable ModulePath
317 # special case for not a nit file
318 if path
.file_extension
!= "nit" then
319 # search dirless files in known -I paths
320 if path
.dirname
== "" then
321 var res
= search_module_in_paths
(null, path
, self.paths
)
322 if res
!= null then return res
325 # Found nothing? maybe it is a group...
327 if path
.file_exists
then
328 var mgroup
= get_mgroup
(path
)
329 if mgroup
!= null then
330 var owner_path
= mgroup
.filepath
.join_path
(mgroup
.name
+ ".nit")
331 if owner_path
.file_exists
then candidate
= owner_path
335 if candidate
== null then
341 # Fast track, the path is already known
342 var pn
= path
.basename
(".nit")
343 var rp
= module_absolute_path
(path
)
344 if identified_files_by_path
.has_key
(rp
) then return identified_files_by_path
[rp
]
347 var mgrouppath
= path
.join_path
("..").simplify_path
348 var mgroup
= get_mgroup
(mgrouppath
)
350 if mgroup
== null then
352 var mproject
= new MProject(pn
, model
)
353 mgroup
= new MGroup(pn
, mproject
, null) # same name for the root group
354 mgroup
.filepath
= path
355 mproject
.root
= mgroup
356 toolcontext
.info
("found project `{pn}` at {path}", 2)
359 var res
= new ModulePath(pn
, path
, mgroup
)
360 mgroup
.module_paths
.add
(res
)
362 identified_files_by_path
[rp
] = res
363 identified_files
.add
(res
)
368 private var mgroups
= new HashMap[String, nullable MGroup]
370 # Return the mgroup associated to a directory path.
371 # If the directory is not a group null is returned.
373 # Note: `paths` is also used to look for mgroups
374 fun get_mgroup
(dirpath
: String): nullable MGroup
376 if not dirpath
.file_exists
then do
378 var try
= p
/ dirpath
379 if try
.file_exists
then
387 var rdp
= module_absolute_path
(dirpath
)
388 if mgroups
.has_key
(rdp
) then
392 # Hack, a group is determined by one of the following:
393 # * the presence of a honomymous nit file
394 # * the fact that the directory is named `src`
395 # * the fact that there is a sub-directory named `src`
396 var pn
= rdp
.basename
(".nit")
397 var mp
= dirpath
.join_path
(pn
+ ".nit").simplify_path
399 # dirpath2 is the root directory
400 # dirpath is the src subdirectory directory, if any, else it is the same that dirpath2
401 var dirpath2
= dirpath
402 if not mp
.file_exists
then
404 # With a src directory, the group name is the name of the parent directory
405 dirpath2
= rdp
.dirname
406 pn
= dirpath2
.basename
("")
408 # Check a `src` subdirectory
409 dirpath
= dirpath2
/ "src"
410 if not dirpath
.file_exists
then
411 # All rules failed, so return null
417 # check parent directory
418 var parentpath
= dirpath2
.join_path
("..").simplify_path
419 var parent
= get_mgroup
(parentpath
)
422 if parent
== null then
423 # no parent, thus new project
424 var mproject
= new MProject(pn
, model
)
425 mgroup
= new MGroup(pn
, mproject
, null) # same name for the root group
426 mproject
.root
= mgroup
427 toolcontext
.info
("found project `{mproject}` at {dirpath}", 2)
429 mgroup
= new MGroup(pn
, parent
.mproject
, parent
)
430 toolcontext
.info
("found sub group `{mgroup.full_name}` at {dirpath}", 2)
433 # search documentation
434 # in src first so the documentation of the project code can be distinct for the documentation of the project usage
435 var readme
= dirpath
.join_path
("README.md")
436 if not readme
.file_exists
then readme
= dirpath
.join_path
("README")
437 if not readme
.file_exists
then readme
= dirpath2
.join_path
("README.md")
438 if not readme
.file_exists
then readme
= dirpath2
.join_path
("README")
439 if readme
.file_exists
then
440 var mdoc
= load_markdown
(readme
)
442 mdoc
.original_mentity
= mgroup
445 mgroup
.filepath
= dirpath
446 mgroups
[module_absolute_path
(dirpath
)] = mgroup
447 mgroups
[module_absolute_path
(dirpath2
)] = mgroup
451 # Load a markdown file as a documentation object
452 fun load_markdown
(filepath
: String): MDoc
454 var mdoc
= new MDoc(new Location(new SourceFile.from_string
(filepath
, ""),0,0,0,0))
455 var s
= new FileReader.open
(filepath
)
457 mdoc
.content
.add
(s
.read_line
)
462 # Force the identification of all ModulePath of the group and sub-groups.
463 fun visit_group
(mgroup
: MGroup) do
464 var p
= mgroup
.filepath
467 var g
= get_mgroup
(fp
)
468 if g
!= null then visit_group
(g
)
473 # Transform relative paths (starting with '../') into absolute paths
474 private fun module_absolute_path
(path
: String): String do
475 return getcwd
.join_path
(path
).simplify_path
478 # Try to load a module AST using a path.
479 # Display an error if there is a problem (IO / lexer / parser) and return null
480 fun load_module_ast
(filename
: String): nullable AModule
482 if filename
.file_extension
!= "nit" then
483 self.toolcontext
.error
(null, "Error: file {filename} is not a valid nit module.")
486 if not filename
.file_exists
then
487 self.toolcontext
.error
(null, "Error: file {filename} not found.")
491 self.toolcontext
.info
("load module {filename}", 2)
494 var file
= new FileReader.open
(filename
)
495 var lexer
= new Lexer(new SourceFile(filename
, file
))
496 var parser
= new Parser(lexer
)
497 var tree
= parser
.parse
500 # Handle lexer and parser error
501 var nmodule
= tree
.n_base
502 if nmodule
== null then
503 var neof
= tree
.n_eof
504 assert neof
isa AError
505 error
(neof
, neof
.message
)
512 # Remove Nit source files from a list of arguments.
514 # Items of `args` that can be loaded as a nit file will be removed from `args` and returned.
515 fun filter_nit_source
(args
: Array[String]): Array[String]
517 var keep
= new Array[String]
518 var res
= new Array[String]
520 var l
= identify_file
(a
)
532 # Try to load a module using a path.
533 # Display an error if there is a problem (IO / lexer / parser) and return null.
534 # Note: usually, you do not need this method, use `get_mmodule_by_name` instead.
536 # The MModule is created however, the importation is not performed,
537 # therefore you should call `build_module_importation`.
538 fun load_module
(filename
: String): nullable AModule
540 # Look for the module
541 var file
= identify_file
(filename
)
543 if filename
.file_exists
then
544 toolcontext
.error
(null, "Error: `{filename}` is not a Nit source file.")
546 toolcontext
.error
(null, "Error: cannot find module `{filename}`.")
551 # Already known and loaded? then return it
552 var mmodule
= file
.mmodule
553 if mmodule
!= null then
554 return mmodule2nmodule
[mmodule
]
558 var nmodule
= load_module_ast
(file
.filepath
)
559 if nmodule
== null then return null # forward error
561 # build the mmodule and load imported modules
562 mmodule
= build_a_mmodule
(file
.mgroup
, file
.name
, nmodule
)
564 if mmodule
== null then return null # forward error
566 # Update the file information
567 file
.mmodule
= mmodule
572 # Injection of a new module without source.
573 # Used by the interpreter.
574 fun load_rt_module
(parent
: nullable MModule, nmodule
: AModule, mod_name
: String): nullable AModule
579 if parent
!= null then mgroup
= parent
.mgroup
580 var mmodule
= new MModule(model
, mgroup
, mod_name
, nmodule
.location
)
581 nmodule
.mmodule
= mmodule
582 nmodules
.add
(nmodule
)
583 self.mmodule2nmodule
[mmodule
] = nmodule
585 if parent
!= null then
586 var imported_modules
= new Array[MModule]
587 imported_modules
.add
(parent
)
588 mmodule
.set_visibility_for
(parent
, intrude_visibility
)
589 mmodule
.set_imported_mmodules
(imported_modules
)
591 build_module_importation
(nmodule
)
597 # Visit the AST and create the `MModule` object
598 private fun build_a_mmodule
(mgroup
: nullable MGroup, mod_name
: String, nmodule
: AModule): nullable MModule
600 # Check the module name
601 var decl
= nmodule
.n_moduledecl
603 var decl_name
= decl
.n_name
.n_id
.text
604 if decl_name
!= mod_name
then
605 error
(decl
.n_name
, "Error: module name missmatch; declared {decl_name} file named {mod_name}")
609 # Check for conflicting module names in the project
610 if mgroup
!= null then
611 var others
= model
.get_mmodules_by_name
(mod_name
)
612 if others
!= null then for other
in others
do
613 if other
.mgroup
!= null and other
.mgroup
.mproject
== mgroup
.mproject
then
615 if decl
== null then node
= nmodule
else node
= decl
.n_name
616 error
(node
, "Error: A module named `{other.full_name}` already exists at {other.location}")
623 var mmodule
= new MModule(model
, mgroup
, mod_name
, nmodule
.location
)
624 nmodule
.mmodule
= mmodule
625 nmodules
.add
(nmodule
)
626 self.mmodule2nmodule
[mmodule
] = nmodule
628 var source
= nmodule
.location
.file
629 if source
!= null then
630 assert source
.mmodule
== null
631 source
.mmodule
= mmodule
635 # Extract documentation
636 var ndoc
= decl
.n_doc
638 var mdoc
= ndoc
.to_mdoc
640 mdoc
.original_mentity
= mmodule
642 advice
(decl
, "missing-doc", "Documentation warning: Undocumented module `{mmodule}`")
644 # Is the module a test suite?
645 mmodule
.is_test_suite
= not decl
.get_annotations
("test_suite").is_empty
651 # Analyze the module importation and fill the module_importation_hierarchy
653 # Unless you used `load_module`, the importation is already done and this method does a no-op.
654 fun build_module_importation
(nmodule
: AModule)
656 if nmodule
.is_importation_done
then return
657 nmodule
.is_importation_done
= true
658 var mmodule
= nmodule
.mmodule
.as(not null)
660 var imported_modules
= new Array[MModule]
661 for aimport
in nmodule
.n_imports
do
663 if not aimport
isa AStdImport then
666 var mgroup
= mmodule
.mgroup
667 if aimport
.n_name
.n_quad
!= null then mgroup
= null # Start from top level
668 for grp
in aimport
.n_name
.n_path
do
669 var path
= search_mmodule_by_name
(grp
, mgroup
, grp
.text
)
670 if path
== null then return # Skip error
673 var mod_name
= aimport
.n_name
.n_id
.text
674 var sup
= self.get_mmodule_by_name
(aimport
.n_name
, mgroup
, mod_name
)
675 if sup
== null then continue # Skip error
676 aimport
.mmodule
= sup
677 imported_modules
.add
(sup
)
678 var mvisibility
= aimport
.n_visibility
.mvisibility
679 if mvisibility
== protected_visibility
then
680 error
(aimport
.n_visibility
, "Error: only properties can be protected.")
683 if sup
== mmodule
then
684 error
(aimport
.n_name
, "Error: Dependency loop in module {mmodule}.")
686 if sup
.in_importation
< mmodule
then
687 error
(aimport
.n_name
, "Error: Dependency loop between modules {mmodule} and {sup}.")
690 mmodule
.set_visibility_for
(sup
, mvisibility
)
693 var mod_name
= "standard"
694 var sup
= self.get_mmodule_by_name
(nmodule
, null, mod_name
)
695 if sup
!= null then # Skip error
696 imported_modules
.add
(sup
)
697 mmodule
.set_visibility_for
(sup
, public_visibility
)
700 self.toolcontext
.info
("{mmodule} imports {imported_modules.join(", ")}", 3)
701 mmodule
.set_imported_mmodules
(imported_modules
)
703 # Force standard to be public if imported
704 for sup
in mmodule
.in_importation
.greaters
do
705 if sup
.name
== "standard" then
706 mmodule
.set_visibility_for
(sup
, public_visibility
)
710 # TODO: Correctly check for useless importation
712 var directs
= mmodule
.in_importation
.direct_greaters
713 for nim
in nmodule
.n_imports
do
714 if not nim
isa AStdImport then continue
716 if im
== null then continue
717 if directs
.has
(im
) then continue
718 # This generates so much noise that it is simpler to just comment it
719 #warning(nim, "Warning: possible useless importation of {im}")
723 # All the loaded modules
724 var nmodules
= new Array[AModule]
726 # Register the nmodule associated to each mmodule
728 # Public clients need to use `mmodule2node` to access stuff.
729 private var mmodule2nmodule
= new HashMap[MModule, AModule]
731 # Retrieve the associated AST node of a mmodule.
732 # This method is used to associate model entity with syntactic entities.
734 # If the module is not associated with a node, returns null.
735 fun mmodule2node
(mmodule
: MModule): nullable AModule
737 return mmodule2nmodule
.get_or_null
(mmodule
)
741 # File-system location of a module (file) that is identified but not always loaded.
743 # The name of the module
744 # (it's the basename of the filepath)
747 # The human path of the module
750 # The group (and the project) of the possible module
753 # The loaded module (if any)
754 var mmodule
: nullable MModule = null
756 redef fun to_s
do return filepath
760 # Modules paths associated with the group
761 var module_paths
= new Array[ModulePath]
763 # Is the group interesting for a final user?
765 # Groups are mandatory in the model but for simple projects they are not
766 # always interesting.
768 # A interesting group has, at least, one of the following true:
770 # * it has 2 modules or more
771 # * it has a subgroup
772 # * it has a documentation
773 fun is_interesting
: Bool
775 return module_paths
.length
> 1 or mmodules
.length
> 1 or not in_nesting
.direct_smallers
.is_empty
or mdoc
!= null
780 redef class SourceFile
781 # Associated mmodule, once created
782 var mmodule
: nullable MModule = null
785 redef class AStdImport
786 # The imported module once determined
787 var mmodule
: nullable MModule = null
791 # The associated MModule once build by a `ModelBuilder`
792 var mmodule
: nullable MModule
793 # Flag that indicate if the importation is already completed
794 var is_importation_done
: Bool = false