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