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