1 #!/usr/bin/env python 2 3 """ 4 The micropython package for processing Python source code. The code originates 5 from the simplify package but has had various details related to that package 6 removed. 7 8 Copyright (C) 2006, 2007, 2008 Paul Boddie <paul@boddie.org.uk> 9 10 This program is free software; you can redistribute it and/or modify it under 11 the terms of the GNU General Public License as published by the Free Software 12 Foundation; either version 3 of the License, or (at your option) any later 13 version. 14 15 This program is distributed in the hope that it will be useful, but WITHOUT 16 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 17 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 18 details. 19 20 You should have received a copy of the GNU General Public License along with 21 this program. If not, see <http://www.gnu.org/licenses/>. 22 23 -------- 24 25 To use this module, an importer should be constructed and the load_from_file 26 method used. Here, the standard path for module searching is employed: 27 28 importer = Importer(sys.path) 29 importer.load_from_file(filename) 30 importer.vacuum() 31 32 Such importer objects are the most convenient mechanism through which the 33 functionality of the micropython package may be accessed. 34 """ 35 36 from micropython.common import * 37 import micropython.ast 38 import micropython.inspect 39 import micropython.table 40 import os 41 try: 42 set 43 except NameError: 44 from sets import Set as set 45 46 class Importer: 47 48 """ 49 An import machine, searching for and loading modules. In addition, this 50 class supports the generation of a program image. 51 """ 52 53 supported_optimisations = micropython.ast.Translation.supported_optimisations 54 55 def __init__(self, path=None, verbose=0): 56 57 """ 58 Initialise the importer with the given search 'path' - a list of 59 directories to search for Python modules. 60 61 The optional 'verbose' parameter causes output concerning the activities 62 of the object to be produced if set to a true value (not the default). 63 """ 64 65 self.path = path or [os.getcwd()] 66 self.verbose = verbose 67 self.modules = {} 68 self.loading = set() 69 70 # Remember the tables once generated. 71 72 self.objtable = None 73 self.paramtable = None 74 75 def vacuum(self): 76 77 "Tidy up the modules." 78 79 for name, module in self.modules.items(): 80 if module.loaded: 81 module.vacuum() 82 else: 83 del self.modules[name] 84 85 def get_modules(self): 86 87 "Return all modules known to the importer." 88 89 return self.modules.values() 90 91 def get_image(self, with_builtins=0, optimisations=None): 92 93 "Return a dictionary mapping modules to structures." 94 95 objtable = self.get_object_table() 96 paramtable = self.get_parameter_table() 97 98 image = [] 99 100 for module_name, module in self.modules.items(): 101 if not with_builtins and module_name == "__builtins__": 102 continue 103 104 # Fix the attributes. 105 106 module.finalise_attributes() 107 108 pos = len(image) 109 110 # Append constants to the image. 111 112 for const in module.constants(): 113 const.location = pos 114 image.append(const) 115 pos += 1 116 117 # Position the module in the image and make a translation. 118 119 module.location = pos 120 trans = micropython.ast.Translation(module, objtable, paramtable, self.modules.get("__builtins__"), optimisations) 121 122 # Add header details. 123 124 image.append(module) 125 pos += 1 126 127 # Append module attributes to the image. 128 129 attributes = module.module_attributes() 130 image += module.attributes_as_list() 131 pos += len(attributes.keys()) 132 133 # Append classes and functions to the image. 134 135 for obj in module.all_objects: 136 if isinstance(obj, micropython.inspect.Class): 137 138 # Fix the attributes. 139 140 obj.finalise_attributes() 141 142 # Position the class in the image. 143 144 obj.location = pos 145 146 # Add header details. 147 148 image.append(obj) 149 pos += 1 150 151 # Append class attributes to the image. 152 153 attributes = obj.class_attributes() 154 image += obj.attributes_as_list() 155 pos += len(attributes.keys()) 156 157 # Class-level code is generated separately. 158 # The code location is set within the code generation 159 # process for the module. 160 161 # NOTE: Generate module and function code here. 162 163 elif isinstance(obj, micropython.inspect.Function): 164 165 # Fix the attributes. 166 167 obj.finalise_attributes() 168 169 # Position the function in the image. 170 171 obj.location = pos 172 173 # Add header details. 174 175 image.append(obj) 176 pos += 1 177 178 # Append any default values to the image. 179 180 image += obj.default_attrs 181 pos += len(obj.default_attrs) 182 183 # Append the function code to the image. 184 185 obj.code_location = pos 186 code = trans.get_code(obj) 187 image += code 188 pos += len(code) 189 190 # Generate the default initialisation code. 191 192 code = trans.get_default_code(obj) 193 image += code 194 pos += len(code) 195 196 # Remember the position of the module code. 197 198 module.code_location = pos 199 200 # Append the module top-level code to the image. 201 202 code = trans.get_module_code() 203 image += code 204 pos += len(code) 205 206 return image 207 208 def get_object_table(self): 209 210 "Return a table with details of attributes for classes and modules." 211 212 if self.objtable is None: 213 t = self.objtable = micropython.table.Table() 214 for module in self.get_modules(): 215 t.add(module.full_name(), module.module_attributes()) 216 for obj in module.all_objects: 217 if isinstance(obj, micropython.inspect.Class): 218 t.add(obj.full_name(), obj.all_attributes()) 219 220 return self.objtable 221 222 def get_parameter_table(self): 223 224 "Return a table with details of parameters for functions and methods." 225 226 # Need the object table to get at class details. 227 228 objtable = self.get_object_table() 229 230 if self.paramtable is None: 231 t = self.paramtable = micropython.table.Table() 232 for module in self.get_modules(): 233 for obj in module.all_objects: 234 if isinstance(obj, micropython.inspect.Function): 235 t.add(obj.full_name(), obj.parameters()) 236 237 # Classes are callable, too. 238 # Take details of the appropriate __init__ method to make an 239 # entry for an instantiation function for the class. 240 241 elif isinstance(obj, micropython.inspect.Class): 242 t.add(obj.full_name(), obj.get_instantiator().parameters()) 243 244 return self.paramtable 245 246 # Import methods. 247 248 def find_in_path(self, name): 249 250 """ 251 Find the given module 'name' in the search path, returning None where no 252 such module could be found, or a 2-tuple from the 'find' method 253 otherwise. 254 """ 255 256 for d in self.path: 257 m = self.find(d, name) 258 if m: return m 259 return None 260 261 def find(self, d, name): 262 263 """ 264 In the directory 'd', find the given module 'name', where 'name' can 265 either refer to a single file module or to a package. Return None if the 266 'name' cannot be associated with either a file or a package directory, 267 or a 2-tuple from '_find_package' or '_find_module' otherwise. 268 """ 269 270 m = self._find_package(d, name) 271 if m: return m 272 m = self._find_module(d, name) 273 if m: return m 274 return None 275 276 def _find_module(self, d, name): 277 278 """ 279 In the directory 'd', find the given module 'name', returning None where 280 no suitable file exists in the directory, or a 2-tuple consisting of 281 None (indicating that no package directory is involved) and a filename 282 indicating the location of the module. 283 """ 284 285 name_py = name + os.extsep + "py" 286 filename = self._find_file(d, name_py) 287 if filename: 288 return None, filename 289 return None 290 291 def _find_package(self, d, name): 292 293 """ 294 In the directory 'd', find the given package 'name', returning None 295 where no suitable package directory exists, or a 2-tuple consisting of 296 a directory (indicating the location of the package directory itself) 297 and a filename indicating the location of the __init__.py module which 298 declares the package's top-level contents. 299 """ 300 301 filename = self._find_file(d, name) 302 if filename: 303 init_py = "__init__" + os.path.extsep + "py" 304 init_py_filename = self._find_file(filename, init_py) 305 if init_py_filename: 306 return filename, init_py_filename 307 return None 308 309 def _find_file(self, d, filename): 310 311 """ 312 Return the filename obtained when searching the directory 'd' for the 313 given 'filename', or None if no actual file exists for the filename. 314 """ 315 316 filename = os.path.join(d, filename) 317 if os.path.exists(filename): 318 return filename 319 else: 320 return None 321 322 def load(self, name, return_leaf=0): 323 324 """ 325 Load the module or package with the given 'name'. Return an object 326 referencing the loaded module or package, or None if no such module or 327 package exists. 328 """ 329 330 if self.modules.has_key(name) and self.modules[name].loaded: 331 #print "Cached (%s)" % name 332 return self.modules[name] 333 if self.verbose: 334 print "Loading", name 335 336 # Split the name into path components, and try to find the uppermost in 337 # the search path. 338 339 path = name.split(".") 340 m = self.find_in_path(path[0]) 341 if not m: 342 if self.verbose: 343 print "Not found (%s)" % path[0] 344 return None # NOTE: Import error. 345 d, filename = m 346 347 # Either acquire a reference to an already-imported module, or load the 348 # module from a file. 349 350 top = module = self.load_from_file(filename, path[0]) 351 352 # For hierarchical names, traverse each path component... 353 354 if len(path) > 1: 355 if not d: 356 if self.verbose: 357 print "No package (%s)" % filename 358 return None # NOTE: Import error (package not found). 359 else: 360 self.add_submodules(d, module) 361 362 path_so_far = path[:1] 363 for p in path[1:]: 364 path_so_far.append(p) 365 366 # Find the package or module concerned. 367 368 m = self.find(d, p) 369 if not m: 370 if self.verbose: 371 print "Not found (%s)" % p 372 return None # NOTE: Import error. 373 d, filename = m 374 module_name = ".".join(path_so_far) 375 376 # Either reference an imported module or load one from a file. 377 378 submodule = self.load_from_file(filename, module_name) 379 380 if d: 381 self.add_submodules(d, module) 382 383 # Store the submodule within its parent module. 384 385 module.set_module(p, submodule) 386 module = submodule 387 388 # Return either the deepest or the uppermost module. 389 390 if return_leaf: 391 return module 392 else: 393 return top 394 395 def load_from_file(self, name, module_name=None): 396 397 """ 398 Load the module with the given 'name' (which may be a full module path). 399 """ 400 401 if module_name is None: 402 module_name = "__main__" 403 404 module = self.add_module(module_name) 405 if not module.loaded and module not in self.loading: 406 self.loading.add(module) 407 #print "Parsing", name 408 module.parse(name) 409 #print "Done", name 410 self.loading.remove(module) 411 module.loaded = 1 412 413 # Record the module. 414 415 #print "Loaded", module_name, "with namespace", module.namespace.keys() 416 return module 417 418 def add_module(self, module_name): 419 420 """ 421 Return the module with the given 'module_name', adding a new module 422 object if one does not already exist. 423 """ 424 425 if not self.modules.has_key(module_name): 426 self.modules[module_name] = module = micropython.inspect.InspectedModule(module_name, self) 427 else: 428 module = self.modules[module_name] 429 return module 430 431 def add_submodules(self, pathname, module): 432 433 """ 434 Work around insufficient __all__ declarations and examine the directory 435 with the given 'pathname', adding submodules to the given 'module'. 436 """ 437 438 for filename in os.listdir(pathname): 439 submodule, ext = os.path.splitext(filename) 440 if ext not in ("", ".py"): 441 continue 442 module.set_module(submodule, self.add_module(module.name + "." + submodule)) 443 444 # vim: tabstop=4 expandtab shiftwidth=4