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, 2009, 2010 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. Here, the standard path 26 for module searching is employed: 27 28 importer = Importer(sys.path) 29 30 To generate programs, the above importer should be supplied in the 31 initialisation of a program instance, and then various methods are called: 32 33 program = Program(importer) 34 image = program.get_raw_image() 35 36 Such importer and program objects are the most convenient mechanism through 37 which the functionality of the micropython package may be accessed. 38 """ 39 40 from micropython.common import ProcessingError, TableGenerationError 41 import micropython.ast 42 import micropython.data 43 import micropython.opt 44 import micropython.inspect 45 import micropython.table 46 import os 47 48 try: 49 set 50 except NameError: 51 from sets import Set as set 52 53 class Program: 54 55 "This class supports the generation of a program image." 56 57 supported_optimisations = micropython.opt.Optimiser.supported_optimisations 58 59 def __init__(self, importer, optimisations=None): 60 61 """ 62 Initialise the program representation with an 'importer' which is able 63 to locate and load Python modules. 64 65 The optional 'optimisations' cause certain techniques to be used in 66 reducing program size and improving program efficiency. 67 """ 68 69 self.importer = importer 70 self.optimisations = optimisations or set() 71 72 # Remember the tables once generated. 73 74 self.objtable = None 75 self.paramtable = None 76 77 # Main program information. 78 79 self.code = None 80 self.code_location = None 81 82 def get_importer(self): 83 return self.importer 84 85 # Access to finalised program information. 86 87 def finalise(self): 88 89 "Finalise the program." 90 91 # Need the tables to finalise. 92 93 objtable = self.get_object_table() 94 self.get_parameter_table() 95 96 self.importer.vacuum(objtable) 97 self.importer.finalise() 98 99 # Now remove unneeded things from the tables. 100 101 self.get_object_table(reset=1) 102 self.get_parameter_table(reset=1) 103 104 def get_image(self, with_builtins=0): 105 106 """ 107 Return the program image including built-in objects if 'with_builtins' 108 is specified and set to a true value. 109 """ 110 111 if self.code is not None: 112 return self.code 113 114 # Optimise and regenerate the object table. 115 116 self.finalise() 117 self.code = [] 118 119 # Append constants to the image. 120 121 for const in self.importer.constants(): 122 self.code.append(const) 123 124 last_module = self.importer.modules_ordered[-1] 125 126 for module in self.importer.modules_ordered: 127 suppress_builtins = not with_builtins and module.name == "__builtins__" 128 129 # Position the module in the image and make a translation. 130 131 trans = micropython.ast.Translation(module, self) 132 133 # Add header details. 134 135 self.code.append(module) 136 137 # Append module attributes to the image. 138 139 attributes = module.module_attributes() 140 self.code += module.attributes_as_list() 141 142 # Append classes and functions to the image. 143 144 for obj in module.all_objects: 145 if isinstance(obj, micropython.inspect.Class): 146 147 # Add header details. 148 149 self.code.append(obj) 150 151 # Append class attributes to the image. 152 153 attributes = obj.class_attributes() 154 self.code += obj.attributes_as_list() 155 156 # Omit built-in function code where requested. 157 158 if suppress_builtins and obj.astnode.doc is None: 159 continue 160 161 # Generate the instantiator/initialiser. 162 # Append the function code to the image. 163 164 code = trans.get_instantiator_code(obj) 165 self.code += code 166 167 # Class-level code is generated separately at the module 168 # level, and the code location is set within the code 169 # generation process for the module. 170 171 elif isinstance(obj, micropython.inspect.Function): 172 173 # Add header details. 174 175 self.code.append(obj) 176 177 # Append any default values to the image. 178 # Only do this for functions which are not dynamic. 179 180 if not obj.is_dynamic(): 181 self.code += obj.default_attrs 182 183 # Omit built-in function code where requested. 184 185 if suppress_builtins and obj.astnode.doc is None: 186 pass 187 188 # Append the function code to the image. 189 190 else: 191 code = trans.get_code(obj) 192 self.code += code 193 194 # Omit built-in module code where requested. 195 196 if suppress_builtins: 197 pass 198 199 # Append the module top-level code to the image. 200 201 else: 202 code = trans.get_module_code() 203 self.code += code 204 205 return self.code 206 207 def get_raw_image(self, architecture=None, with_builtins=0): 208 209 "Return the raw image representation of the program." 210 211 architecture = architecture or micropython.rsvp 212 213 self.get_image(with_builtins) 214 215 objtable = self.get_object_table() 216 paramtable = self.get_parameter_table() 217 218 # Position the objects. 219 220 pos = 0 221 222 for item in self.code: 223 arch_item = architecture.get_object(item) 224 225 # Get the raw version for the architecture. 226 227 if arch_item is not None: 228 pos = arch_item.set_location(pos, with_builtins) 229 else: 230 pos += 1 231 232 # Generate the raw code. 233 234 self.raw_code = [] 235 236 for item in self.code: 237 arch_item = architecture.get_object(item) 238 239 # Get the raw version for the architecture. 240 241 if arch_item is not None: 242 self.raw_code += arch_item.as_raw(objtable, paramtable, with_builtins) 243 arch_item.finalise_location(with_builtins) 244 else: 245 self.raw_code.append(item) 246 247 # Fix the module locations. 248 249 for module in self.importer.modules_ordered: 250 251 if not with_builtins and module.name == "__builtins__": 252 continue 253 254 module.code_location = module.blocks[0].location 255 256 self.code_location = self.importer.modules["__main__"].code_location 257 return self.raw_code 258 259 def get_object_table(self, reset=0): 260 261 "Return a table with details of attributes for classes and modules." 262 263 if self.objtable is None or reset: 264 265 t = self.objtable = micropython.table.ObjectTable() 266 for module in self.importer.get_modules(): 267 t.add(module.full_name(), module.module_attributes()) 268 269 # Add class and instance attributes for all classes, together 270 # with descendant information. 271 272 for obj in module.all_objects: 273 if isinstance(obj, micropython.inspect.Class): 274 275 # Prevent ambiguous classes. 276 277 full_name = obj.full_name() 278 name = obj.name 279 280 if module.has_key(name) and module[name].defines_ambiguous_class(): 281 raise TableGenerationError, "Class %r in module %r is ambiguously defined." % (name, module.full_name()) 282 283 # Define a table entry for the class. 284 285 attributes = {full_name : obj} 286 attributes.update(obj.all_attributes()) 287 attributes.update(obj.all_descendants()) 288 t.add(full_name, attributes) 289 290 return self.objtable 291 292 def get_parameter_table(self, reset=0): 293 294 "Return a table with details of parameters for functions and methods." 295 296 # Need the object table to get at class details. 297 298 if self.paramtable is None or reset: 299 t = self.paramtable = micropython.table.ParameterTable() 300 301 # Visit each module, getting function and method details. 302 303 for module in self.importer.get_modules(): 304 for obj in module.all_objects: 305 if isinstance(obj, micropython.inspect.Function): 306 t.add(obj.full_name(), obj.parameters()) 307 308 # Classes are callable, too. 309 # Take details of the appropriate __init__ method to make an 310 # entry for an instantiation function for the class. 311 312 elif isinstance(obj, micropython.inspect.Class): 313 t.add(obj.get_instantiator().full_name(), obj.get_instantiator().parameters()) 314 315 # Filter out all parameter table entries not referenced by keyword 316 # arguments. 317 318 keyword_names = set() 319 320 for module in self.importer.get_modules(): 321 keyword_names.update(module.keyword_names) 322 323 for function_name, parameters in t.table.items(): 324 for name in parameters.keys(): 325 if name in keyword_names: 326 break 327 else: 328 del t.table[function_name] 329 330 return self.paramtable 331 332 class Importer: 333 334 "An import machine, searching for and loading modules." 335 336 predefined_constants = { 337 "None" : None, 338 "True" : True, 339 "False" : False, 340 #"Ellipsis" : Ellipsis, 341 "NotImplemented" : NotImplemented 342 } 343 344 names_always_used = [ 345 "bool", "__call__", "__bool__" 346 ] 347 348 def __init__(self, path=None, verbose=0, optimisations=None): 349 350 """ 351 Initialise the importer with the given search 'path' - a list of 352 directories to search for Python modules. 353 354 The optional 'verbose' parameter causes output concerning the activities 355 of the object to be produced if set to a true value (not the default). 356 357 The optional 'optimisations' cause certain techniques to be used in 358 reducing program size and improving program efficiency. 359 """ 360 361 self.path = path or [os.getcwd()] 362 self.verbose = verbose 363 self.optimisations = optimisations or set() 364 365 self.modules = {} 366 self.modules_ordered = [] 367 self.loading = set() 368 369 # Constant records. 370 371 self.constant_values = {} 372 self.constant_list = None # cache for constants 373 self.init_predefined_constants() 374 375 # Attribute usage. 376 377 self.attributes_used = set() 378 self.name_references = {} 379 self.specific_name_references = {} 380 self.attribute_users_visited = set() 381 self.attributes_to_visit = {} 382 383 # Status information. 384 385 self.vacuumed = 0 386 self.finalised = 0 387 388 def get_modules(self): 389 390 "Return all modules known to the importer." 391 392 return self.modules.values() 393 394 def get_module(self, name): 395 396 "Return the module with the given 'name'." 397 398 return self.modules[name] 399 400 # General maintenance. 401 402 def vacuum(self, objtable): 403 404 "Tidy up the modules." 405 406 if self.vacuumed: 407 return 408 409 # Complete the list of attribute names used in the program. 410 411 self.collect_attributes(objtable) 412 413 for name, module in self.modules.items(): 414 if module.loaded: 415 module.vacuum() 416 else: 417 del self.modules[name] 418 419 self.vacuumed = 1 420 421 def finalise(self): 422 423 "Finalise the program (which should have been vacuumed first)." 424 425 if self.finalised: 426 return 427 428 # Reset any previously compiled information. 429 430 for module in self.get_modules(): 431 module.unfinalise() 432 433 # Prepare module information again. 434 435 for module in self.get_modules(): 436 module.finalise() 437 438 self.finalised = 1 439 440 # Name accounting. 441 442 def use_name(self, name, from_name): 443 444 """ 445 Register the given 'name' as being used in the program from within an 446 object with the specified 'from_name'. 447 """ 448 449 if not self.name_references.has_key(from_name): 450 self.name_references[from_name] = set() 451 self.name_references[from_name].add((name,)) 452 453 def use_names(self, names, from_name): 454 455 """ 456 Register the given 'names' as being used in the program from within an 457 object with the specified 'from_name'. 458 """ 459 460 if not self.name_references.has_key(from_name): 461 self.name_references[from_name] = set() 462 self.name_references[from_name].add(names) 463 464 def use_specific_name(self, objname, attrname, from_name): 465 466 """ 467 Register the given 'objname' (for an object) whose 'attrname' is being 468 used in the program from within an object with the specified 469 'from_name'. 470 """ 471 472 if not self.specific_name_references.has_key(from_name): 473 self.specific_name_references[from_name] = set() 474 self.specific_name_references[from_name].add((objname, attrname)) 475 476 # Name accounting products. 477 478 def uses_attribute(self, objname, name): 479 480 """ 481 Return whether the attribute of the object with the given 'objname' 482 having the given 'name' is used as an attribute in the program. 483 """ 484 485 return (objname + "." + name) in self.attributes_used 486 487 def use_attribute(self, objname, name): 488 489 """ 490 Indicate that in the object with the given 'objname', the attribute of 491 the given 'name' is used. 492 """ 493 494 self.attributes_used.add(objname + "." + name) 495 496 def use_object(self, objname): 497 498 "Indicate that the object with the given 'objname' is used." 499 500 self.attributes_used.add(objname) 501 502 def collect_attributes(self, objtable): 503 504 "Collect attribute references for the entire program." 505 506 # Include names which may not be explicitly used in programs. 507 # NOTE: Potentially declare these when inspecting. 508 509 for attrname in self.names_always_used: 510 for objname in objtable.all_possible_objects([attrname]): 511 512 # Record attributes of objects for potential visiting. 513 514 self.add_attribute_to_visit(objname, attrname) 515 516 # Start with the "root" modules, finding referenced objects. 517 518 self._collect_attributes("__builtins__", objtable) 519 self._collect_attributes("__main__", objtable) 520 521 def add_attribute_to_visit(self, objname, attrname): 522 523 """ 524 Queue an attribute of the object with the given 'objname', having the 525 given 'attrname', to the list for potential visiting if the specified 526 object is actually referenced. 527 """ 528 529 if not self.attributes_to_visit.has_key(objname): 530 self.attributes_to_visit[objname] = set() 531 self.attributes_to_visit[objname].add(attrname) 532 533 def _collect_attributes(self, from_name, objtable): 534 535 """ 536 Given an object called 'from_name', find all names referenced from such 537 an object according to the register of names. 538 """ 539 540 if from_name in self.attribute_users_visited: 541 return 542 543 self.attribute_users_visited.add(from_name) 544 545 # Get name references and find possible objects which support such 546 # combinations of attribute names. 547 548 for names in self.name_references.get(from_name, []): 549 objnames = objtable.all_possible_objects(names) 550 if not objnames: 551 print "Warning: usage in %r finds no object supporting all attributes %r" % (from_name, names) 552 objnames = objtable.any_possible_objects(names) 553 if not objnames: 554 print "Warning: usage in %r finds no object supporting any attributes %r" % (from_name, names) 555 556 # For each suggested object, consider each attribute given by the 557 # names. 558 559 for objname in objnames: 560 for name in names: 561 562 # Visit attributes of objects known to be used. 563 564 if objname in self.attributes_used: 565 self.use_attribute(objname, name) 566 self._collect_attributes(objname + "." + name, objtable) 567 568 # Record attributes of other objects for potential visiting. 569 570 else: 571 self.add_attribute_to_visit(objname, name) 572 573 # Get specific name references and visit the referenced objects. 574 575 for objname, attrname in self.specific_name_references.get(from_name, []): 576 self.use_attribute(objname, attrname) 577 self._collect_attributes(objname + "." + attrname, objtable) 578 579 # Where the object has an __init__ attribute, assume that it is an 580 # initialiser which is called at some point, and collect attributes used 581 # in this initialiser. 582 583 if "__init__" in objtable.table.get(from_name, []): 584 self.use_attribute(from_name, "__init__") 585 self._collect_attributes(from_name + ".__init__", objtable) 586 587 # Visit attributes on objects not previously visited. 588 589 attributes_to_visit = self.attributes_to_visit.get(from_name, []) 590 591 if attributes_to_visit: 592 del self.attributes_to_visit[from_name] 593 594 for attrname in attributes_to_visit: 595 self.use_attribute(from_name, attrname) 596 self._collect_attributes(from_name + "." + attrname, objtable) 597 598 # Constant accounting. 599 600 def init_predefined_constants(self): 601 602 "Ensure the predefined constants." 603 604 for name, value in self.predefined_constants.items(): 605 self.make_constant(value) 606 607 def get_predefined_constant(self, name): 608 609 "Return the predefined constant for the given 'name'." 610 611 return self.make_constant(self.predefined_constants[name]) 612 613 def get_constant(self, value): 614 615 "Return a constant for the given 'value'." 616 617 const = micropython.data.Const(value) 618 return self.constant_values[const] 619 620 def get_constant_type_name(self, value): 621 return value.__class__.__name__ 622 623 def make_constant(self, value): 624 625 "Make and return a constant for the given 'value'." 626 627 # Ensure the presence of the constant's type. 628 629 name = self.get_constant_type_name(value) 630 if self.modules.has_key("__builtins__"): 631 attr = self.modules["__builtins__"].get(name) 632 633 # Make a constant object and return it. 634 635 const = micropython.data.Const(value) 636 if not self.constant_values.has_key(const): 637 self.constant_values[const] = const 638 return self.constant_values[const] 639 640 def constants(self): 641 642 "Return a list of constants." 643 644 if self.constant_list is None: 645 self.constant_list = list(self.constant_values.values()) 646 647 return self.constant_list 648 649 # Import methods. 650 651 def find_in_path(self, name): 652 653 """ 654 Find the given module 'name' in the search path, returning None where no 655 such module could be found, or a 2-tuple from the 'find' method 656 otherwise. 657 """ 658 659 for d in self.path: 660 m = self.find(d, name) 661 if m: return m 662 return None 663 664 def find(self, d, name): 665 666 """ 667 In the directory 'd', find the given module 'name', where 'name' can 668 either refer to a single file module or to a package. Return None if the 669 'name' cannot be associated with either a file or a package directory, 670 or a 2-tuple from '_find_package' or '_find_module' otherwise. 671 """ 672 673 m = self._find_package(d, name) 674 if m: return m 675 m = self._find_module(d, name) 676 if m: return m 677 return None 678 679 def _find_module(self, d, name): 680 681 """ 682 In the directory 'd', find the given module 'name', returning None where 683 no suitable file exists in the directory, or a 2-tuple consisting of 684 None (indicating that no package directory is involved) and a filename 685 indicating the location of the module. 686 """ 687 688 name_py = name + os.extsep + "py" 689 filename = self._find_file(d, name_py) 690 if filename: 691 return None, filename 692 return None 693 694 def _find_package(self, d, name): 695 696 """ 697 In the directory 'd', find the given package 'name', returning None 698 where no suitable package directory exists, or a 2-tuple consisting of 699 a directory (indicating the location of the package directory itself) 700 and a filename indicating the location of the __init__.py module which 701 declares the package's top-level contents. 702 """ 703 704 filename = self._find_file(d, name) 705 if filename: 706 init_py = "__init__" + os.path.extsep + "py" 707 init_py_filename = self._find_file(filename, init_py) 708 if init_py_filename: 709 return filename, init_py_filename 710 return None 711 712 def _find_file(self, d, filename): 713 714 """ 715 Return the filename obtained when searching the directory 'd' for the 716 given 'filename', or None if no actual file exists for the filename. 717 """ 718 719 filename = os.path.join(d, filename) 720 if os.path.exists(filename): 721 return filename 722 else: 723 return None 724 725 def load(self, name, return_leaf=0): 726 727 """ 728 Load the module or package with the given 'name'. Return an object 729 referencing the loaded module or package, or None if no such module or 730 package exists. 731 """ 732 733 if return_leaf: 734 name_for_return = name 735 else: 736 name_for_return = name.split(".")[0] 737 738 if self.modules.has_key(name) and self.modules[name].loaded: 739 #print "Cached (%s)" % name 740 return self.modules[name_for_return] 741 742 if self.verbose: 743 print "Loading", name 744 745 # Split the name into path components, and try to find the uppermost in 746 # the search path. 747 748 path = name.split(".") 749 m = self.find_in_path(path[0]) 750 if not m: 751 if self.verbose: 752 print "Not found (%s)" % path[0] 753 return None # NOTE: Import error. 754 d, filename = m 755 756 # Either acquire a reference to an already-imported module, or load the 757 # module from a file. 758 759 top = module = self.load_from_file(filename, path[0]) 760 761 # For hierarchical names, traverse each path component... 762 763 if len(path) > 1: 764 if not d: 765 if self.verbose: 766 print "No package (%s)" % filename 767 return None # NOTE: Import error (package not found). 768 else: 769 self.add_submodules(d, module) 770 771 path_so_far = path[:1] 772 for p in path[1:]: 773 path_so_far.append(p) 774 775 # Find the package or module concerned. 776 777 m = self.find(d, p) 778 if not m: 779 if self.verbose: 780 print "Not found (%s)" % p 781 return None # NOTE: Import error. 782 d, filename = m 783 module_name = ".".join(path_so_far) 784 785 # Either reference an imported module or load one from a file. 786 787 submodule = self.load_from_file(filename, module_name) 788 789 if d: 790 self.add_submodules(d, module) 791 792 # Store the submodule within its parent module. 793 794 module.set_module(p, submodule) 795 module = submodule 796 797 # Return either the deepest or the uppermost module. 798 799 if return_leaf: 800 return module 801 else: 802 return top 803 804 def load_from_file(self, name, module_name=None): 805 806 """ 807 Load the module with the given 'name' (which may be a full module path). 808 """ 809 810 if module_name is None: 811 module_name = "__main__" 812 813 module = self.add_module(module_name) 814 if not module.loaded and module not in self.loading: 815 self.loading.add(module) 816 #print "Parsing", name 817 module.parse(name) 818 #print "Done", name 819 self.loading.remove(module) 820 module.loaded = 1 821 822 # Record the module. 823 824 self.use_object(module.full_name()) 825 #print "Loaded", module_name, "with namespace", module.namespace.keys() 826 return module 827 828 def add_module(self, module_name): 829 830 """ 831 Return the module with the given 'module_name', adding a new module 832 object if one does not already exist. 833 """ 834 835 if not self.modules.has_key(module_name): 836 self.modules[module_name] = module = micropython.inspect.InspectedModule(module_name, self) 837 self.modules_ordered.append(module) 838 else: 839 module = self.modules[module_name] 840 return module 841 842 def add_submodules(self, pathname, module): 843 844 """ 845 Work around insufficient __all__ declarations and examine the directory 846 with the given 'pathname', adding submodules to the given 'module'. 847 """ 848 849 for filename in os.listdir(pathname): 850 submodule, ext = os.path.splitext(filename) 851 if ext not in ("", ".py"): 852 continue 853 module.set_module(submodule, self.add_module(module.name + "." + submodule)) 854 855 # vim: tabstop=4 expandtab shiftwidth=4