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