1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2006-2008 Floréal Morandat <morandat@lirmm.fr>
4 # Copyright 2008 Jean Privat <jean@pryen.org>
5 # Copyright 2009 Jean-Sebastien Gelinas <calestar@gmail.com>
7 # Licensed under the Apache License, Version 2.0 (the "License");
8 # you may not use this file except in compliance with the License.
9 # You may obtain a copy of the License at
11 # http://www.apache.org/licenses/LICENSE-2.0
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS,
15 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
19 # This module is used to load a metamodel
28 redef type OTHER: Message
30 readable var _location
: nullable Location
31 readable var _text
: String
33 redef fun <(other
: OTHER): Bool do
34 if location
== null then return true
35 if other
.location
== null then return false
37 return location
.as(not null) < other
.location
.as(not null)
40 redef fun to_s
: String
50 fun to_color_string
: String
53 var red
= "{esc}[0;31m"
54 var bred
= "{esc}[1;31m"
55 var green
= "{esc}[0;32m"
56 var yellow
= "{esc}[0;33m"
62 else if l
.file
== null then
63 return "{yellow}{l}{def}: {text}"
65 return "{yellow}{l}{def}: {text}\n{l.colored_line("1;31")}"
70 # Global context for tools
74 readable var _error_count
: Int = 0
77 readable var _warning_count
: Int = 0
79 # Directory where to generate log files
80 readable var _log_directory
: String = "logs"
83 var _messages
: Array[Message] = new Array[Message]
84 var _message_sorter
: ComparableSorter[Message] = new ComparableSorter[Message]
88 if _messages
.length
> 0 then
89 _message_sorter
.sort
(_messages
)
92 if opt_no_color
.value
then
95 stderr
.write
("{m.to_color_string}\n")
102 if error_count
> 0 then exit
(1)
106 fun error
(l
: nullable Location, s
: String)
108 _messages
.add
(new Message(l
,s
))
109 _error_count
= _error_count
+ 1
110 if opt_stop_on_first_error
.value
then check_errors
113 # Add an error, show errors and quit
114 fun fatal_error
(l
: nullable Location, s
: String)
121 fun warning
(l
: nullable Location, s
: String)
123 if _opt_warn
.value
== 0 then return
124 _messages
.add
(new Message(l
,s
))
125 _warning_count
= _warning_count
+ 1
126 if opt_stop_on_first_error
.value
then check_errors
130 fun info
(s
: String, level
: Int)
132 if level
<= verbose_level
then
137 # Paths where to locate modules files
138 readable var _paths
: Array[String] = new Array[String]
140 # List of module loaders
141 var _loaders
: Array[ModuleLoader] = new Array[ModuleLoader]
143 # Global OptionContext
144 readable var _option_context
: OptionContext = new OptionContext
147 readable var _opt_warn
: OptionCount = new OptionCount("Show warnings", "-W", "--warn")
150 readable var _opt_quiet
: OptionBool = new OptionBool("Do not show warnings", "-q", "--quiet")
153 readable var _opt_path
: OptionArray = new OptionArray("Set include path for loaders (may be used more than once)", "-I", "--path")
156 readable var _opt_log
: OptionBool = new OptionBool("Generate various log files", "--log")
159 readable var _opt_log_dir
: OptionString = new OptionString("Directory where to generate log files", "--log-dir")
161 # Option --only-metamodel
162 readable var _opt_only_metamodel
: OptionBool = new OptionBool("Stop after meta-model processing", "--only-metamodel")
164 # Option --only-parse
165 readable var _opt_only_parse
: OptionBool = new OptionBool("Only proceed to parse step of loaders", "--only-parse")
168 readable var _opt_help
: OptionBool = new OptionBool("Show Help (This screen)", "-h", "-?", "--help")
171 readable var _opt_version
: OptionBool = new OptionBool("Show version and exit", "--version")
174 readable var _opt_verbose
: OptionCount = new OptionCount("Verbose", "-v", "--verbose")
176 # Option --stop-on-first-error
177 readable var _opt_stop_on_first_error
: OptionBool = new OptionBool("Stop on first error", "--stop-on-first-error")
180 readable var _opt_no_color
: OptionBool = new OptionBool("Do not use color to display errors and warnings", "--no-color")
183 readable var _verbose_level
: Int = 0
188 option_context
.add_option
(opt_warn
, opt_quiet
, opt_stop_on_first_error
, opt_no_color
, opt_path
, opt_log
, opt_log_dir
, opt_only_parse
, opt_only_metamodel
, opt_help
, opt_version
, opt_verbose
)
191 # Parse and process the options given on the command line
194 self.opt_warn
.value
= 1
197 option_context
.parse
(args
)
200 _verbose_level
= opt_verbose
.value
202 if self.opt_quiet
.value
then self.opt_warn
.value
= 0
204 # Setup the paths value
205 paths
.append
(opt_path
.value
)
207 var path_env
= once
("NIT_PATH".to_symbol
).environ
208 if not path_env
.is_empty
then
209 paths
.append
(path_env
.split_with
(':'))
212 path_env
= once
("NIT_DIR".to_symbol
).environ
213 if not path_env
.is_empty
then
214 var libname
= "{path_env}/lib"
215 if libname
.file_exists
then paths
.add
(libname
)
218 var libname
= "{sys.program_name.dirname}/../lib"
219 if libname
.file_exists
then paths
.add
(libname
.simplify_path
)
221 if opt_log_dir
.value
!= null then _log_directory
= opt_log_dir
.value
.as(not null)
222 if _opt_log
.value
then
223 # Make sure the output directory exists
228 # Load and process a module in a directory (or a parent directory).
229 # If the module is already loaded, just return it without further processing.
230 # If no module is found, just return null without complaining.
231 private fun try_to_load
(module_name
: Symbol, dir
: MMDirectory): nullable MMModule
233 # Look in the module directory
234 for m
in dir
.modules
.values
do
235 if m
.name
== module_name
then return m
238 # print "try to load {module_name} in {dir.name} {_loaders.length}"
241 var dir2
= l
.try_to_load_dir
(module_name
, dir
)
243 var m
= try_to_load
(module_name
, dir2
)
251 if l
.can_handle
(module_name
, dir
) then
252 var full_name
= dir
.full_name_for
(module_name
)
253 if _processing_modules
.has
(full_name
) then
254 # FIXME: Generate better error
255 fatal_error
(null, "Error: Dependency loop for module {full_name}")
257 _processing_modules
.add
(full_name
)
258 var m
= l
.load_and_process_module
(self, module_name
, dir
)
259 _processing_modules
.remove
(full_name
)
260 #if m != null then print "loaded {m.name} in {m.directory.name} -> {m.full_name} ({m.full_name.object_id.to_hex})"
268 # List of module currently processed.
269 # Used to prevent dependence loops.
270 var _processing_modules
: HashSet[Symbol] = new HashSet[Symbol]
272 # Locate, load and analysis a module (and its supermodules) from its file name.
273 # If the module is already loaded, just return it without further processing.
274 # Beware, the files are automatically considered root of their directory.
275 fun get_module_from_filename
(filename
: String): MMModule
277 var path
= filename
.dirname
278 var module_name
= filename
.basename
(".nit").to_symbol
280 var dir
= directory_for
(path
)
282 if module_name
.to_s
== filename
then
283 # It's just a modulename
284 # look for it in the path directory "."
285 var m
= try_to_load
(module_name
, dir
)
286 if m
!= null then return m
288 # Else look for it in the path
289 return get_module
(module_name
, null)
292 if not filename
.file_exists
then
293 fatal_error
(null, "Error: File {filename} not found.")
297 # Try to load the module where mentionned
298 var m
= try_to_load
(module_name
, dir
)
299 if m
!= null then return m
301 fatal_error
(null, "Error: {filename} is not a NIT source module.")
305 # Locate, load and analysis a module (and its supermodules).
306 # If the module is already loaded, just return it without further processing.
307 fun get_module
(module_name
: Symbol, from
: nullable MMModule): MMModule
310 var dir
: nullable MMDirectory = from
.directory
312 var m
= try_to_load
(module_name
, dir
)
313 if m
!= null then return m
319 var m
= try_to_load
(module_name
, directory_for
(p
))
320 if m
!= null then return m
322 # FIXME: Generate better error
323 fatal_error
(null, "Error: No ressource found for module {module_name}.")
327 # Return the module directory associated with a given path
328 private fun directory_for
(path
: String): MMDirectory
330 if _path_dirs
.has_key
(path
) then return _path_dirs
[path
]
331 var dir
= new MMDirectory(path
.to_symbol
, path
, null)
332 _path_dirs
[path
] = dir
336 # Association bwtween plain path and module directories
337 var _path_dirs
: Map[String, MMDirectory] = new HashMap[String, MMDirectory]
339 # Register a new module loader
340 fun register_loader
(ml
: ModuleLoader) do _loaders
.add
(ml
)
343 # A load handler know how to load a specific module type
345 # Type of module loaded by the loader
346 type MODULE: MMModule
348 # Extension that the loadhandler accepts
349 fun file_type
: String is abstract
351 # Try to load a new module directory
352 fun try_to_load_dir
(dirname
: Symbol, parent_dir
: MMDirectory): nullable MMDirectory
354 var fname
= "{parent_dir.path}/{dirname}"
355 if not fname
.file_exists
then return null
357 var dir
= new MMDirectory(parent_dir
.full_name_for
(dirname
), fname
, parent_dir
)
361 # Can the loadhandler load a given module?
362 # Return the file found
363 fun can_handle
(module_name
: Symbol, dir
: MMDirectory): Bool
365 var fname
= "{dir.path}/{module_name}.{file_type}"
366 if fname
.file_exists
then return true
370 # Load the module and process it
371 # filename is the result of can_handle
372 fun load_and_process_module
(context
: ToolContext, module_name
: Symbol, dir
: MMDirectory): MODULE
374 var filename
= "{dir.path}/{module_name}.{file_type}".simplify_path
375 var m
= load_module
(context
, module_name
, dir
, filename
)
376 if not context
.opt_only_parse
.value
then process_metamodel
(context
, m
)
380 # Load an parse the module
381 private fun load_module
(context
: ToolContext, module_name
: Symbol, dir
: MMDirectory, filename
: String): MODULE
384 if filename
== "-" then
387 file
= new IFStream.open
(filename
.to_s
)
391 context
.fatal_error
(null, "Error: Problem in opening file {filename}")
393 var m
= parse_file
(context
, file
, filename
, module_name
, dir
)
394 if file
!= stdin
then file
.close
398 # Parse the file to load a module
399 protected fun parse_file
(context
: ToolContext, file
: IFStream, filename
: String, module_name
: Symbol, dir
: MMDirectory): MODULE is abstract
401 # Process a parsed module
402 protected fun process_metamodel
(context
: ToolContext, mod
: MODULE) is abstract