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