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