nitc: move line coloration to Location
[nit.git] / src / mmloader.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
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>
6 #
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
10 #
11 # http://www.apache.org/licenses/LICENSE-2.0
12 #
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.
18
19 # This module is used to load a metamodel
20 package mmloader
21
22 import metamodel
23 import opts
24 import location
25
26 class Message
27 super Comparable
28 redef type OTHER: Message
29
30 readable var _location: nullable Location
31 readable var _text: String
32
33 redef fun <(other: OTHER): Bool do
34 if location == null then return true
35 if other.location == null then return false
36
37 return location.as(not null) < other.location.as(not null)
38 end
39
40 redef fun to_s: String
41 do
42 var l = location
43 if l == null then
44 return text
45 else
46 return "{l}: {text}"
47 end
48 end
49
50 fun to_color_string: String
51 do
52 var esc = 27.ascii
53 var red = "{esc}[0;31m"
54 var bred = "{esc}[1;31m"
55 var green = "{esc}[0;32m"
56 var yellow = "{esc}[0;33m"
57 var def = "{esc}[0m"
58
59 var l = location
60 if l == null then
61 return text
62 else if l.file == null then
63 return "{yellow}{l}{def}: {text}"
64 else
65 return "{yellow}{l}{def}: {text}\n{l.colored_line("1;31")}"
66 end
67 end
68 end
69
70 # Global context for tools
71 class ToolContext
72 super MMContext
73 # Number of errors
74 readable var _error_count: Int = 0
75
76 # Number of warnings
77 readable var _warning_count: Int = 0
78
79 # Directory where to generate log files
80 readable var _log_directory: String = "logs"
81
82 # Messages
83 var _messages: Array[Message] = new Array[Message]
84 var _message_sorter: ComparableSorter[Message] = new ComparableSorter[Message]
85
86 fun check_errors
87 do
88 if _messages.length > 0 then
89 _message_sorter.sort(_messages)
90
91 for m in _messages do
92 if opt_no_color.value then
93 stderr.write("{m}\n")
94 else
95 stderr.write("{m.to_color_string}\n")
96 end
97 end
98
99 _messages.clear
100 end
101
102 if error_count > 0 then exit(1)
103 end
104
105 # Display an error
106 fun error(l: nullable Location, s: String)
107 do
108 _messages.add(new Message(l,s))
109 _error_count = _error_count + 1
110 if opt_stop_on_first_error.value then check_errors
111 end
112
113 # Add an error, show errors and quit
114 fun fatal_error(l: nullable Location, s: String)
115 do
116 error(l,s)
117 check_errors
118 end
119
120 # Display a warning
121 fun warning(l: nullable Location, s: String)
122 do
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
127 end
128
129 # Display an info
130 fun info(s: String, level: Int)
131 do
132 if level <= verbose_level then
133 print "{s}"
134 end
135 end
136
137 # Paths where to locate modules files
138 readable var _paths: Array[String] = new Array[String]
139
140 # List of module loaders
141 var _loaders: Array[ModuleLoader] = new Array[ModuleLoader]
142
143 # Global OptionContext
144 readable var _option_context: OptionContext = new OptionContext
145
146 # Option --warn
147 readable var _opt_warn: OptionCount = new OptionCount("Show warnings", "-W", "--warn")
148
149 # Option --quiet
150 readable var _opt_quiet: OptionBool = new OptionBool("Do not show warnings", "-q", "--quiet")
151
152 # Option --path
153 readable var _opt_path: OptionArray = new OptionArray("Set include path for loaders (may be used more than once)", "-I", "--path")
154
155 # Option --log
156 readable var _opt_log: OptionBool = new OptionBool("Generate various log files", "--log")
157
158 # Option --log-dir
159 readable var _opt_log_dir: OptionString = new OptionString("Directory where to generate log files", "--log-dir")
160
161 # Option --only-metamodel
162 readable var _opt_only_metamodel: OptionBool = new OptionBool("Stop after meta-model processing", "--only-metamodel")
163
164 # Option --only-parse
165 readable var _opt_only_parse: OptionBool = new OptionBool("Only proceed to parse step of loaders", "--only-parse")
166
167 # Option --help
168 readable var _opt_help: OptionBool = new OptionBool("Show Help (This screen)", "-h", "-?", "--help")
169
170 # Option --version
171 readable var _opt_version: OptionBool = new OptionBool("Show version and exit", "--version")
172
173 # Option --verbose
174 readable var _opt_verbose: OptionCount = new OptionCount("Verbose", "-v", "--verbose")
175
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")
178
179 # Option --no-color
180 readable var _opt_no_color: OptionBool = new OptionBool("Do not use color to display errors and warnings", "--no-color")
181
182 # Verbose level
183 readable var _verbose_level: Int = 0
184
185 init
186 do
187 super
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)
189 end
190
191 # Parse and process the options given on the command line
192 fun process_options
193 do
194 self.opt_warn.value = 1
195
196 # init options
197 option_context.parse(args)
198
199 # Set verbose level
200 _verbose_level = opt_verbose.value
201
202 if self.opt_quiet.value then self.opt_warn.value = 0
203
204 # Setup the paths value
205 paths.append(opt_path.value)
206
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(':'))
210 end
211
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)
216 end
217
218 var libname = "{sys.program_name.dirname}/../lib"
219 if libname.file_exists then paths.add(libname.simplify_path)
220
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
224 log_directory.mkdir
225 end
226 end
227
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
232 do
233 # Look in the module directory
234 for m in dir.modules.values do
235 if m.name == module_name then return m
236 end
237
238 # print "try to load {module_name} in {dir.name} {_loaders.length}"
239
240 for l in _loaders do
241 var dir2 = l.try_to_load_dir(module_name, dir)
242 if dir2 != null then
243 var m = try_to_load(module_name, dir2)
244 if m != null then
245 dir2.owner = m
246 dir.add_module(m)
247 return m
248 end
249 end
250
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}")
256 end
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})"
261 dir.add_module(m)
262 return m
263 end
264 end
265 return null
266 end
267
268 # List of module currently processed.
269 # Used to prevent dependence loops.
270 var _processing_modules: HashSet[Symbol] = new HashSet[Symbol]
271
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
276 do
277 var path = filename.dirname
278 var module_name = filename.basename(".nit").to_symbol
279
280 var dir = directory_for(path)
281
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
287
288 # Else look for it in the path
289 return get_module(module_name, null)
290 end
291
292 if not filename.file_exists then
293 fatal_error(null, "Error: File {filename} not found.")
294 abort
295 end
296
297 # Try to load the module where mentionned
298 var m = try_to_load(module_name, dir)
299 if m != null then return m
300
301 fatal_error(null, "Error: {filename} is not a NIT source module.")
302 abort
303 end
304
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
308 do
309 if from != null then
310 var dir: nullable MMDirectory = from.directory
311 while dir != null do
312 var m = try_to_load(module_name, dir)
313 if m != null then return m
314 dir = dir.parent
315 end
316 end
317
318 for p in paths do
319 var m = try_to_load(module_name, directory_for(p))
320 if m != null then return m
321 end
322 # FIXME: Generate better error
323 fatal_error(null, "Error: No ressource found for module {module_name}.")
324 abort
325 end
326
327 # Return the module directory associated with a given path
328 private fun directory_for(path: String): MMDirectory
329 do
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
333 return dir
334 end
335
336 # Association bwtween plain path and module directories
337 var _path_dirs: Map[String, MMDirectory] = new HashMap[String, MMDirectory]
338
339 # Register a new module loader
340 fun register_loader(ml: ModuleLoader) do _loaders.add(ml)
341 end
342
343 # A load handler know how to load a specific module type
344 class ModuleLoader
345 # Type of module loaded by the loader
346 type MODULE: MMModule
347
348 # Extension that the loadhandler accepts
349 fun file_type: String is abstract
350
351 # Try to load a new module directory
352 fun try_to_load_dir(dirname: Symbol, parent_dir: MMDirectory): nullable MMDirectory
353 do
354 var fname = "{parent_dir.path}/{dirname}"
355 if not fname.file_exists then return null
356
357 var dir = new MMDirectory(parent_dir.full_name_for(dirname), fname, parent_dir)
358 return dir
359 end
360
361 # Can the loadhandler load a given module?
362 # Return the file found
363 fun can_handle(module_name: Symbol, dir: MMDirectory): Bool
364 do
365 var fname = "{dir.path}/{module_name}.{file_type}"
366 if fname.file_exists then return true
367 return false
368 end
369
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
373 do
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)
377 return m
378 end
379
380 # Load an parse the module
381 private fun load_module(context: ToolContext, module_name: Symbol, dir: MMDirectory, filename: String): MODULE
382 do
383 var file: IFStream
384 if filename == "-" then
385 file = stdin
386 else
387 file = new IFStream.open(filename.to_s)
388 end
389
390 if file.eof then
391 context.fatal_error(null, "Error: Problem in opening file {filename}")
392 end
393 var m = parse_file(context, file, filename, module_name, dir)
394 if file != stdin then file.close
395 return m
396 end
397
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
400
401 # Process a parsed module
402 protected fun process_metamodel(context: ToolContext, mod: MODULE) is abstract
403 end