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
)
75 var mmodule
= nmodule
.mmodule
76 if mmodule
== null then continue # skip error
80 self.toolcontext
.info
("*** END PARSE: {time1-time0} ***", 2)
82 self.toolcontext
.check_errors
84 if toolcontext
.opt_only_parse
.value
then
85 self.toolcontext
.info
("*** ONLY PARSE...", 1)
92 # Load recursively all modules of the group `mgroup`.
93 # See `parse` for details.
94 fun parse_group
(mgroup
: MGroup): Array[MModule]
96 var res
= new Array[MModule]
98 for mg
in mgroup
.in_nesting
.smallers
do
99 for mp
in mg
.module_paths
do
100 var nmodule
= self.load_module
(mp
.filepath
)
101 if nmodule
== null then continue # Skip error
102 # Load imported module
103 build_module_importation
(nmodule
)
104 var mmodule
= nmodule
.mmodule
105 if mmodule
== null then continue # Skip error
112 # Load a bunch of modules and groups.
116 # * a path to a module, a group or a directory of projects.
117 # * a short name of a module or a group that are looked in the `paths` (-I)
119 # Then, for each entry, if it is:
121 # * a module, then is it parser and returned.
122 # * a group then recursively all its modules are parsed.
123 # * a directory of projects then all the modules of all projects are parsed.
124 # * else an error is displayed.
126 # See `parse` for details.
127 fun parse_full
(names
: Sequence[String]): Array[MModule]
130 # Parse and recursively load
131 self.toolcontext
.info
("*** PARSE ***", 1)
132 var mmodules
= new ArraySet[MModule]
135 var mgroup
= self.get_mgroup
(a
)
136 if mgroup
!= null then
137 mmodules
.add_all parse_group
(mgroup
)
141 # Case of a directory that is not a group
142 var stat
= a
.to_path
.stat
143 if stat
!= null and stat
.is_dir
then
144 self.toolcontext
.info
("look in directory {a}", 2)
146 # Try each entry as a group or a module
149 mgroup
= get_mgroup
(af
)
150 if mgroup
!= null then
151 mmodules
.add_all parse_group
(mgroup
)
154 var mp
= identify_file
(af
)
156 var nmodule
= self.load_module
(af
)
157 if nmodule
== null then continue # Skip error
158 build_module_importation
(nmodule
)
159 var mmodule
= nmodule
.mmodule
160 if mmodule
== null then continue # Skip error
163 self.toolcontext
.info
("ignore file {af}", 2)
169 var nmodule
= self.load_module
(a
)
170 if nmodule
== null then continue # Skip error
171 # Load imported module
172 build_module_importation
(nmodule
)
173 var mmodule
= nmodule
.mmodule
174 if mmodule
== null then continue # Skip error
178 self.toolcontext
.info
("*** END PARSE: {time1-time0} ***", 2)
180 self.toolcontext
.check_errors
182 if toolcontext
.opt_only_parse
.value
then
183 self.toolcontext
.info
("*** ONLY PARSE...", 1)
190 # The list of directories to search for top level modules
191 # The list is initially set with:
193 # * the toolcontext --path option
194 # * the NIT_PATH environment variable
195 # * `toolcontext.nit_dir`
196 # Path can be added (or removed) by the client
197 var paths
= new Array[String]
199 # Like (and used by) `get_mmodule_by_name` but just return the ModulePath
200 fun search_mmodule_by_name
(anode
: nullable ANode, mgroup
: nullable MGroup, name
: String): nullable ModulePath
202 # First, look in groups
205 var dirname
= c
.filepath
206 if dirname
== null then break # virtual group
207 if dirname
.has_suffix
(".nit") then break # singleton project
209 # Second, try the directory to find a file
210 var try_file
= dirname
+ "/" + name
+ ".nit"
211 if try_file
.file_exists
then
212 var res
= self.identify_file
(try_file
.simplify_path
)
217 # Third, try if the requested module is itself a group
218 try_file
= dirname
+ "/" + name
+ "/" + name
+ ".nit"
219 if try_file
.file_exists
then
220 var res
= self.identify_file
(try_file
.simplify_path
)
228 # Look at some known directories
229 var lookpaths
= self.paths
231 # Look in the directory of the group project also (even if not explicitly in the path)
232 if mgroup
!= null then
233 # path of the root group
234 var dirname
= mgroup
.mproject
.root
.filepath
235 if dirname
!= null then
236 dirname
= dirname
.join_path
("..").simplify_path
237 if not lookpaths
.has
(dirname
) and dirname
.file_exists
then
238 lookpaths
= lookpaths
.to_a
239 lookpaths
.add
(dirname
)
244 var candidate
= search_module_in_paths
(anode
.hot_location
, name
, lookpaths
)
246 if candidate
== null then
247 if mgroup
!= null then
248 error
(anode
, "Error: cannot find module `{name}` from `{mgroup.name}`. Tried: {lookpaths.join(", ")}.")
250 error
(anode
, "Error: cannot find module `{name}`. Tried: {lookpaths.join(", ")}.")
257 # Get a module by its short name; if required, the module is loaded, parsed and its hierarchies computed.
258 # If `mgroup` is set, then the module search starts from it up to the top level (see `paths`);
259 # if `mgroup` is null then the module is searched in the top level only.
260 # If no module exists or there is a name conflict, then an error on `anode` is displayed and null is returned.
261 fun get_mmodule_by_name
(anode
: nullable ANode, mgroup
: nullable MGroup, name
: String): nullable MModule
263 var path
= search_mmodule_by_name
(anode
, mgroup
, name
)
264 if path
== null then return null # Forward error
265 var res
= self.load_module
(path
.filepath
)
266 if res
== null then return null # Forward error
267 # Load imported module
268 build_module_importation
(res
)
272 # Search a module `name` from path `lookpaths`.
273 # If found, the path of the file is returned
274 private fun search_module_in_paths
(location
: nullable Location, name
: String, lookpaths
: Collection[String]): nullable ModulePath
276 var candidate
: nullable String = null
277 for dirname
in lookpaths
do
278 var try_file
= (dirname
+ "/" + name
+ ".nit").simplify_path
279 if try_file
.file_exists
then
280 if candidate
== null then
282 else if candidate
!= try_file
then
283 # try to disambiguate conflicting modules
284 var abs_candidate
= module_absolute_path
(candidate
)
285 var abs_try_file
= module_absolute_path
(try_file
)
286 if abs_candidate
!= abs_try_file
then
287 toolcontext
.error
(location
, "Error: conflicting module file for `{name}`: `{candidate}` `{try_file}`")
291 try_file
= (dirname
+ "/" + name
+ "/" + name
+ ".nit").simplify_path
292 if try_file
.file_exists
then
293 if candidate
== null then
295 else if candidate
!= try_file
then
296 # try to disambiguate conflicting modules
297 var abs_candidate
= module_absolute_path
(candidate
)
298 var abs_try_file
= module_absolute_path
(try_file
)
299 if abs_candidate
!= abs_try_file
then
300 toolcontext
.error
(location
, "Error: conflicting module file for `{name}`: `{candidate}` `{try_file}`")
305 if candidate
== null then return null
306 return identify_file
(candidate
)
309 # Cache for `identify_file` by realpath
310 private var identified_files_by_path
= new HashMap[String, nullable ModulePath]
312 # All the currently identified modules.
313 # See `identify_file`.
314 var identified_files
= new Array[ModulePath]
316 # Identify a source file
317 # Load the associated project and groups if required
319 # Silently return `null` if `path` is not a valid module path.
320 fun identify_file
(path
: String): nullable ModulePath
322 # special case for not a nit file
323 if path
.file_extension
!= "nit" then
324 # search dirless files in known -I paths
325 if path
.dirname
== "" then
326 var res
= search_module_in_paths
(null, path
, self.paths
)
327 if res
!= null then return res
330 # Found nothing? maybe it is a group...
332 if path
.file_exists
then
333 var mgroup
= get_mgroup
(path
)
334 if mgroup
!= null then
335 var owner_path
= mgroup
.filepath
.join_path
(mgroup
.name
+ ".nit")
336 if owner_path
.file_exists
then candidate
= owner_path
340 if candidate
== null then
346 # Fast track, the path is already known
347 var pn
= path
.basename
(".nit")
348 var rp
= module_absolute_path
(path
)
349 if identified_files_by_path
.has_key
(rp
) then return identified_files_by_path
[rp
]
352 var mgrouppath
= path
.join_path
("..").simplify_path
353 var mgroup
= get_mgroup
(mgrouppath
)
355 if mgroup
== null then
357 var mproject
= new MProject(pn
, model
)
358 mgroup
= new MGroup(pn
, mproject
, null) # same name for the root group
359 mgroup
.filepath
= path
360 mproject
.root
= mgroup
361 toolcontext
.info
("found project `{pn}` at {path}", 2)
364 var res
= new ModulePath(pn
, path
, mgroup
)
365 mgroup
.module_paths
.add
(res
)
367 identified_files_by_path
[rp
] = res
368 identified_files
.add
(res
)
373 private var mgroups
= new HashMap[String, nullable MGroup]
375 # Return the mgroup associated to a directory path.
376 # If the directory is not a group null is returned.
378 # Note: `paths` is also used to look for mgroups
379 fun get_mgroup
(dirpath
: String): nullable MGroup
381 if not dirpath
.file_exists
then do
383 var try
= p
/ dirpath
384 if try
.file_exists
then
392 var rdp
= module_absolute_path
(dirpath
)
393 if mgroups
.has_key
(rdp
) then
397 # Hack, a group is determined by one of the following:
398 # * the presence of a honomymous nit file
399 # * the fact that the directory is named `src`
400 # * the fact that there is a sub-directory named `src`
401 var pn
= rdp
.basename
(".nit")
402 var mp
= dirpath
.join_path
(pn
+ ".nit").simplify_path
404 # dirpath2 is the root directory
405 # dirpath is the src subdirectory directory, if any, else it is the same that dirpath2
406 var dirpath2
= dirpath
407 if not mp
.file_exists
then
409 # With a src directory, the group name is the name of the parent directory
410 dirpath2
= rdp
.dirname
411 pn
= dirpath2
.basename
("")
413 # Check a `src` subdirectory
414 dirpath
= dirpath2
/ "src"
415 if not dirpath
.file_exists
then
416 # All rules failed, so return null
422 # check parent directory
423 var parentpath
= dirpath2
.join_path
("..").simplify_path
424 var parent
= get_mgroup
(parentpath
)
427 if parent
== null then
428 # no parent, thus new project
429 var mproject
= new MProject(pn
, model
)
430 mgroup
= new MGroup(pn
, mproject
, null) # same name for the root group
431 mproject
.root
= mgroup
432 toolcontext
.info
("found project `{mproject}` at {dirpath}", 2)
434 mgroup
= new MGroup(pn
, parent
.mproject
, parent
)
435 toolcontext
.info
("found sub group `{mgroup.full_name}` at {dirpath}", 2)
438 # search documentation
439 # in src first so the documentation of the project code can be distinct for the documentation of the project usage
440 var readme
= dirpath
.join_path
("README.md")
441 if not readme
.file_exists
then readme
= dirpath
.join_path
("README")
442 if not readme
.file_exists
then readme
= dirpath2
.join_path
("README.md")
443 if not readme
.file_exists
then readme
= dirpath2
.join_path
("README")
444 if readme
.file_exists
then
445 var mdoc
= load_markdown
(readme
)
447 mdoc
.original_mentity
= mgroup
450 mgroup
.filepath
= dirpath
451 mgroups
[module_absolute_path
(dirpath
)] = mgroup
452 mgroups
[module_absolute_path
(dirpath2
)] = mgroup
456 # Load a markdown file as a documentation object
457 fun load_markdown
(filepath
: String): MDoc
459 var mdoc
= new MDoc(new Location(new SourceFile.from_string
(filepath
, ""),0,0,0,0))
460 var s
= new FileReader.open
(filepath
)
462 mdoc
.content
.add
(s
.read_line
)
467 # Force the identification of all ModulePath of the group and sub-groups.
468 fun visit_group
(mgroup
: MGroup) do
469 var p
= mgroup
.filepath
472 var g
= get_mgroup
(fp
)
473 if g
!= null then visit_group
(g
)
478 # Transform relative paths (starting with '../') into absolute paths
479 private fun module_absolute_path
(path
: String): String do
480 return getcwd
.join_path
(path
).simplify_path
483 # Try to load a module AST using a path.
484 # Display an error if there is a problem (IO / lexer / parser) and return null
485 fun load_module_ast
(filename
: String): nullable AModule
487 if filename
.file_extension
!= "nit" then
488 self.toolcontext
.error
(null, "Error: file `{filename}` is not a valid nit module.")
491 if not filename
.file_exists
then
492 self.toolcontext
.error
(null, "Error: file `{filename}` not found.")
496 self.toolcontext
.info
("load module {filename}", 2)
499 var file
= new FileReader.open
(filename
)
500 var lexer
= new Lexer(new SourceFile(filename
, file
))
501 var parser
= new Parser(lexer
)
502 var tree
= parser
.parse
505 # Handle lexer and parser error
506 var nmodule
= tree
.n_base
507 if nmodule
== null then
508 var neof
= tree
.n_eof
509 assert neof
isa AError
510 error
(neof
, neof
.message
)
517 # Remove Nit source files from a list of arguments.
519 # Items of `args` that can be loaded as a nit file will be removed from `args` and returned.
520 fun filter_nit_source
(args
: Array[String]): Array[String]
522 var keep
= new Array[String]
523 var res
= new Array[String]
525 var l
= identify_file
(a
)
537 # Try to load a module using a path.
538 # Display an error if there is a problem (IO / lexer / parser) and return null.
539 # Note: usually, you do not need this method, use `get_mmodule_by_name` instead.
541 # The MModule is created however, the importation is not performed,
542 # therefore you should call `build_module_importation`.
543 fun load_module
(filename
: String): nullable AModule
545 # Look for the module
546 var file
= identify_file
(filename
)
548 if filename
.file_exists
then
549 toolcontext
.error
(null, "Error: `{filename}` is not a Nit source file.")
551 toolcontext
.error
(null, "Error: cannot find module `{filename}`.")
556 # Already known and loaded? then return it
557 var mmodule
= file
.mmodule
558 if mmodule
!= null then
559 return mmodule2nmodule
[mmodule
]
563 var nmodule
= load_module_ast
(file
.filepath
)
564 if nmodule
== null then return null # forward error
566 # build the mmodule and load imported modules
567 mmodule
= build_a_mmodule
(file
.mgroup
, file
.name
, nmodule
)
569 if mmodule
== null then return null # forward error
571 # Update the file information
572 file
.mmodule
= mmodule
577 # Injection of a new module without source.
578 # Used by the interpreter.
579 fun load_rt_module
(parent
: nullable MModule, nmodule
: AModule, mod_name
: String): nullable AModule
584 if parent
!= null then mgroup
= parent
.mgroup
585 var mmodule
= new MModule(model
, mgroup
, mod_name
, nmodule
.location
)
586 nmodule
.mmodule
= mmodule
587 nmodules
.add
(nmodule
)
588 self.mmodule2nmodule
[mmodule
] = nmodule
590 if parent
!= null then
591 var imported_modules
= new Array[MModule]
592 imported_modules
.add
(parent
)
593 mmodule
.set_visibility_for
(parent
, intrude_visibility
)
594 mmodule
.set_imported_mmodules
(imported_modules
)
596 build_module_importation
(nmodule
)
602 # Visit the AST and create the `MModule` object
603 private fun build_a_mmodule
(mgroup
: nullable MGroup, mod_name
: String, nmodule
: AModule): nullable MModule
605 # Check the module name
606 var decl
= nmodule
.n_moduledecl
608 var decl_name
= decl
.n_name
.n_id
.text
609 if decl_name
!= mod_name
then
610 error
(decl
.n_name
, "Error: module name mismatch; declared {decl_name} file named {mod_name}.")
614 # Check for conflicting module names in the project
615 if mgroup
!= null then
616 var others
= model
.get_mmodules_by_name
(mod_name
)
617 if others
!= null then for other
in others
do
618 if other
.mgroup
!= null and other
.mgroup
.mproject
== mgroup
.mproject
then
620 if decl
== null then node
= nmodule
else node
= decl
.n_name
621 error
(node
, "Error: a module named `{other.full_name}` already exists at {other.location}.")
628 var mmodule
= new MModule(model
, mgroup
, mod_name
, nmodule
.location
)
629 nmodule
.mmodule
= mmodule
630 nmodules
.add
(nmodule
)
631 self.mmodule2nmodule
[mmodule
] = nmodule
633 var source
= nmodule
.location
.file
634 if source
!= null then
635 assert source
.mmodule
== null
636 source
.mmodule
= mmodule
640 # Extract documentation
641 var ndoc
= decl
.n_doc
643 var mdoc
= ndoc
.to_mdoc
645 mdoc
.original_mentity
= mmodule
647 advice
(decl
, "missing-doc", "Documentation warning: Undocumented module `{mmodule}`")
649 # Is the module a test suite?
650 mmodule
.is_test_suite
= not decl
.get_annotations
("test_suite").is_empty
656 # Analyze the module importation and fill the module_importation_hierarchy
658 # Unless you used `load_module`, the importation is already done and this method does a no-op.
659 fun build_module_importation
(nmodule
: AModule)
661 if nmodule
.is_importation_done
then return
662 nmodule
.is_importation_done
= true
663 var mmodule
= nmodule
.mmodule
.as(not null)
665 var imported_modules
= new Array[MModule]
666 for aimport
in nmodule
.n_imports
do
668 if not aimport
isa AStdImport then
671 var mgroup
= mmodule
.mgroup
672 if aimport
.n_name
.n_quad
!= null then mgroup
= null # Start from top level
673 for grp
in aimport
.n_name
.n_path
do
674 var path
= search_mmodule_by_name
(grp
, mgroup
, grp
.text
)
676 nmodule
.mmodule
= null # invalidate the module
681 var mod_name
= aimport
.n_name
.n_id
.text
682 var sup
= self.get_mmodule_by_name
(aimport
.n_name
, mgroup
, mod_name
)
684 nmodule
.mmodule
= null # invalidate the module
685 continue # Skip error
687 aimport
.mmodule
= sup
688 imported_modules
.add
(sup
)
689 var mvisibility
= aimport
.n_visibility
.mvisibility
690 if mvisibility
== protected_visibility
then
691 error
(aimport
.n_visibility
, "Error: only properties can be protected.")
692 nmodule
.mmodule
= null # invalidate the module
695 if sup
== mmodule
then
696 error
(aimport
.n_name
, "Error: dependency loop in module {mmodule}.")
697 nmodule
.mmodule
= null # invalidate the module
699 if sup
.in_importation
< mmodule
then
700 error
(aimport
.n_name
, "Error: dependency loop between modules {mmodule} and {sup}.")
701 nmodule
.mmodule
= null # invalidate the module
704 mmodule
.set_visibility_for
(sup
, mvisibility
)
707 var mod_name
= "standard"
708 var sup
= self.get_mmodule_by_name
(nmodule
, null, mod_name
)
710 nmodule
.mmodule
= null # invalidate the module
712 imported_modules
.add
(sup
)
713 mmodule
.set_visibility_for
(sup
, public_visibility
)
716 self.toolcontext
.info
("{mmodule} imports {imported_modules.join(", ")}", 3)
717 mmodule
.set_imported_mmodules
(imported_modules
)
719 # Force standard to be public if imported
720 for sup
in mmodule
.in_importation
.greaters
do
721 if sup
.name
== "standard" then
722 mmodule
.set_visibility_for
(sup
, public_visibility
)
726 # TODO: Correctly check for useless importation
728 var directs
= mmodule
.in_importation
.direct_greaters
729 for nim
in nmodule
.n_imports
do
730 if not nim
isa AStdImport then continue
732 if im
== null then continue
733 if directs
.has
(im
) then continue
734 # This generates so much noise that it is simpler to just comment it
735 #warning(nim, "Warning: possible useless importation of {im}")
739 # All the loaded modules
740 var nmodules
= new Array[AModule]
742 # Register the nmodule associated to each mmodule
744 # Public clients need to use `mmodule2node` to access stuff.
745 private var mmodule2nmodule
= new HashMap[MModule, AModule]
747 # Retrieve the associated AST node of a mmodule.
748 # This method is used to associate model entity with syntactic entities.
750 # If the module is not associated with a node, returns null.
751 fun mmodule2node
(mmodule
: MModule): nullable AModule
753 return mmodule2nmodule
.get_or_null
(mmodule
)
757 # File-system location of a module (file) that is identified but not always loaded.
759 # The name of the module
760 # (it's the basename of the filepath)
763 # The human path of the module
766 # The group (and the project) of the possible module
769 # The loaded module (if any)
770 var mmodule
: nullable MModule = null
772 redef fun to_s
do return filepath
776 # Modules paths associated with the group
777 var module_paths
= new Array[ModulePath]
779 # Is the group interesting for a final user?
781 # Groups are mandatory in the model but for simple projects they are not
782 # always interesting.
784 # A interesting group has, at least, one of the following true:
786 # * it has 2 modules or more
787 # * it has a subgroup
788 # * it has a documentation
789 fun is_interesting
: Bool
791 return module_paths
.length
> 1 or mmodules
.length
> 1 or not in_nesting
.direct_smallers
.is_empty
or mdoc
!= null
796 redef class SourceFile
797 # Associated mmodule, once created
798 var mmodule
: nullable MModule = null
801 redef class AStdImport
802 # The imported module once determined
803 var mmodule
: nullable MModule = null
807 # The associated MModule once build by a `ModelBuilder`
808 var mmodule
: nullable MModule
809 # Flag that indicate if the importation is already completed
810 var is_importation_done
: Bool = false