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, 2011 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.data.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.data.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.data.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.data.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.data.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 452 attrnames = (name,) 453 usage = (attrnames,) 454 self.name_references[from_name].add((None, None, usage)) 455 456 def use_names(self, user, name, usage, from_name): 457 458 """ 459 For the given attribute 'user' (which may be None if no specific user is 460 given), register for the given 'name' the given attribute 'usage' 461 (combinations of attribute names), noting the scope of this usage as 462 being the program object with the specified 'from_name'. 463 """ 464 465 if not self.name_references.has_key(from_name): 466 self.name_references[from_name] = set() 467 468 self.name_references[from_name].add((user, name, usage)) 469 470 def use_specific_name(self, objname, attrname, from_name): 471 472 """ 473 Register the given 'objname' (for an object) whose 'attrname' is being 474 used in the program from within an object with the specified 475 'from_name'. 476 """ 477 478 if not self.specific_name_references.has_key(from_name): 479 self.specific_name_references[from_name] = set() 480 self.specific_name_references[from_name].add((objname, attrname)) 481 482 # Name accounting products. 483 484 def uses_attribute(self, objname, name): 485 486 """ 487 Return whether the attribute of the object with the given 'objname' 488 having the given 'name' is used as an attribute in the program. 489 """ 490 491 return (objname + "." + name) in self.attributes_used 492 493 def use_attribute(self, objname, name): 494 495 """ 496 Indicate that in the object with the given 'objname', the attribute of 497 the given 'name' is used. 498 """ 499 500 self.attributes_used.add(objname + "." + name) 501 502 def use_object(self, objname): 503 504 "Indicate that the object with the given 'objname' is used." 505 506 self.attributes_used.add(objname) 507 508 def collect_attributes(self, objtable): 509 510 "Collect attribute references for the entire program." 511 512 # Include names which may not be explicitly used in programs. 513 # NOTE: Potentially declare these when inspecting. 514 515 for attrname in self.names_always_used: 516 for objname in objtable.all_possible_objects([attrname]): 517 518 # Record attributes of objects for potential visiting. 519 520 self.add_attribute_to_visit(objname, attrname) 521 522 # Visit all modules, since some may employ initialisation code which has 523 # some kind of side-effect. 524 525 for name in self.modules.keys(): 526 self._collect_attributes(name, objtable) 527 528 def add_attribute_to_visit(self, objname, attrname): 529 530 """ 531 Queue an attribute of the object with the given 'objname', having the 532 given 'attrname', to the list for potential visiting if the specified 533 object is actually referenced. 534 """ 535 536 if not self.attributes_to_visit.has_key(objname): 537 self.attributes_to_visit[objname] = set() 538 self.attributes_to_visit[objname].add(attrname) 539 540 def _collect_attributes(self, from_name, objtable): 541 542 """ 543 Given an object called 'from_name', find all names referenced from such 544 an object according to the register of names. 545 """ 546 547 if from_name in self.attribute_users_visited: 548 return 549 550 self.attribute_users_visited.add(from_name) 551 552 # Get name references and find possible objects which support such 553 # combinations of attribute names. 554 555 for user, name, usage in self.name_references.get(from_name, []): 556 557 # Using all attribute names for a particular name, attempt to get 558 # specific object types. 559 560 all_objtypes = set() 561 562 for attrnames in usage: 563 objtypes = objtable.all_possible_objects_plus_status(attrnames) 564 if not objtypes: 565 print "Warning: usage in %r for %r finds no object supporting all attributes %r" % (from_name, name, attrnames) 566 objtypes = objtable.any_possible_objects_plus_status(attrnames) 567 if not objtypes: 568 print "Warning: usage in %r for %r finds no object supporting any attributes %r" % (from_name, name, attrnames) 569 570 all_objtypes.update(objtypes) 571 572 # Record the object types for generating guards. 573 574 if user is not None: 575 if not hasattr(user, "_attrtypes"): 576 user._attrtypes = {} 577 578 user._attrtypes[name] = all_objtypes 579 580 # For each suggested object type, consider each attribute given by 581 # the names. 582 583 for objname, is_static in all_objtypes: 584 for attrnames in usage: 585 for attrname in attrnames: 586 587 # Visit attributes of objects known to be used. 588 589 if objname in self.attributes_used: 590 self.use_attribute(objname, attrname) 591 self._collect_attributes(objname + "." + attrname, objtable) 592 593 # Record attributes of other objects for potential visiting. 594 595 else: 596 self.add_attribute_to_visit(objname, attrname) 597 598 # Get specific name references and visit the referenced objects. 599 600 for objname, attrname in self.specific_name_references.get(from_name, []): 601 self.use_attribute(objname, attrname) 602 self._collect_attributes(objname + "." + attrname, objtable) 603 604 # Where the object has an __init__ attribute, assume that it is an 605 # initialiser which is called at some point, and collect attributes used 606 # in this initialiser. 607 608 if "__init__" in objtable.table.get(from_name, []): 609 self.use_attribute(from_name, "__init__") 610 self._collect_attributes(from_name + ".__init__", objtable) 611 612 # Visit attributes on this object that were queued in case of the object 613 # being referenced. 614 615 attributes_to_visit = self.attributes_to_visit.get(from_name, []) 616 617 if attributes_to_visit: 618 del self.attributes_to_visit[from_name] 619 620 for attrname in attributes_to_visit: 621 self.use_attribute(from_name, attrname) 622 self._collect_attributes(from_name + "." + attrname, objtable) 623 624 # Constant accounting. 625 626 def init_predefined_constants(self): 627 628 "Ensure the predefined constants." 629 630 for name, value in self.predefined_constants.items(): 631 self.make_constant(value) 632 633 def get_predefined_constant(self, name): 634 635 "Return the predefined constant for the given 'name'." 636 637 return self.make_constant(self.predefined_constants[name]) 638 639 def get_constant(self, value): 640 641 "Return a constant for the given 'value'." 642 643 const = micropython.data.Const(value) 644 return self.constant_values[const] 645 646 def get_constant_type_name(self, value): 647 return value.__class__.__name__ 648 649 def make_constant(self, value): 650 651 "Make and return a constant for the given 'value'." 652 653 # Ensure the presence of the constant's type. 654 655 name = self.get_constant_type_name(value) 656 if self.modules.has_key("__builtins__"): 657 attr = self.modules["__builtins__"].get(name) 658 659 # Make a constant object and return it. 660 661 const = micropython.data.Const(value) 662 if not self.constant_values.has_key(const): 663 self.constant_values[const] = const 664 return self.constant_values[const] 665 666 def constants(self): 667 668 "Return a list of constants." 669 670 if self.constant_list is None: 671 self.constant_list = list(self.constant_values.values()) 672 673 return self.constant_list 674 675 # Import methods. 676 677 def find_in_path(self, name): 678 679 """ 680 Find the given module 'name' in the search path, returning None where no 681 such module could be found, or a 2-tuple from the 'find' method 682 otherwise. 683 """ 684 685 for d in self.path: 686 m = self.find(d, name) 687 if m: return m 688 return None 689 690 def find(self, d, name): 691 692 """ 693 In the directory 'd', find the given module 'name', where 'name' can 694 either refer to a single file module or to a package. Return None if the 695 'name' cannot be associated with either a file or a package directory, 696 or a 2-tuple from '_find_package' or '_find_module' otherwise. 697 """ 698 699 m = self._find_package(d, name) 700 if m: return m 701 m = self._find_module(d, name) 702 if m: return m 703 return None 704 705 def _find_module(self, d, name): 706 707 """ 708 In the directory 'd', find the given module 'name', returning None where 709 no suitable file exists in the directory, or a 2-tuple consisting of 710 None (indicating that no package directory is involved) and a filename 711 indicating the location of the module. 712 """ 713 714 name_py = name + os.extsep + "py" 715 filename = self._find_file(d, name_py) 716 if filename: 717 return None, filename 718 return None 719 720 def _find_package(self, d, name): 721 722 """ 723 In the directory 'd', find the given package 'name', returning None 724 where no suitable package directory exists, or a 2-tuple consisting of 725 a directory (indicating the location of the package directory itself) 726 and a filename indicating the location of the __init__.py module which 727 declares the package's top-level contents. 728 """ 729 730 filename = self._find_file(d, name) 731 if filename: 732 init_py = "__init__" + os.path.extsep + "py" 733 init_py_filename = self._find_file(filename, init_py) 734 if init_py_filename: 735 return filename, init_py_filename 736 return None 737 738 def _find_file(self, d, filename): 739 740 """ 741 Return the filename obtained when searching the directory 'd' for the 742 given 'filename', or None if no actual file exists for the filename. 743 """ 744 745 filename = os.path.join(d, filename) 746 if os.path.exists(filename): 747 return filename 748 else: 749 return None 750 751 def load(self, name, return_leaf=0): 752 753 """ 754 Load the module or package with the given 'name'. Return an object 755 referencing the loaded module or package, or None if no such module or 756 package exists. 757 """ 758 759 if return_leaf: 760 name_for_return = name 761 else: 762 name_for_return = name.split(".")[0] 763 764 if self.modules.has_key(name) and self.modules[name].loaded: 765 #print "Cached (%s)" % name 766 return self.modules[name_for_return] 767 768 if self.verbose: 769 print "Loading", name 770 771 # Split the name into path components, and try to find the uppermost in 772 # the search path. 773 774 path = name.split(".") 775 m = self.find_in_path(path[0]) 776 if not m: 777 if self.verbose: 778 print "Not found (%s)" % path[0] 779 return None # NOTE: Import error. 780 d, filename = m 781 782 # Either acquire a reference to an already-imported module, or load the 783 # module from a file. 784 785 top = module = self.load_from_file(filename, path[0]) 786 787 # For hierarchical names, traverse each path component... 788 789 if len(path) > 1: 790 if not d: 791 if self.verbose: 792 print "No package (%s)" % filename 793 return None # NOTE: Import error (package not found). 794 else: 795 self.add_submodules(d, module) 796 797 path_so_far = path[:1] 798 for p in path[1:]: 799 path_so_far.append(p) 800 801 # Find the package or module concerned. 802 803 m = self.find(d, p) 804 if not m: 805 if self.verbose: 806 print "Not found (%s)" % p 807 return None # NOTE: Import error. 808 d, filename = m 809 module_name = ".".join(path_so_far) 810 811 # Either reference an imported module or load one from a file. 812 813 submodule = self.load_from_file(filename, module_name) 814 815 if d: 816 self.add_submodules(d, module) 817 818 # Store the submodule within its parent module. 819 820 module.set_module(p, submodule) 821 module = submodule 822 823 # Return either the deepest or the uppermost module. 824 825 if return_leaf: 826 return module 827 else: 828 return top 829 830 def load_from_file(self, name, module_name=None): 831 832 """ 833 Load the module with the given 'name' (which may be a full module path). 834 """ 835 836 if module_name is None: 837 module_name = "__main__" 838 839 module = self.add_module(module_name) 840 if not module.loaded and module not in self.loading: 841 self.loading.add(module) 842 #print "Parsing", name 843 module.parse(name) 844 #print "Done", name 845 self.loading.remove(module) 846 module.loaded = 1 847 848 # Record the module. 849 850 self.use_object(module.full_name()) 851 #print "Loaded", module_name, "with namespace", module.namespace.keys() 852 return module 853 854 def add_module(self, module_name): 855 856 """ 857 Return the module with the given 'module_name', adding a new module 858 object if one does not already exist. 859 """ 860 861 if not self.modules.has_key(module_name): 862 self.modules[module_name] = module = micropython.inspect.InspectedModule(module_name, self) 863 self.modules_ordered.append(module) 864 else: 865 module = self.modules[module_name] 866 return module 867 868 def add_submodules(self, pathname, module): 869 870 """ 871 Work around insufficient __all__ declarations and examine the directory 872 with the given 'pathname', adding submodules to the given 'module'. 873 """ 874 875 for filename in os.listdir(pathname): 876 submodule, ext = os.path.splitext(filename) 877 if ext not in ("", ".py"): 878 continue 879 module.set_module(submodule, self.add_module(module.name + "." + submodule)) 880 881 # vim: tabstop=4 expandtab shiftwidth=4