update NOTICE and LICENSE
[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 var i = location.line_start
66 var line_start = l.file.line_starts[i-1]
67 var line_end = line_start
68 var string = l.file.string
69 while line_end+1 < string.length and string[line_end+1] != '\n' and string[line_end+1] != '\r' do
70 line_end += 1
71 end
72 var lstart = string.substring(line_start, location.column_start - 1)
73 var cend
74 if i != location.line_end then
75 cend = line_end - line_start + 1
76 else
77 cend = location.column_end
78 end
79 var lmid = string.substring(line_start + location.column_start - 1, cend - location.column_start + 1)
80 var lend = string.substring(line_start + cend, line_end - line_start - cend + 1)
81 var indent = new Buffer
82 for j in [line_start..line_start+location.column_start-1[ do
83 if string[j] == '\t' then
84 indent.add '\t'
85 else
86 indent.add ' '
87 end
88 end
89 return "{yellow}{l}{def}: {text}\n\t{lstart}{bred}{lmid}{def}{lend}\n\t{indent}^"
90 end
91 end
92 end
93
94 # Global context for tools
95 class ToolContext
96 super MMContext
97 # Number of errors
98 readable var _error_count: Int = 0
99
100 # Number of warnings
101 readable var _warning_count: Int = 0
102
103 # Directory where to generate log files
104 readable var _log_directory: String = "logs"
105
106 # Messages
107 var _messages: Array[Message] = new Array[Message]
108 var _message_sorter: ComparableSorter[Message] = new ComparableSorter[Message]
109
110 fun check_errors
111 do
112 if _messages.length > 0 then
113 _message_sorter.sort(_messages)
114
115 for m in _messages do
116 if opt_no_color.value then
117 stderr.write("{m}\n")
118 else
119 stderr.write("{m.to_color_string}\n")
120 end
121 end
122
123 _messages.clear
124 end
125
126 if error_count > 0 then exit(1)
127 end
128
129 # Display an error
130 fun error(l: nullable Location, s: String)
131 do
132 _messages.add(new Message(l,s))
133 _error_count = _error_count + 1
134 if opt_stop_on_first_error.value then check_errors
135 end
136
137 # Add an error, show errors and quit
138 fun fatal_error(l: nullable Location, s: String)
139 do
140 error(l,s)
141 check_errors
142 end
143
144 # Display a warning
145 fun warning(l: nullable Location, s: String)
146 do
147 if _opt_warn.value == 0 then return
148 _messages.add(new Message(l,s))
149 if _opt_warn.value == 1 then
150 _warning_count = _warning_count + 1
151 else
152 _error_count = _error_count + 1
153 end
154 if opt_stop_on_first_error.value then check_errors
155 end
156
157 # Display an info
158 fun info(s: String, level: Int)
159 do
160 if level <= verbose_level then
161 print "{s}"
162 end
163 end
164
165 # Paths where to locate modules files
166 readable var _paths: Array[String] = new Array[String]
167
168 # List of module loaders
169 var _loaders: Array[ModuleLoader] = new Array[ModuleLoader]
170
171 # Global OptionContext
172 readable var _option_context: OptionContext = new OptionContext
173
174 # Option --warn
175 readable var _opt_warn: OptionCount = new OptionCount("Show warnings", "-W", "--warn")
176
177 # Option --path
178 readable var _opt_path: OptionArray = new OptionArray("Set include path for loaders (may be used more than once)", "-I", "--path")
179
180 # Option --log
181 readable var _opt_log: OptionBool = new OptionBool("Generate various log files", "--log")
182
183 # Option --log-dir
184 readable var _opt_log_dir: OptionString = new OptionString("Directory where to generate log files", "--log-dir")
185
186 # Option --only-metamodel
187 readable var _opt_only_metamodel: OptionBool = new OptionBool("Stop after meta-model processing", "--only-metamodel")
188
189 # Option --only-parse
190 readable var _opt_only_parse: OptionBool = new OptionBool("Only proceed to parse step of loaders", "--only-parse")
191
192 # Option --help
193 readable var _opt_help: OptionBool = new OptionBool("Show Help (This screen)", "-h", "-?", "--help")
194
195 # Option --version
196 readable var _opt_version: OptionBool = new OptionBool("Show version and exit", "--version")
197
198 # Option --verbose
199 readable var _opt_verbose: OptionCount = new OptionCount("Verbose", "-v", "--verbose")
200
201 # Option --stop-on-first-error
202 readable var _opt_stop_on_first_error: OptionBool = new OptionBool("Stop on first error", "--stop-on-first-error")
203
204 # Option --no-color
205 readable var _opt_no_color: OptionBool = new OptionBool("Do not use color to display errors and warnings", "--no-color")
206
207 # Verbose level
208 readable var _verbose_level: Int = 0
209
210 init
211 do
212 super
213 option_context.add_option(opt_warn, 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)
214 end
215
216 # Parse and process the options given on the command line
217 fun process_options
218 do
219 # init options
220 option_context.parse(args)
221
222 # Set verbose level
223 _verbose_level = opt_verbose.value
224
225 # Setup the paths value
226 paths.append(opt_path.value)
227
228 var path_env = once ("NIT_PATH".to_symbol).environ
229 if not path_env.is_empty then
230 paths.append(path_env.split_with(':'))
231 end
232
233 path_env = once ("NIT_DIR".to_symbol).environ
234 if not path_env.is_empty then
235 var libname = "{path_env}/lib"
236 if libname.file_exists then paths.add(libname)
237 end
238
239 var libname = "{sys.program_name.dirname}/../lib"
240 if libname.file_exists then paths.add(libname)
241
242 if opt_log_dir.value != null then _log_directory = opt_log_dir.value.as(not null)
243 if _opt_log.value then
244 # Make sure the output directory exists
245 log_directory.mkdir
246 end
247 end
248
249 # Load and process a module in a directory (or a parent directory).
250 # If the module is already loaded, just return it without further processing.
251 # If no module is found, just return null without complaining.
252 private fun try_to_load(module_name: Symbol, dir: MMDirectory): nullable MMModule
253 do
254 # Look in the module directory
255 for m in dir.modules do
256 if m.name == module_name then return m
257 end
258
259 # print "try to load {module_name} in {dir.name} {_loaders.length}"
260
261 for l in _loaders do
262 var dir2 = l.try_to_load_dir(module_name, dir)
263 if dir2 != null then
264 var m = try_to_load(module_name, dir2)
265 if m != null then
266 dir2.owner = m
267 dir.add_module(m)
268 return m
269 end
270 end
271
272 if l.can_handle(module_name, dir) then
273 var full_name = dir.full_name_for(module_name)
274 if _processing_modules.has(full_name) then
275 # FIXME: Generate better error
276 fatal_error(null, "Error: Dependency loop for module {full_name}")
277 end
278 _processing_modules.add(full_name)
279 var m = l.load_and_process_module(self, module_name, dir)
280 _processing_modules.remove(full_name)
281 #if m != null then print "loaded {m.name} in {m.directory.name} -> {m.full_name} ({m.full_name.object_id.to_hex})"
282 dir.add_module(m)
283 return m
284 end
285 end
286 return null
287 end
288
289 # List of module currently processed.
290 # Used to prevent dependence loops.
291 var _processing_modules: HashSet[Symbol] = new HashSet[Symbol]
292
293 # Locate, load and analysis a module (and its supermodules) from its file name.
294 # If the module is already loaded, just return it without further processing.
295 # Beware, the files are automatically considered root of their directory.
296 fun get_module_from_filename(filename: String): MMModule
297 do
298 var path = filename.dirname
299 var module_name = filename.basename(".nit").to_symbol
300
301 var dir = directory_for(path)
302
303 if module_name.to_s == filename then
304 # It's just a modulename
305 # look for it in the path directory "."
306 var m = try_to_load(module_name, dir)
307 if m != null then return m
308
309 # Else look for it in the path
310 return get_module(module_name, null)
311 end
312
313 if not filename.file_exists then
314 fatal_error(null, "Error: File {filename} not found.")
315 abort
316 end
317
318 # Try to load the module where mentionned
319 var m = try_to_load(module_name, dir)
320 if m != null then return m
321
322 fatal_error(null, "Error: {filename} is not a NIT source module.")
323 abort
324 end
325
326 # Locate, load and analysis a module (and its supermodules).
327 # If the module is already loaded, just return it without further processing.
328 fun get_module(module_name: Symbol, from: nullable MMModule): MMModule
329 do
330 if from != null then
331 var dir: nullable MMDirectory = from.directory
332 while dir != null do
333 var m = try_to_load(module_name, dir)
334 if m != null then return m
335 dir = dir.parent
336 end
337 end
338
339 for p in paths do
340 var m = try_to_load(module_name, directory_for(p))
341 if m != null then return m
342 end
343 # FIXME: Generate better error
344 fatal_error(null, "Error: No ressource found for module {module_name}.")
345 abort
346 end
347
348 # Return the module directory associated with a given path
349 private fun directory_for(path: String): MMDirectory
350 do
351 if _path_dirs.has_key(path) then return _path_dirs[path]
352 var dir = new MMDirectory(path.to_symbol, path, null)
353 _path_dirs[path] = dir
354 return dir
355 end
356
357 # Association bwtween plain path and module directories
358 var _path_dirs: Map[String, MMDirectory] = new HashMap[String, MMDirectory]
359
360 # Register a new module loader
361 fun register_loader(ml: ModuleLoader) do _loaders.add(ml)
362 end
363
364 # A load handler know how to load a specific module type
365 class ModuleLoader
366 # Type of module loaded by the loader
367 type MODULE: MMModule
368
369 # Extension that the loadhandler accepts
370 fun file_type: String is abstract
371
372 # Try to load a new module directory
373 fun try_to_load_dir(dirname: Symbol, parent_dir: MMDirectory): nullable MMDirectory
374 do
375 var fname = "{parent_dir.path}/{dirname}/"
376 if not fname.file_exists then return null
377
378 var dir = new MMDirectory(parent_dir.full_name_for(dirname), fname, parent_dir)
379 return dir
380 end
381
382 # Can the loadhandler load a given module?
383 # Return the file found
384 fun can_handle(module_name: Symbol, dir: MMDirectory): Bool
385 do
386 var fname = "{dir.path}/{module_name}.{file_type}"
387 if fname.file_exists then return true
388 return false
389 end
390
391 # Load the module and process it
392 # filename is the result of can_handle
393 fun load_and_process_module(context: ToolContext, module_name: Symbol, dir: MMDirectory): MODULE
394 do
395 var filename = "{dir.path}/{module_name}.{file_type}"
396 var m = load_module(context, module_name, dir, filename)
397 if not context.opt_only_parse.value then process_metamodel(context, m)
398 return m
399 end
400
401 # Load an parse the module
402 private fun load_module(context: ToolContext, module_name: Symbol, dir: MMDirectory, filename: String): MODULE
403 do
404 var file: IFStream
405 if filename == "-" then
406 file = stdin
407 else
408 file = new IFStream.open(filename.to_s)
409 end
410
411 if file.eof then
412 context.fatal_error(null, "Error: Problem in opening file {filename}")
413 end
414 var m = parse_file(context, file, filename, module_name, dir)
415 if file != stdin then file.close
416 return m
417 end
418
419 # Parse the file to load a module
420 protected fun parse_file(context: ToolContext, file: IFStream, filename: String, module_name: Symbol, dir: MMDirectory): MODULE is abstract
421
422 # Process a parsed module
423 protected fun process_metamodel(context: ToolContext, mod: MODULE) is abstract
424 end