1 #!/usr/bin/env python 2 3 """ 4 Inspect source files, obtaining details of classes and attributes. 5 6 Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 21 -------- 22 23 The results of inspecting a module are as follows: 24 25 Constants 26 --------- 27 28 All constants identified within the code shall be registered. 29 30 Classes 31 ------- 32 33 All global classes shall be registered; local classes (within functions) or 34 nested classes (within classes) are not currently registered. 35 36 Base classes must be detected and constant. 37 38 All classes without bases are made to inherit from __builtins__.object in order 39 to support some standard methods. 40 41 Functions 42 --------- 43 44 All functions and lambda definitions shall be registered. 45 46 Namespaces 47 ---------- 48 49 Modules define their own "global" namespace, within which classes, functions 50 and lambda definitions establish a hierarchy of namespaces. 51 52 Only local, global and built-in namespaces are recognised; closures are not 53 supported. 54 55 Assignments 56 ----------- 57 58 Name assignment and attribute assignment involving modules and classes cause 59 names to be associated with values within namespaces. 60 61 Any assignments within loops are considered to cause the targets of such 62 assignments to provide non-constant values. 63 64 Assignments to names are only really considered to cause the targets of such 65 assignments to provide constant values if the targets reside in class 66 namespaces, subject to the above conditions. 67 68 Assignments to names within functions are not generally considered to cause the 69 targets of such assignments to provide constant values since functions can be 70 invoked many times with different inputs. This affects particularly the 71 definition of functions or lambdas within functions. However, there may be 72 benefits in considering a local to be constant within a single invocation. 73 """ 74 75 from micropython.common import ASTVisitor, operator_functions 76 from micropython.data import * 77 from micropython.errors import * 78 import compiler.ast 79 import sys 80 81 class NullBranch(compiler.ast.AttributeUser): 82 83 "A class representing an attribute user for a non-existent branch." 84 85 pass 86 87 # Program visitors. 88 89 class InspectedModule(ASTVisitor, Module): 90 91 """ 92 An inspected module, providing core details via the Module superclass, but 93 capable of being used as an AST visitor. 94 95 A module can be inspected through the invocation of the following methods in 96 order: 97 98 1. parse 99 2. process 100 3. vacuum 101 4. finalise 102 103 A module importer can be expected to perform these invocations. 104 """ 105 106 def __init__(self, name, importer): 107 108 """ 109 Initialise this visitor with a module 'name' and an 'importer' which is 110 used to provide access to other modules when required. 111 """ 112 113 Module.__init__(self, name, importer) 114 self.visitor = self 115 116 # Import machinery links. 117 118 self.optimisations = self.importer.optimisations 119 self.builtins = self.importer.modules.get("__builtins__") 120 self.loaded = False 121 self.completed = False 122 123 # Current expression state. 124 125 self.expr = None 126 self.in_assignment = False # For slice and subscript handling. 127 128 # Namespace state. 129 130 self.in_method = False # Find instance attributes in all methods. 131 self.in_function = False # Note function presence, affecting definitions. 132 self.in_loop = False # Note loop "membership", affecting assignments. 133 self.namespaces = [] 134 self.functions = [] 135 136 def parse(self, filename): 137 138 "Parse the file having the given 'filename'." 139 140 self.astnode = module = compiler.parseFile(filename) 141 142 # Detect and record imports and globals declared in the module. 143 144 self.process_structure(module) 145 146 def complete(self): 147 if not self.completed: 148 self.completed = True 149 self.process() 150 if self.importer.verbose: 151 print >>sys.stderr, "Completed import of", self.full_name() 152 153 def process(self): 154 return self.process_module(self.astnode) 155 156 def process_module(self, module): 157 158 """ 159 Process the given 'module', visiting module-level code and function 160 code. 161 """ 162 163 # Add __name__ to the namespace. 164 165 self.store("__name__", self._visitConst(self.full_name())) 166 167 # Visit module-level code, also recording global names. 168 169 processed = self.dispatch(module) 170 171 self.finalise_attribute_usage() 172 173 # Visit functions. 174 175 self.process_functions() 176 177 # Add references to other modules declared using the __all__ global. 178 179 if self.has_key("__all__"): 180 all = self["__all__"] 181 if isinstance(all, compiler.ast.List): 182 for n in all.nodes: 183 self.store(n.value, self.importer.add_module(self.name + "." + n.value)) 184 185 return processed 186 187 def process_functions(self): 188 189 """ 190 Process all function bodies. Deferred imports may occur during this 191 process. 192 """ 193 194 # Then, visit each function, recording other names. This happens to 195 # work for lambda definitions inside functions since they are added to 196 # the end of self.functions and are thus visited as the iteration 197 # reaches the end of the original list. 198 199 for node, namespaces in self.functions: 200 self._visitFunctionBody(node, namespaces) 201 namespaces[-1].finalise_attribute_usage() 202 203 def process_structure(self, node): 204 205 """ 206 Within the given 'node', process global declarations, adjusting the 207 module namespace, and import statements, building a module dependency 208 hierarchy. 209 """ 210 211 for n in node.getChildNodes(): 212 213 # Module global detection. 214 215 if isinstance(n, compiler.ast.Global): 216 for name in n.names: 217 218 # Each name may potentially be assigned many times. 219 # We don't try and find out the specifics at this point and 220 # just indicate that the name cannot be relied upon for 221 # various observations. 222 223 self.modify_name(name) 224 225 # Module import declarations. 226 227 elif isinstance(n, compiler.ast.From): 228 229 # Load the mentioned module. 230 231 self.record_import(n.modname, n) 232 233 # Speculatively load modules for names beneath the module. 234 235 for name, alias in n.names: 236 modname = n.modname + "." + name 237 self.record_import(modname, n) 238 239 elif isinstance(n, compiler.ast.Import): 240 241 # Load the mentioned module. 242 243 for name, alias in n.names: 244 self.record_import(name, n) 245 246 # Nodes using operator module functions. 247 248 elif operator_functions.has_key(n.__class__.__name__) or \ 249 isinstance(n, (compiler.ast.AugAssign, compiler.ast.Compare)): 250 251 n._module = self.importer.load("operator") 252 253 else: 254 self.process_structure(n) 255 256 def get_module_paths(self, name): 257 258 """ 259 Return the paths of modules leading to the module having the given 260 'name'. 261 """ 262 263 names = [] 264 parts = [] 265 for part in name.split("."): 266 parts.append(part) 267 names.append(".".join(parts)) 268 return names 269 270 def record_import(self, name, node): 271 272 """ 273 Record an import of a module with the given 'name' occurring at the 274 given 'node'. 275 """ 276 277 module = self.importer.load(name, 1, importer=node) 278 if module and not module.loaded: 279 self.importer.circular_imports.add(module) 280 281 def complete_import(self, name, return_leaf): 282 283 """ 284 Complete the import of the module with the given 'name', returning the 285 module itself if 'return_leaf' is a true value, or returning the root of 286 the module hierarchy if 'return_leaf' is a false value. 287 """ 288 289 top = module = None 290 291 for modname in self.get_module_paths(name): 292 293 # Attempt to get the module, returning None for non-existent 294 # modules. 295 296 try: 297 module = self.importer.get_module(modname) 298 except KeyError: 299 return None 300 301 if module: 302 module.complete() 303 304 if top is None: 305 top = module 306 307 if return_leaf: 308 return module 309 else: 310 return top 311 312 def vacuum(self): 313 314 """ 315 Vacuum the module namespace, removing unreferenced objects and unused 316 names. 317 """ 318 319 if self.should_optimise_unused_objects(): 320 self.vacuum_object(self) 321 322 all_objects = list(self.all_objects) 323 324 for obj in all_objects: 325 self.vacuum_object(obj) 326 327 def vacuum_object(self, obj, delete_all=0): 328 329 "Vacuum the given object 'obj'." 330 331 # Get all constant objects in apparent use. 332 333 if delete_all: 334 obj_objects = set() 335 else: 336 obj_objects = [] 337 for name, attr in obj.items_for_vacuum(): 338 339 # Get constant objects for attributes in use. 340 341 if self.importer.uses_attribute(obj.full_name(), name) and \ 342 attr is not None and attr.is_constant(): 343 344 value = attr.get_value() 345 obj_objects.append(value) 346 347 # Now vacuum unused attributes and objects not in use. 348 349 for name, attr in obj.items_for_vacuum(): 350 351 # Only consider deleting entire unused objects or things accessible 352 # via names which are never used. 353 354 if delete_all or not self.importer.uses_attribute(obj.full_name(), name): 355 obj.vacuum_item(name) 356 357 # Delete any unambiguous attribute value. Such values can only 358 # have been defined within the object and therefore are not 359 # redefined by other code regions. 360 361 if attr is not None and attr.is_constant(): 362 value = attr.get_value() 363 364 # The value must have this object as a parent. 365 # However, it must not be shared by several names. 366 367 if value is not obj and value.parent is obj and \ 368 value in self.all_objects and value not in obj_objects: 369 370 self.all_objects.remove(value) 371 372 # Delete class contents and lambdas from functions. 373 374 self.vacuum_object(value, 1) 375 376 def unfinalise(self): 377 378 "Reset finalised information for the module." 379 380 for obj in self.all_objects: 381 obj.unfinalise_attributes() 382 383 def finalise(self, objtable): 384 385 "Finalise the module." 386 387 for obj in self.all_objects: 388 obj.finalise(objtable) 389 390 self.finalise_users(objtable) 391 392 def add_object(self, obj, any_scope=0): 393 394 """ 395 Record 'obj' if non-local or if the optional 'any_scope' is set to a 396 true value. 397 """ 398 399 if any_scope or not (self.namespaces and isinstance(self.namespaces[-1], Function)): 400 self.all_objects.add(obj) 401 402 # Optimisation tests. 403 404 def should_optimise_unused_objects(self): 405 return "unused_objects" in self.optimisations 406 407 # Namespace methods. 408 409 def in_class(self, namespaces=None): 410 namespaces = namespaces or self.namespaces 411 return len(namespaces) > 1 and isinstance(namespaces[-2], Class) 412 413 def store(self, name, obj): 414 415 "Record attribute or local 'name', storing 'obj'." 416 417 # Store in the module. 418 419 if not self.namespaces: 420 if self.in_loop and self.used_in_scope(name, "builtins"): 421 raise InspectError("Name %r already used as a built-in." % name) 422 else: 423 self.set(name, obj, not self.in_loop) 424 425 # Or store locally. 426 427 else: 428 locals = self.namespaces[-1] 429 430 if self.in_loop and locals.used_in_scope(name, "global") and not name in locals.globals: 431 raise InspectError("Name %r already used as global." % name) 432 elif self.in_loop and locals.used_in_scope(name, "builtins"): 433 raise InspectError("Name %r already used as a built-in." % name) 434 else: 435 locals.set(name, obj, not self.in_loop) 436 437 def store_lambda(self, obj): 438 439 "Store a lambda function 'obj'." 440 441 self.add_object(obj) 442 self.get_namespace().add_lambda(obj) 443 444 def store_module_attr(self, name, module): 445 446 """ 447 Record module attribute 'name' in the given 'module' using the current 448 expression. 449 """ 450 451 module.set(name, self.expr, 0) 452 self.use_specific_attribute(module.full_name(), name) 453 454 def store_class_attr(self, name, cls): 455 456 """ 457 Record class attribute 'name' in the given class 'cls' using the current 458 expression. 459 """ 460 461 cls.set(name, self.expr, 0) 462 self.use_specific_attribute(cls.full_name(), name) 463 464 def store_instance_attr(self, name, tentative=False): 465 466 """ 467 Record instance attribute 'name' in the current class. If 'tentative' is 468 set to a true value, the instance attribute will be discarded if a class 469 attribute is observed. 470 """ 471 472 if self.in_method: 473 474 # Current namespace is the function. 475 # Previous namespace is the class. 476 477 cls = self.namespaces[-2] 478 cls.add_instance_attribute(name, tentative) 479 480 # NOTE: The instance attribute, although defined in a specific 481 # NOTE: class, obviously appears in all descendant classes. 482 483 self.use_specific_attribute(cls.full_name(), name) 484 485 def get_namespace(self): 486 487 "Return the parent (or most recent) namespace currently exposed." 488 489 return (self.namespaces[-1:] or [self])[0] 490 491 get_unit = get_namespace # compatibility method for error handling 492 493 def use_name(self, name, node=None, value=None, ns=None): 494 495 """ 496 Use the given 'name' within the current namespace/unit, either in 497 conjunction with a particular object (if 'node' is specified and not 498 None) or unconditionally. 499 """ 500 501 unit = self.get_namespace() 502 503 # Handle attribute usage situations within the current unit. 504 505 if node is not None and isinstance(node, compiler.ast.Name) and ns is unit: 506 self.use_attribute(node.name, name, value) 507 508 # For general name usage, declare usage of the given name from this 509 # particular unit. 510 511 else: 512 self.importer.use_name(name, unit.full_name(), value) 513 514 def use_constant(self, const): 515 516 "Use the given 'const' within the current namespace/unit." 517 518 unit = self.get_namespace() 519 self.importer.use_constant(const, unit.full_name()) 520 521 # Attribute usage methods. 522 # These are convenience methods which refer to the specific namespace's 523 # implementation of these operations. 524 525 def new_branchpoint(self, loop_node=None): 526 self.get_namespace()._new_branchpoint(loop_node) 527 528 def new_branch(self, node): 529 self.get_namespace()._new_branch(node) 530 531 def abandon_branch(self): 532 self.get_namespace()._abandon_branch() 533 534 def suspend_broken_branch(self): 535 self.get_namespace()._suspend_broken_branch() 536 537 def suspend_continuing_branch(self): 538 self.get_namespace()._suspend_continuing_branch() 539 540 def shelve_branch(self): 541 self.get_namespace()._shelve_branch() 542 543 def merge_branches(self): 544 self.get_namespace()._merge_branches() 545 546 def resume_broken_branches(self): 547 self.get_namespace()._resume_broken_branches() 548 549 def resume_continuing_branches(self): 550 self.get_namespace()._resume_continuing_branches() 551 552 def resume_abandoned_branches(self): 553 self.get_namespace()._resume_abandoned_branches() 554 555 def define_attribute_user(self, node): 556 557 """ 558 Define 'node' as the user of attributes, indicating the point where the 559 user is defined. 560 """ 561 562 self.get_namespace()._define_attribute_user(node) 563 564 def use_attribute(self, name, attrname, value=None): 565 566 """ 567 Note usage on the attribute user 'name' of the attribute 'attrname', 568 noting an assignment if 'value' is specified. 569 """ 570 571 return self.get_namespace()._use_attribute(name, attrname, value) 572 573 def use_specific_attribute(self, objname, attrname, from_name=None): 574 575 """ 576 Note usage on the object having the given 'objname' of the attribute 577 'attrname'. If 'objname' is None, the current namespace is chosen as the 578 object providing the attribute. 579 """ 580 581 return self.get_namespace()._use_specific_attribute(objname, attrname, from_name) 582 583 def define_attribute_accessor(self, name, attrname, node, value=None): 584 585 """ 586 Note applicable attribute users providing the given 'name' when 587 accessing the given 'attrname' on the specified 'node', with the 588 optional 'value' indicating an assignment. 589 """ 590 591 self.get_namespace()._define_attribute_accessor(name, attrname, node, value) 592 593 # Visitor methods. 594 595 def default(self, node, *args): 596 raise InspectError("Node class %r is not supported." % node.__class__) 597 598 def NOP(self, node): 599 for n in node.getChildNodes(): 600 self.dispatch(n) 601 602 def NOP_ABANDON(self, node): 603 self.NOP(node) 604 self.abandon_branch() 605 606 def TEST_NOP(self, node): 607 self.use_name("__bool__", node) 608 self.NOP(node) 609 610 def OP(self, node): 611 for n in node.getChildNodes(): 612 self.dispatch(n) 613 return make_instance() 614 615 def TEST_OP(self, node): 616 self.use_name("__bool__", node) 617 self.new_branchpoint() 618 619 # Propagate attribute usage to branches. 620 # Each node starts a new conditional region, effectively making a deeply 621 # nested collection of if-like statements. 622 623 for n in node.nodes: 624 self.new_branch(n) 625 self.dispatch(n) 626 627 # The nested regions must be terminated. 628 629 for n in node.nodes: 630 self.shelve_branch() 631 632 self.merge_branches() 633 return make_instance() 634 635 # Generic support for classes of operations. 636 637 def _ensureOperators(self, node): 638 attr, scope, namespace = self._get_with_scope("$operator") 639 if attr is None: 640 module = node._module 641 module.complete() 642 self["$operator"] = module 643 else: 644 module = attr.get_value() 645 return module 646 647 def _visitOperator(self, node, operator_name=None): 648 649 "Accounting method for the operator 'node'." 650 651 operator_module = self._ensureOperators(node) 652 operator_fn = operator_functions[operator_name or node.__class__.__name__] 653 self.use_specific_attribute(operator_module.full_name(), operator_fn) 654 return self.OP(node) 655 656 def _visitAttr(self, expr, attrname, node): 657 658 """ 659 Process the attribute provided by the given 'expr' with the given 660 'attrname' and involving the given 'node'. 661 """ 662 663 # Attempt to identify the nature of the attribute. 664 665 if isinstance(expr, Attr): 666 value = expr.get_value() 667 668 # Get the attribute and record its usage. 669 # NOTE: Need to provide concrete values for things like base classes 670 # NOTE: while also handling module attribute modification. 671 672 # Only specific class attributes are detected here since class 673 # attribute finalisation has not yet occurred. 674 675 if isinstance(value, (Class, Module)): 676 677 # Check for class.__class__. 678 679 if attrname == "__class__" and isinstance(value, Class): 680 attr = get_constant_class("type") 681 else: 682 attr = value.get(attrname) or make_instance() 683 self.use_specific_attribute(value.full_name(), attrname) 684 685 elif isinstance(value, UnresolvedName): 686 attr = UnresolvedName(attrname, value.full_name(), self) 687 688 # The actual attribute is not readily identifiable and is assumed 689 # to be an instance. 690 691 else: 692 693 # Record any instance attributes. 694 695 if expr.name == "self": 696 self.store_instance_attr(attrname, tentative=True) 697 698 attr = make_instance() 699 700 # Note usage of the attribute where a local is involved. 701 702 self._visitAttrUser(expr, attrname, node) 703 704 # Constants provide specific kinds of expressions. 705 # NOTE: If attributes are accessed on a pre-made, but not yet defined 706 # NOTE: class, no useful attribute will be available. 707 708 elif isinstance(expr, Const): 709 attr = get_constant_class(expr.get_class_name()).all_attributes().get(attrname) or make_instance() 710 711 # No particular attribute has been identified, thus a general instance 712 # is assumed. 713 714 else: 715 attr = make_instance() 716 self.use_name(attrname, node) 717 718 return attr 719 720 def _visitAttrUser(self, expr, attrname, node, value=None): 721 722 """ 723 Note usage of the attribute provided by 'expr' with the given 'attrname' 724 where a local is involved, annotating the given 'node'. If the optional 725 'value' is given, note an assignment for future effects on attributes 726 where such attributes are inferred from the usage. 727 """ 728 729 # Access to attributes via a local in functions, classes or modules. 730 # Since module-level locals are globals that can be modified 731 # independently of the namespace, any attribute usage observations made 732 # here may be revoked later if such modification is thought to occur. 733 734 if expr.parent is self.get_namespace(): 735 self.define_attribute_accessor(expr.name, attrname, node, value) 736 else: 737 self.use_name(attrname, node.expr, value, ns=expr.parent) 738 739 def _visitConst(self, value): 740 741 """ 742 Register the constant given by 'value', if necessary, returning the 743 resulting object. The type name is noted as being used, thus preserving 744 the class in any generated program. 745 """ 746 747 self.use_specific_attribute("__builtins__", self.importer.get_constant_type_name(value)) 748 const = self.importer.make_constant(value) 749 self.use_constant(const) 750 return const 751 752 def _visitFunction(self, node, name): 753 754 """ 755 Return a function object for the function defined by 'node' with the 756 given 'name'. If a lambda expression is being visited, 'name' should be 757 None. 758 """ 759 760 # Define the function object. 761 762 function = Function( 763 name, 764 self.get_namespace(), 765 node.argnames, 766 node.defaults, 767 (node.flags & 4 != 0), 768 (node.flags & 8 != 0), 769 self.in_loop or self.in_function, 770 self, 771 node 772 ) 773 774 self.add_object(function, any_scope=1) 775 776 # Make a back reference from the node for code generation. 777 778 node.unit = function 779 780 # Process the defaults. 781 782 for n in node.defaults: 783 self.expr = self.dispatch(n) 784 function.store_default(self.expr) 785 786 # Note attribute usage where tuple parameters are involved. 787 788 if function.tuple_parameters(): 789 self.use_name("__getitem__", node) 790 791 # Record the namespace context of the function for later processing. 792 793 self.functions.append((node, self.namespaces + [function])) 794 795 # Store the function. 796 797 if name is not None: 798 self.store(name, function) 799 else: 800 self.store_lambda(function) 801 802 # Test the defaults and assess whether an dynamic object will result. 803 804 function.make_dynamic() 805 return function 806 807 def _visitFunctionBody(self, node, namespaces): 808 809 "Enter the function." 810 811 # Current namespace is the function. 812 # Previous namespace is the class. 813 814 if self.in_class(namespaces): 815 self.in_method = True 816 817 in_function = self.in_function 818 in_loop = self.in_loop 819 self.in_function = True 820 self.in_loop = False 821 822 self.namespaces = namespaces 823 self.dispatch(node.code) 824 825 self.in_loop = in_loop 826 self.in_function = in_function 827 self.in_method = False 828 829 # Specific handler methods. 830 831 visitAdd = _visitOperator 832 833 visitAnd = TEST_OP 834 835 visitAssert = NOP 836 837 def visitAssign(self, node): 838 self.expr = self.dispatch(node.expr) 839 self.in_assignment = True 840 for n in node.nodes: 841 self.dispatch(n) 842 self.in_assignment = False 843 844 def visitAssAttr(self, node): 845 expr = self.dispatch(node.expr) 846 attrname = node.attrname 847 848 # Record the attribute on the presumed target. 849 850 if isinstance(expr, Attr): 851 value = expr.get_value() 852 853 if expr.name == "self": 854 self.store_instance_attr(attrname) 855 self.use_attribute(expr.name, attrname, value) 856 self._visitAttrUser(expr, attrname, node, self.expr) 857 858 # No definite attribute can be identified, since the instance 859 # being accessed may be a subclass of the method's class. 860 861 attr = make_instance() 862 863 elif isinstance(value, Module): 864 self.store_module_attr(attrname, value) 865 attr = value.get(attrname) 866 867 elif isinstance(value, Class): 868 self.store_class_attr(attrname, value) 869 attr = value.get(attrname) 870 871 # Note usage of the attribute where a local is involved. 872 873 else: 874 self._visitAttrUser(expr, attrname, node, self.expr) 875 attr = make_instance() 876 877 else: 878 self.use_name(attrname, node) 879 attr = make_instance() 880 881 node._attr = attr 882 883 def visitAssList(self, node): 884 885 # Declare names which will be used by generated code. 886 887 self.use_name("__getitem__", node) 888 889 # Process the assignment. 890 891 for i, n in enumerate(node.nodes): 892 self.dispatch(n) 893 self._visitConst(i) # for __getitem__(i) at run-time 894 895 def visitAssName(self, node): 896 if node.flags == "OP_DELETE": 897 print >>sys.stderr, "Warning: deletion of attribute %r in %r is not supported." % (node.name, self.full_name()) 898 #raise InspectError("Deletion of attribute %r is not supported." % node.name) 899 self._visitAssName(node) 900 901 def _visitAssName(self, node): 902 self.store(node.name, self.expr) 903 self.define_attribute_user(node) 904 905 # Ensure the presence of the given name in this namespace. 906 # NOTE: Consider not registering assignments involving methods, since 907 # NOTE: this is merely creating aliases for such methods. 908 909 if isinstance(self.get_namespace(), (Class, Module)): 910 if not isinstance(self.expr, Attr) or not isinstance(self.expr.get_value(), Function): 911 self.use_specific_attribute(None, node.name) 912 else: 913 fn = self.expr.get_value() 914 ns = self.get_namespace().full_name() 915 self.use_specific_attribute(fn.parent.full_name(), fn.name, "%s.%s" % (ns, node.name)) 916 917 visitAssTuple = visitAssList 918 919 def visitAugAssign(self, node): 920 921 # Accounting. 922 923 operator_fn = operator_functions.get(node.op) 924 operator_module = self._ensureOperators(node) 925 self.use_specific_attribute(operator_module.full_name(), operator_fn) 926 927 # Process the assignment. 928 929 self.expr = self.dispatch(node.expr) 930 931 # NOTE: Similar to micropython.ast handler code. 932 # NOTE: Slices and subscripts are supported by __setitem__(slice) and 933 # NOTE: not __setslice__. 934 935 if isinstance(node.node, compiler.ast.Name): 936 self._visitAssName(node.node) 937 elif isinstance(node.node, compiler.ast.Getattr): 938 self.visitAssAttr(node.node) 939 else: 940 self.dispatch(node.node) 941 self.use_specific_attribute("__builtins__", "slice") 942 self.use_name("__setitem__", node) 943 944 visitBackquote = OP 945 946 visitBitand = _visitOperator 947 948 visitBitor = _visitOperator 949 950 visitBitxor = _visitOperator 951 952 def visitBreak(self, node): 953 self.NOP(node) 954 self.suspend_broken_branch() 955 956 visitCallFunc = OP 957 958 def visitClass(self, node): 959 960 """ 961 Register the class at the given 'node' subject to the restrictions 962 mentioned in the module docstring. 963 """ 964 965 if self.namespaces: 966 print >>sys.stderr, "Warning: class %r in %r is not global: ignored." % (node.name, self.namespaces[-1].full_name()) 967 return 968 else: 969 if self.in_loop: 970 print >>sys.stderr, "Warning: class %r in %r defined in a loop." % (node.name, self.full_name()) 971 972 cls = get_class(node.name, self.get_namespace(), self, node) 973 974 # Make a back reference from the node for code generation. 975 976 node.unit = cls 977 978 # Process base classes in the context of the class's namespace. 979 # This confines references to such classes to the class instead of 980 # the namespace in which it is defined. 981 982 self.namespaces.append(cls) 983 984 # Visit the base class expressions, attempting to find concrete 985 # definitions of classes. 986 987 for base in node.bases: 988 expr = self.dispatch(base) 989 990 # Each base class must be constant and known at compile-time. 991 992 if isinstance(expr, Attr): 993 if expr.assignments != 1: 994 raise InspectError("Base class %r for %r is not constant: %r" % (base, cls.full_name(), expr)) 995 elif not isinstance(expr.get_value(), Class): 996 raise InspectError("Base class %r for %r is not a class: %r" % (base, cls.full_name(), expr.get_value())) 997 else: 998 cls.add_base(expr.get_value()) 999 1000 # Where no expression value is available, the base class is 1001 # not identifiable. 1002 1003 else: 1004 raise InspectError("Base class %r for %r is not found: it may be hidden in some way." % (base, cls.full_name())) 1005 1006 # NOTE: Potentially dubious measure to permit __init__ availability. 1007 # If no bases exist, adopt the 'object' class. 1008 1009 if not node.bases and not (self.name == "__builtins__" and node.name == "object"): 1010 expr = self.dispatch(compiler.ast.Name("object")) 1011 cls.add_base(expr.get_value()) 1012 1013 # Make an entry for the class in the parent namespace. 1014 1015 self.namespaces.pop() 1016 self.store(node.name, cls) 1017 self.define_attribute_user(node) 1018 self.add_object(cls) 1019 1020 # Process the class body in its own namespace. 1021 # Add __name__ to the namespace. 1022 1023 self.namespaces.append(cls) 1024 self.store("__name__", self._visitConst(node.name)) 1025 self.dispatch(node.code) 1026 self.namespaces.pop() 1027 1028 cls.finalise_attribute_usage() 1029 return cls 1030 1031 def visitCompare(self, node): 1032 1033 # Accounting. 1034 # NOTE: Replicates some code in micropython.ast.visitCompare. 1035 1036 self.use_name("__bool__", node) 1037 1038 this_node = node 1039 1040 for op in node.ops: 1041 op_name, next_node = op 1042 1043 # Define name/attribute usage. 1044 # Get the applicable operation. 1045 1046 operator_fn = operator_functions.get(op_name) 1047 1048 # For operators, reference the specific function involved. 1049 1050 if operator_fn is not None: 1051 operator_module = self._ensureOperators(node) 1052 self.use_specific_attribute(operator_module.full_name(), operator_fn) 1053 1054 # Define __contains__ usage on the next node. 1055 1056 elif op_name.endswith("in"): 1057 self.use_name("__contains__", next_node) 1058 1059 this_node = next_node 1060 1061 return self.OP(node) 1062 1063 def visitConst(self, node): 1064 return self._visitConst(node.value) 1065 1066 def visitContinue(self, node): 1067 self.NOP(node) 1068 self.suspend_continuing_branch() 1069 1070 visitDecorators = NOP 1071 1072 visitDict = OP 1073 1074 visitDiscard = NOP 1075 1076 visitDiv = _visitOperator 1077 1078 visitEllipsis = NOP 1079 1080 visitExec = NOP 1081 1082 visitExpression = OP 1083 1084 visitFloorDiv = _visitOperator 1085 1086 def visitFor(self, node): 1087 self.new_branchpoint(node) 1088 1089 # Declare names which will be used by generated code. 1090 1091 self.use_name("__iter__", node.list) 1092 self.use_name("next") 1093 self.use_name("StopIteration") 1094 1095 in_loop = self.in_loop 1096 self.in_loop = True 1097 self.dispatch(node.list) 1098 1099 # NOTE: Could generate AST nodes for the actual operations instead of 1100 # NOTE: manually generating code in micropython.ast. 1101 1102 self.expr = make_instance() # each element is a result of a function call 1103 self.dispatch(node.assign) 1104 1105 # Enter the loop. 1106 # Propagate attribute usage to branches. 1107 1108 self.new_branch(node) 1109 self.dispatch(node.body) 1110 1111 self.resume_continuing_branches() 1112 1113 self.shelve_branch() 1114 1115 self.in_loop = in_loop 1116 1117 # A null branch is used to record a path around the loop. 1118 1119 self.new_branch(node.else_ or NullBranch()) 1120 self.shelve_branch() 1121 1122 self.merge_branches() 1123 1124 # The else clause is evaluated outside any branch. 1125 1126 if node.else_ is not None: 1127 self.dispatch(node.else_) 1128 1129 # Any suspended branches from the loop can now be resumed. 1130 1131 self.resume_broken_branches() 1132 1133 def visitFrom(self, node): 1134 module = self.complete_import(node.modname, True) 1135 1136 for name, alias in node.names: 1137 1138 # For specific names, obtain and store referenced objects using 1139 # the name or any alias provided in the current namespace. 1140 1141 if name != "*": 1142 if module: 1143 1144 # Missing names may refer to submodules. 1145 1146 submodule = self.complete_import(node.modname + "." + name, True) 1147 if submodule: 1148 if not module.has_key(name): 1149 module.store(name, submodule) 1150 1151 # Complete the import if the name was found. 1152 1153 if module.has_key(name): 1154 attr = module[name] 1155 self.store(alias or name, attr) 1156 self.use_specific_attribute(module.full_name(), name) 1157 continue 1158 1159 # Support the import of names from missing modules. 1160 1161 self.store(alias or name, UnresolvedName(name, node.modname, self)) 1162 1163 # For wildcards, obtain and store all objects from a module in the 1164 # current namespace. 1165 1166 else: 1167 if module: 1168 for n in module.keys(): 1169 attr = module[n] 1170 self.store(n, attr) 1171 self.use_specific_attribute(module.full_name(), n) 1172 1173 def visitFunction(self, node): 1174 return self._visitFunction(node, node.name) 1175 1176 visitGenExpr = OP 1177 1178 visitGenExprFor = NOP 1179 1180 visitGenExprIf = NOP 1181 1182 visitGenExprInner = NOP 1183 1184 def visitGetattr(self, node): 1185 node._expr = self.dispatch(node.expr) 1186 node._attr = self._visitAttr(node._expr, node.attrname, node) 1187 return node._attr 1188 1189 def visitGlobal(self, node): 1190 if self.namespaces: 1191 for name in node.names: 1192 ns = self.namespaces[-1] 1193 if not ns.make_global(name): 1194 raise InspectError("Name %r is global and local in %r" % (name, ns.full_name())) 1195 1196 # The name is recorded in an earlier process. 1197 1198 def visitIf(self, node): 1199 self.use_name("__bool__", node) 1200 self.new_branchpoint() 1201 1202 # Propagate attribute usage to branches. 1203 1204 for test, body in node.tests: 1205 self.dispatch(test) 1206 1207 self.new_branch(body) 1208 self.dispatch(body) 1209 self.shelve_branch() 1210 1211 # Maintain a branch for the else clause. 1212 1213 self.new_branch(node.else_ or NullBranch()) 1214 if node.else_ is not None: 1215 self.dispatch(node.else_) 1216 self.shelve_branch() 1217 1218 self.merge_branches() 1219 1220 def visitIfExp(self, node): 1221 self.use_name("__bool__", node) 1222 self.new_branchpoint() 1223 1224 # Propagate attribute usage to branches. 1225 1226 self.dispatch(node.test) 1227 1228 self.new_branch(node.then) 1229 self.dispatch(node.then) 1230 self.shelve_branch() 1231 1232 self.new_branch(node.else_) 1233 self.dispatch(node.else_) 1234 self.shelve_branch() 1235 1236 self.merge_branches() 1237 return make_instance() # either outcome is possible 1238 1239 def visitImport(self, node): 1240 for name, alias in node.names: 1241 module = self.complete_import(name, alias) 1242 if alias is not None: 1243 self.store(alias, module or UnresolvedName(None, name, self)) 1244 else: 1245 name_used = name.split(".")[0] 1246 self.store(name_used, module or UnresolvedName(None, name_used, self)) 1247 1248 visitInvert = _visitOperator 1249 1250 def visitKeyword(self, node): 1251 self.dispatch(node.expr) 1252 self._visitConst(node.name) 1253 self.keyword_names.add(node.name) 1254 1255 def visitLambda(self, node): 1256 fn = self._visitFunction(node, None) 1257 self.use_specific_attribute(None, fn.name) 1258 return fn 1259 1260 visitLeftShift = _visitOperator 1261 1262 def visitList(self, node): 1263 self.use_specific_attribute("__builtins__", "list") 1264 return self.OP(node) 1265 1266 def visitListComp(self, node): 1267 1268 # Note that explicit dispatch is performed. 1269 1270 if node.quals: 1271 self.visitListCompFor(node.quals[0], node.quals[1:], node.expr) 1272 return make_instance() 1273 1274 def visitListCompFor(self, node, following_quals, expr): 1275 self.new_branchpoint() 1276 1277 # Declare names which will be used by generated code. 1278 1279 self.use_name("__iter__", node.list) 1280 self.use_name("next") 1281 1282 in_loop = self.in_loop 1283 self.in_loop = True 1284 self.dispatch(node.list) 1285 1286 # NOTE: Could generate AST nodes for the actual operations instead of 1287 # NOTE: manually generating code in micropython.ast. 1288 1289 self.expr = make_instance() # each element is a result of a function call 1290 self.dispatch(node.assign) 1291 1292 # Enter the loop. 1293 # Propagate attribute usage to branches. 1294 1295 self.new_branch(node) 1296 1297 # Note that explicit dispatch is performed. 1298 1299 if node.ifs: 1300 self.visitListCompIf(node.ifs[0], node.ifs[1:], following_quals, expr) 1301 elif following_quals: 1302 self.visitListCompFor(following_quals[0], following_quals[1:], expr) 1303 else: 1304 self.dispatch(expr) 1305 1306 self.shelve_branch() 1307 self.in_loop = in_loop 1308 1309 self.merge_branches() 1310 1311 def visitListCompIf(self, node, following_ifs, following_quals, expr): 1312 self.use_name("__bool__", node) 1313 self.new_branchpoint() 1314 1315 # Propagate attribute usage to branches. 1316 1317 self.dispatch(node.test) 1318 1319 # Note that explicit dispatch is performed. 1320 1321 if following_ifs: 1322 self.visitListCompIf(following_ifs[0], following_ifs[1:], following_quals, expr) 1323 elif following_quals: 1324 self.visitListCompFor(following_quals[0], following_quals[1:], expr) 1325 else: 1326 self.new_branch(expr) 1327 self.dispatch(expr) 1328 self.shelve_branch() 1329 1330 # Maintain a branch for the else clause. 1331 1332 self.new_branch(NullBranch()) 1333 self.shelve_branch() 1334 1335 self.merge_branches() 1336 1337 visitMod = _visitOperator 1338 1339 def visitModule(self, node): 1340 1341 # Make a back reference from the node for code generation. 1342 1343 node.unit = self 1344 return self.dispatch(node.node) 1345 1346 visitMul = _visitOperator 1347 1348 def visitName(self, node): 1349 attr = self.get_namespace().get_using_node(node.name, node) or make_instance() 1350 node._attr = attr 1351 return attr 1352 1353 def visitNot(self, node): 1354 self.use_name("__bool__", node) 1355 self.dispatch(node.expr) 1356 return make_instance() 1357 1358 visitOr = TEST_OP 1359 1360 visitPass = NOP 1361 1362 visitPower = _visitOperator 1363 1364 def _visitPrint(self, node, function_name): 1365 self.NOP(node) 1366 self.use_specific_attribute("__builtins__", function_name) 1367 1368 def visitPrint(self, node): 1369 self._visitPrint(node, "_print") 1370 1371 def visitPrintnl(self, node): 1372 self._visitPrint(node, "_printnl") 1373 1374 visitRaise = NOP_ABANDON 1375 1376 visitReturn = NOP_ABANDON 1377 1378 visitRightShift = _visitOperator 1379 1380 def visitSlice(self, node): 1381 return self._visitOperator(node, self.in_assignment and "AssSlice" or "Slice") 1382 1383 visitSliceobj = OP 1384 1385 def visitStmt(self, node): 1386 for n in node.nodes: 1387 self.dispatch(n) 1388 1389 visitSub = _visitOperator 1390 1391 def visitSubscript(self, node): 1392 return self._visitOperator(node, self.in_assignment and "AssSubscript" or "Subscript") 1393 1394 def visitTryExcept(self, node): 1395 self.new_branchpoint() 1396 self.dispatch(node.body) 1397 1398 for name, var, n in node.handlers: 1399 if name is not None: 1400 self.dispatch(name) 1401 1402 self.new_branch(n) 1403 1404 # Any abandoned branches from the body can now be resumed. 1405 1406 self.resume_abandoned_branches() 1407 1408 # Establish the local for the handler. 1409 1410 if var is not None: 1411 self.dispatch(var) 1412 if n is not None: 1413 self.dispatch(n) 1414 1415 self.shelve_branch() 1416 1417 # The else clause maintains the usage from the body but without the 1418 # abandoned branches since they would never lead to the else clause 1419 # being executed. 1420 1421 self.new_branch(node.else_ or NullBranch()) 1422 if node.else_ is not None: 1423 self.dispatch(node.else_) 1424 self.shelve_branch() 1425 1426 self.merge_branches() 1427 1428 visitTryFinally = NOP 1429 1430 visitTuple = OP 1431 1432 visitUnaryAdd = _visitOperator 1433 1434 visitUnarySub = _visitOperator 1435 1436 def visitWhile(self, node): 1437 self.use_name("__bool__", node) 1438 self.new_branchpoint(node) 1439 1440 # Propagate attribute usage to branches. 1441 1442 in_loop = self.in_loop 1443 self.in_loop = True 1444 1445 # The test is evaluated initially and again in the loop. 1446 1447 self.dispatch(node.test) 1448 1449 self.new_branch(node) 1450 self.dispatch(node.body) 1451 1452 self.resume_continuing_branches() 1453 1454 self.dispatch(node.test) 1455 self.shelve_branch() 1456 1457 self.in_loop = in_loop 1458 1459 # A null branch is used to record a path around the loop. 1460 1461 self.new_branch(node.else_ or NullBranch()) 1462 self.shelve_branch() 1463 1464 self.merge_branches() 1465 1466 # The else clause is evaluated outside any branch. 1467 1468 if node.else_ is not None: 1469 self.dispatch(node.else_) 1470 1471 # Any suspended branches from the loop can now be resumed. 1472 1473 self.resume_broken_branches() 1474 1475 visitWith = NOP 1476 1477 visitYield = NOP 1478 1479 # vim: tabstop=4 expandtab shiftwidth=4