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