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 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 import micropython.ast 37 import micropython.inspect 38 import micropython.table 39 import os 40 try: 41 set 42 except NameError: 43 from sets import Set as set 44 45 class Importer: 46 47 "An import machine, searching for and loading modules." 48 49 def __init__(self, path=None): 50 51 """ 52 Initialise the importer with the given search 'path' - a list of 53 directories to search for Python modules. 54 """ 55 56 self.path = path or [os.getcwd()] 57 self.modules = {} 58 self.loading = set() 59 60 def vacuum(self): 61 62 "Tidy up the modules." 63 64 for name, module in self.modules.items(): 65 if module.loaded: 66 module.vacuum() 67 else: 68 del self.modules[name] 69 70 def get_modules(self): 71 72 "Return all modules known to the importer." 73 74 return self.modules.values() 75 76 def get_image(self, objtable=None, paramtable=None): 77 78 "Return a dictionary mapping modules to structures." 79 80 objtable = objtable or self.get_object_table() 81 paramtable = paramtable or self.get_parameter_table() 82 83 image = [] 84 85 for module_name, module in self.modules.items(): 86 pos = len(image) 87 88 # Position the module in the image and make a translation. 89 90 module.location = pos 91 trans = micropython.ast.Translation(module, objtable, paramtable) 92 93 # Add header details. 94 95 image.append(module) 96 pos += 1 97 98 # Append constants to the image. 99 100 for const in module.constants(): 101 const.location = pos 102 image.append(const) 103 pos += 1 104 105 # Append module attributes to the image. 106 107 attributes = module.module_attributes() 108 109 for name in module.module_attribute_names(): 110 attr = attributes[name] 111 image.append(attr) 112 pos += 1 113 114 # Append classes and functions to the image. 115 116 for obj in module.all_objects: 117 if isinstance(obj, micropython.inspect.Class): 118 119 # Position the class in the image. 120 121 obj.location = pos 122 123 # Add header details. 124 125 image.append(obj) 126 pos += 1 127 128 # Append class attributes to the image. 129 130 attributes = obj.class_attributes() 131 132 for name in obj.class_attribute_names(): 133 attr = attributes[name] 134 image.append(attr) 135 pos += 1 136 137 # Append the class-level code to the image. 138 # NOTE: An extra optimisation would involve 139 # NOTE: pre-initialisation of attributes and no code being 140 # NOTE: generated here, or perhaps the pre-initialisation of 141 # NOTE: methods and only other attribute-related code being 142 # NOTE: generated here. 143 144 obj.code_location = obj.location = pos 145 code = trans.get_code(obj) 146 image += code 147 pos += len(code) 148 149 # NOTE: Generate module and function code here. 150 151 elif isinstance(obj, micropython.inspect.Function): 152 153 # Position the function in the image. 154 155 obj.location = pos 156 157 # Add header details. 158 159 image.append(obj) 160 pos += 1 161 162 # Append the function code to the image. 163 164 obj.code_location = obj.location = pos 165 code = trans.get_code(obj) 166 image += code 167 pos += len(code) 168 169 # Remember the position of the module code. 170 171 module.code_location = pos 172 173 # Append the module top-level code to the image. 174 175 code = trans.get_module_code() 176 image += code 177 pos += len(code) 178 179 return image 180 181 def get_object_table(self): 182 183 "Return a table with details of attributes for classes and modules." 184 185 t = micropython.table.Table() 186 for module in self.get_modules(): 187 t.add(module.full_name(), module.module_attributes()) 188 for obj in module.all_objects: 189 if isinstance(obj, micropython.inspect.Class): 190 t.add(obj.full_name(), obj.all_attributes()) 191 return t 192 193 def get_parameter_table(self): 194 195 "Return a table with details of parameters for functions and methods." 196 197 t = micropython.table.Table() 198 for module in self.get_modules(): 199 for obj in module.all_objects: 200 if isinstance(obj, micropython.inspect.Function): 201 t.add(obj.full_name(), obj.parameters()) 202 return t 203 204 # Import methods. 205 206 def find_in_path(self, name): 207 208 """ 209 Find the given module 'name' in the search path, returning None where no 210 such module could be found, or a 2-tuple from the 'find' method 211 otherwise. 212 """ 213 214 for d in self.path: 215 m = self.find(d, name) 216 if m: return m 217 return None 218 219 def find(self, d, name): 220 221 """ 222 In the directory 'd', find the given module 'name', where 'name' can 223 either refer to a single file module or to a package. Return None if the 224 'name' cannot be associated with either a file or a package directory, 225 or a 2-tuple from '_find_package' or '_find_module' otherwise. 226 """ 227 228 m = self._find_package(d, name) 229 if m: return m 230 m = self._find_module(d, name) 231 if m: return m 232 return None 233 234 def _find_module(self, d, name): 235 236 """ 237 In the directory 'd', find the given module 'name', returning None where 238 no suitable file exists in the directory, or a 2-tuple consisting of 239 None (indicating that no package directory is involved) and a filename 240 indicating the location of the module. 241 """ 242 243 name_py = name + os.extsep + "py" 244 filename = self._find_file(d, name_py) 245 if filename: 246 return None, filename 247 return None 248 249 def _find_package(self, d, name): 250 251 """ 252 In the directory 'd', find the given package 'name', returning None 253 where no suitable package directory exists, or a 2-tuple consisting of 254 a directory (indicating the location of the package directory itself) 255 and a filename indicating the location of the __init__.py module which 256 declares the package's top-level contents. 257 """ 258 259 filename = self._find_file(d, name) 260 if filename: 261 init_py = "__init__" + os.path.extsep + "py" 262 init_py_filename = self._find_file(filename, init_py) 263 if init_py_filename: 264 return filename, init_py_filename 265 return None 266 267 def _find_file(self, d, filename): 268 269 """ 270 Return the filename obtained when searching the directory 'd' for the 271 given 'filename', or None if no actual file exists for the filename. 272 """ 273 274 filename = os.path.join(d, filename) 275 if os.path.exists(filename): 276 return filename 277 else: 278 return None 279 280 def load(self, name, return_leaf=0): 281 282 """ 283 Load the module or package with the given 'name'. Return an object 284 referencing the loaded module or package, or None if no such module or 285 package exists. 286 """ 287 288 if self.modules.has_key(name) and self.modules[name].loaded: 289 #print "Cached (%s)" % name 290 return self.modules[name] 291 print "Loading", name 292 293 # Split the name into path components, and try to find the uppermost in 294 # the search path. 295 296 path = name.split(".") 297 m = self.find_in_path(path[0]) 298 if not m: 299 print "Not found (%s)" % path[0] 300 return None # NOTE: Import error. 301 d, filename = m 302 303 # Either acquire a reference to an already-imported module, or load the 304 # module from a file. 305 306 top = module = self.load_from_file(filename, path[0]) 307 308 # For hierarchical names, traverse each path component... 309 310 if len(path) > 1: 311 if not d: 312 print "No package (%s)" % filename 313 return None # NOTE: Import error (package not found). 314 else: 315 self.add_submodules(d, module) 316 317 path_so_far = path[:1] 318 for p in path[1:]: 319 path_so_far.append(p) 320 321 # Find the package or module concerned. 322 323 m = self.find(d, p) 324 if not m: 325 print "Not found (%s)" % p 326 return None # NOTE: Import error. 327 d, filename = m 328 module_name = ".".join(path_so_far) 329 330 # Either reference an imported module or load one from a file. 331 332 submodule = self.load_from_file(filename, module_name) 333 334 if d: 335 self.add_submodules(d, module) 336 337 # Store the submodule within its parent module. 338 339 module.set_module(p, submodule) 340 module = submodule 341 342 # Return either the deepest or the uppermost module. 343 344 if return_leaf: 345 return module 346 else: 347 return top 348 349 def load_from_file(self, name, module_name=None): 350 351 """ 352 Load the module with the given 'name' (which may be a full module path). 353 """ 354 355 if module_name is None: 356 module_name = "__main__" 357 358 module = self.add_module(module_name) 359 if not module.loaded and module not in self.loading: 360 self.loading.add(module) 361 #print "Parsing", name 362 module.parse(name) 363 #print "Done", name 364 self.loading.remove(module) 365 module.loaded = 1 366 367 # Record the module. 368 369 #print "Loaded", module_name, "with namespace", module.namespace.keys() 370 return module 371 372 def add_module(self, module_name): 373 374 """ 375 Return the module with the given 'module_name', adding a new module 376 object if one does not already exist. 377 """ 378 379 if not self.modules.has_key(module_name): 380 self.modules[module_name] = module = micropython.inspect.InspectedModule(module_name, self) 381 else: 382 module = self.modules[module_name] 383 return module 384 385 def add_submodules(self, pathname, module): 386 387 """ 388 Work around insufficient __all__ declarations and examine the directory 389 with the given 'pathname', adding submodules to the given 'module'. 390 """ 391 392 for filename in os.listdir(pathname): 393 submodule = os.path.splitext(filename)[0] 394 module.set_module(submodule, self.add_module(module.name + "." + submodule)) 395 396 # vim: tabstop=4 expandtab shiftwidth=4