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