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