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