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