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