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:
393 # * the presence of a honomymous nit file
394 # * the fact that the directory is named `src`
395 var pn
= rdp
.basename
(".nit")
396 var mp
= dirpath
.join_path
(pn
+ ".nit").simplify_path
398 var dirpath2
= dirpath
399 if not mp
.file_exists
then
401 # With a src directory, the group name is the name of the parent directory
402 dirpath2
= rdp
.dirname
403 pn
= dirpath2
.basename
("")
409 # check parent directory
410 var parentpath
= dirpath
.join_path
("..").simplify_path
411 var parent
= get_mgroup
(parentpath
)
414 if parent
== null then
415 # no parent, thus new project
416 var mproject
= new MProject(pn
, model
)
417 mgroup
= new MGroup(pn
, mproject
, null) # same name for the root group
418 mproject
.root
= mgroup
419 toolcontext
.info
("found project `{mproject}` at {dirpath}", 2)
421 mgroup
= new MGroup(pn
, parent
.mproject
, parent
)
422 toolcontext
.info
("found sub group `{mgroup.full_name}` at {dirpath}", 2)
425 # search documentation
426 # in src first so the documentation of the project code can be distinct for the documentation of the project usage
427 var readme
= dirpath
.join_path
("README.md")
428 if not readme
.file_exists
then readme
= dirpath
.join_path
("README")
429 if not readme
.file_exists
then readme
= dirpath2
.join_path
("README.md")
430 if not readme
.file_exists
then readme
= dirpath2
.join_path
("README")
431 if readme
.file_exists
then
432 var mdoc
= load_markdown
(readme
)
434 mdoc
.original_mentity
= mgroup
437 mgroup
.filepath
= dirpath
438 mgroups
[rdp
] = mgroup
442 # Load a markdown file as a documentation object
443 fun load_markdown
(filepath
: String): MDoc
445 var mdoc
= new MDoc(new Location(new SourceFile.from_string
(filepath
, ""),0,0,0,0))
446 var s
= new FileReader.open
(filepath
)
448 mdoc
.content
.add
(s
.read_line
)
453 # Force the identification of all ModulePath of the group and sub-groups.
454 fun visit_group
(mgroup
: MGroup) do
455 var p
= mgroup
.filepath
458 var g
= get_mgroup
(fp
)
459 if g
!= null then visit_group
(g
)
464 # Transform relative paths (starting with '../') into absolute paths
465 private fun module_absolute_path
(path
: String): String do
466 return getcwd
.join_path
(path
).simplify_path
469 # Try to load a module AST using a path.
470 # Display an error if there is a problem (IO / lexer / parser) and return null
471 fun load_module_ast
(filename
: String): nullable AModule
473 if filename
.file_extension
!= "nit" then
474 self.toolcontext
.error
(null, "Error: file {filename} is not a valid nit module.")
477 if not filename
.file_exists
then
478 self.toolcontext
.error
(null, "Error: file {filename} not found.")
482 self.toolcontext
.info
("load module {filename}", 2)
485 var file
= new FileReader.open
(filename
)
486 var lexer
= new Lexer(new SourceFile(filename
, file
))
487 var parser
= new Parser(lexer
)
488 var tree
= parser
.parse
491 # Handle lexer and parser error
492 var nmodule
= tree
.n_base
493 if nmodule
== null then
494 var neof
= tree
.n_eof
495 assert neof
isa AError
496 error
(neof
, neof
.message
)
503 # Remove Nit source files from a list of arguments.
505 # Items of `args` that can be loaded as a nit file will be removed from `args` and returned.
506 fun filter_nit_source
(args
: Array[String]): Array[String]
508 var keep
= new Array[String]
509 var res
= new Array[String]
511 var l
= identify_file
(a
)
523 # Try to load a module using a path.
524 # Display an error if there is a problem (IO / lexer / parser) and return null.
525 # Note: usually, you do not need this method, use `get_mmodule_by_name` instead.
527 # The MModule is created however, the importation is not performed,
528 # therefore you should call `build_module_importation`.
529 fun load_module
(filename
: String): nullable AModule
531 # Look for the module
532 var file
= identify_file
(filename
)
534 if filename
.file_exists
then
535 toolcontext
.error
(null, "Error: `{filename}` is not a Nit source file.")
537 toolcontext
.error
(null, "Error: cannot find module `{filename}`.")
542 # Already known and loaded? then return it
543 var mmodule
= file
.mmodule
544 if mmodule
!= null then
545 return mmodule2nmodule
[mmodule
]
549 var nmodule
= load_module_ast
(file
.filepath
)
550 if nmodule
== null then return null # forward error
552 # build the mmodule and load imported modules
553 mmodule
= build_a_mmodule
(file
.mgroup
, file
.name
, nmodule
)
555 if mmodule
== null then return null # forward error
557 # Update the file information
558 file
.mmodule
= mmodule
563 # Injection of a new module without source.
564 # Used by the interpreter.
565 fun load_rt_module
(parent
: nullable MModule, nmodule
: AModule, mod_name
: String): nullable AModule
570 if parent
!= null then mgroup
= parent
.mgroup
571 var mmodule
= new MModule(model
, mgroup
, mod_name
, nmodule
.location
)
572 nmodule
.mmodule
= mmodule
573 nmodules
.add
(nmodule
)
574 self.mmodule2nmodule
[mmodule
] = nmodule
576 if parent
!= null then
577 var imported_modules
= new Array[MModule]
578 imported_modules
.add
(parent
)
579 mmodule
.set_visibility_for
(parent
, intrude_visibility
)
580 mmodule
.set_imported_mmodules
(imported_modules
)
582 build_module_importation
(nmodule
)
588 # Visit the AST and create the `MModule` object
589 private fun build_a_mmodule
(mgroup
: nullable MGroup, mod_name
: String, nmodule
: AModule): nullable MModule
591 # Check the module name
592 var decl
= nmodule
.n_moduledecl
594 var decl_name
= decl
.n_name
.n_id
.text
595 if decl_name
!= mod_name
then
596 error
(decl
.n_name
, "Error: module name missmatch; declared {decl_name} file named {mod_name}")
600 # Check for conflicting module names in the project
601 if mgroup
!= null then
602 var others
= model
.get_mmodules_by_name
(mod_name
)
603 if others
!= null then for other
in others
do
604 if other
.mgroup
!= null and other
.mgroup
.mproject
== mgroup
.mproject
then
606 if decl
== null then node
= nmodule
else node
= decl
.n_name
607 error
(node
, "Error: A module named `{other.full_name}` already exists at {other.location}")
614 var mmodule
= new MModule(model
, mgroup
, mod_name
, nmodule
.location
)
615 nmodule
.mmodule
= mmodule
616 nmodules
.add
(nmodule
)
617 self.mmodule2nmodule
[mmodule
] = nmodule
619 var source
= nmodule
.location
.file
620 if source
!= null then
621 assert source
.mmodule
== null
622 source
.mmodule
= mmodule
626 # Extract documentation
627 var ndoc
= decl
.n_doc
629 var mdoc
= ndoc
.to_mdoc
631 mdoc
.original_mentity
= mmodule
633 advice
(decl
, "missing-doc", "Documentation warning: Undocumented module `{mmodule}`")
635 # Is the module a test suite?
636 mmodule
.is_test_suite
= not decl
.get_annotations
("test_suite").is_empty
642 # Analyze the module importation and fill the module_importation_hierarchy
644 # Unless you used `load_module`, the importation is already done and this method does a no-op.
645 fun build_module_importation
(nmodule
: AModule)
647 if nmodule
.is_importation_done
then return
648 nmodule
.is_importation_done
= true
649 var mmodule
= nmodule
.mmodule
.as(not null)
651 var imported_modules
= new Array[MModule]
652 for aimport
in nmodule
.n_imports
do
654 if not aimport
isa AStdImport then
657 var mgroup
= mmodule
.mgroup
658 if aimport
.n_name
.n_quad
!= null then mgroup
= null # Start from top level
659 for grp
in aimport
.n_name
.n_path
do
660 var path
= search_mmodule_by_name
(grp
, mgroup
, grp
.text
)
661 if path
== null then return # Skip error
664 var mod_name
= aimport
.n_name
.n_id
.text
665 var sup
= self.get_mmodule_by_name
(aimport
.n_name
, mgroup
, mod_name
)
666 if sup
== null then continue # Skip error
667 aimport
.mmodule
= sup
668 imported_modules
.add
(sup
)
669 var mvisibility
= aimport
.n_visibility
.mvisibility
670 if mvisibility
== protected_visibility
then
671 error
(aimport
.n_visibility
, "Error: only properties can be protected.")
674 if sup
== mmodule
then
675 error
(aimport
.n_name
, "Error: Dependency loop in module {mmodule}.")
677 if sup
.in_importation
< mmodule
then
678 error
(aimport
.n_name
, "Error: Dependency loop between modules {mmodule} and {sup}.")
681 mmodule
.set_visibility_for
(sup
, mvisibility
)
684 var mod_name
= "standard"
685 var sup
= self.get_mmodule_by_name
(nmodule
, null, mod_name
)
686 if sup
!= null then # Skip error
687 imported_modules
.add
(sup
)
688 mmodule
.set_visibility_for
(sup
, public_visibility
)
691 self.toolcontext
.info
("{mmodule} imports {imported_modules.join(", ")}", 3)
692 mmodule
.set_imported_mmodules
(imported_modules
)
694 # Force standard to be public if imported
695 for sup
in mmodule
.in_importation
.greaters
do
696 if sup
.name
== "standard" then
697 mmodule
.set_visibility_for
(sup
, public_visibility
)
701 # TODO: Correctly check for useless importation
703 var directs
= mmodule
.in_importation
.direct_greaters
704 for nim
in nmodule
.n_imports
do
705 if not nim
isa AStdImport then continue
707 if im
== null then continue
708 if directs
.has
(im
) then continue
709 # This generates so much noise that it is simpler to just comment it
710 #warning(nim, "Warning: possible useless importation of {im}")
714 # All the loaded modules
715 var nmodules
= new Array[AModule]
717 # Register the nmodule associated to each mmodule
719 # Public clients need to use `mmodule2node` to access stuff.
720 private var mmodule2nmodule
= new HashMap[MModule, AModule]
722 # Retrieve the associated AST node of a mmodule.
723 # This method is used to associate model entity with syntactic entities.
725 # If the module is not associated with a node, returns null.
726 fun mmodule2node
(mmodule
: MModule): nullable AModule
728 return mmodule2nmodule
.get_or_null
(mmodule
)
732 # File-system location of a module (file) that is identified but not always loaded.
734 # The name of the module
735 # (it's the basename of the filepath)
738 # The human path of the module
741 # The group (and the project) of the possible module
744 # The loaded module (if any)
745 var mmodule
: nullable MModule = null
747 redef fun to_s
do return filepath
751 # Modules paths associated with the group
752 var module_paths
= new Array[ModulePath]
754 # Is the group interesting for a final user?
756 # Groups are mandatory in the model but for simple projects they are not
757 # always interesting.
759 # A interesting group has, at least, one of the following true:
761 # * it has 2 modules or more
762 # * it has a subgroup
763 # * it has a documentation
764 fun is_interesting
: Bool
766 return module_paths
.length
> 1 or mmodules
.length
> 1 or not in_nesting
.direct_smallers
.is_empty
or mdoc
!= null
771 redef class SourceFile
772 # Associated mmodule, once created
773 var mmodule
: nullable MModule = null
776 redef class AStdImport
777 # The imported module once determined
778 var mmodule
: nullable MModule = null
782 # The associated MModule once build by a `ModelBuilder`
783 var mmodule
: nullable MModule
784 # Flag that indicate if the importation is already completed
785 var is_importation_done
: Bool = false