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.add_object(cls) 1018 1019 # Process the class body in its own namespace. 1020 # Add __name__ to the namespace. 1021 1022 self.namespaces.append(cls) 1023 self.store("__name__", self._visitConst(node.name)) 1024 self.dispatch(node.code) 1025 self.namespaces.pop() 1026 1027 cls.finalise_attribute_usage() 1028 return cls 1029 1030 def visitCompare(self, node): 1031 1032 # Accounting. 1033 # NOTE: Replicates some code in micropython.ast.visitCompare. 1034 1035 self.use_name("__bool__", node) 1036 1037 this_node = node 1038 1039 for op in node.ops: 1040 op_name, next_node = op 1041 1042 # Define name/attribute usage. 1043 # Get the applicable operation. 1044 1045 operator_fn = operator_functions.get(op_name) 1046 1047 # For operators, reference the specific function involved. 1048 1049 if operator_fn is not None: 1050 operator_module = self._ensureOperators(node) 1051 self.use_specific_attribute(operator_module.full_name(), operator_fn) 1052 1053 # Define __contains__ usage on the next node. 1054 1055 elif op_name.endswith("in"): 1056 self.use_name("__contains__", next_node) 1057 1058 this_node = next_node 1059 1060 return self.OP(node) 1061 1062 def visitConst(self, node): 1063 return self._visitConst(node.value) 1064 1065 def visitContinue(self, node): 1066 self.NOP(node) 1067 self.suspend_continuing_branch() 1068 1069 visitDecorators = NOP 1070 1071 visitDict = OP 1072 1073 visitDiscard = NOP 1074 1075 visitDiv = _visitOperator 1076 1077 visitEllipsis = NOP 1078 1079 visitExec = NOP 1080 1081 visitExpression = OP 1082 1083 visitFloorDiv = _visitOperator 1084 1085 def visitFor(self, node): 1086 self.new_branchpoint(node) 1087 1088 # Declare names which will be used by generated code. 1089 1090 self.use_name("__iter__", node.list) 1091 self.use_name("next") 1092 self.use_name("StopIteration") 1093 1094 in_loop = self.in_loop 1095 self.in_loop = True 1096 self.dispatch(node.list) 1097 1098 # NOTE: Could generate AST nodes for the actual operations instead of 1099 # NOTE: manually generating code in micropython.ast. 1100 1101 self.expr = make_instance() # each element is a result of a function call 1102 self.dispatch(node.assign) 1103 1104 # Enter the loop. 1105 # Propagate attribute usage to branches. 1106 1107 self.new_branch(node) 1108 self.dispatch(node.body) 1109 1110 self.resume_continuing_branches() 1111 1112 self.shelve_branch() 1113 1114 self.in_loop = in_loop 1115 1116 # A null branch is used to record a path around the loop. 1117 1118 self.new_branch(node.else_ or NullBranch()) 1119 self.shelve_branch() 1120 1121 self.merge_branches() 1122 1123 # The else clause is evaluated outside any branch. 1124 1125 if node.else_ is not None: 1126 self.dispatch(node.else_) 1127 1128 # Any suspended branches from the loop can now be resumed. 1129 1130 self.resume_broken_branches() 1131 1132 def visitFrom(self, node): 1133 module = self.complete_import(node.modname, True) 1134 1135 for name, alias in node.names: 1136 1137 # For specific names, obtain and store referenced objects using 1138 # the name or any alias provided in the current namespace. 1139 1140 if name != "*": 1141 if module: 1142 1143 # Missing names may refer to submodules. 1144 1145 submodule = self.complete_import(node.modname + "." + name, True) 1146 if submodule: 1147 if not module.has_key(name): 1148 module.store(name, submodule) 1149 1150 # Complete the import if the name was found. 1151 1152 if module.has_key(name): 1153 attr = module[name] 1154 self.store(alias or name, attr) 1155 self.use_specific_attribute(module.full_name(), name) 1156 continue 1157 1158 # Support the import of names from missing modules. 1159 1160 self.store(alias or name, UnresolvedName(name, node.modname, self)) 1161 1162 # For wildcards, obtain and store all objects from a module in the 1163 # current namespace. 1164 1165 else: 1166 if module: 1167 for n in module.keys(): 1168 attr = module[n] 1169 self.store(n, attr) 1170 self.use_specific_attribute(module.full_name(), n) 1171 1172 def visitFunction(self, node): 1173 return self._visitFunction(node, node.name) 1174 1175 visitGenExpr = OP 1176 1177 visitGenExprFor = NOP 1178 1179 visitGenExprIf = NOP 1180 1181 visitGenExprInner = NOP 1182 1183 def visitGetattr(self, node): 1184 node._expr = self.dispatch(node.expr) 1185 node._attr = self._visitAttr(node._expr, node.attrname, node) 1186 return node._attr 1187 1188 def visitGlobal(self, node): 1189 if self.namespaces: 1190 for name in node.names: 1191 ns = self.namespaces[-1] 1192 if not ns.make_global(name): 1193 raise InspectError("Name %r is global and local in %r" % (name, ns.full_name())) 1194 1195 # The name is recorded in an earlier process. 1196 1197 def visitIf(self, node): 1198 self.use_name("__bool__", node) 1199 self.new_branchpoint() 1200 1201 # Propagate attribute usage to branches. 1202 1203 for test, body in node.tests: 1204 self.dispatch(test) 1205 1206 self.new_branch(body) 1207 self.dispatch(body) 1208 self.shelve_branch() 1209 1210 # Maintain a branch for the else clause. 1211 1212 self.new_branch(node.else_ or NullBranch()) 1213 if node.else_ is not None: 1214 self.dispatch(node.else_) 1215 self.shelve_branch() 1216 1217 self.merge_branches() 1218 1219 def visitIfExp(self, node): 1220 self.use_name("__bool__", node) 1221 self.new_branchpoint() 1222 1223 # Propagate attribute usage to branches. 1224 1225 self.dispatch(node.test) 1226 1227 self.new_branch(node.then) 1228 self.dispatch(node.then) 1229 self.shelve_branch() 1230 1231 self.new_branch(node.else_) 1232 self.dispatch(node.else_) 1233 self.shelve_branch() 1234 1235 self.merge_branches() 1236 return make_instance() # either outcome is possible 1237 1238 def visitImport(self, node): 1239 for name, alias in node.names: 1240 module = self.complete_import(name, alias) 1241 if alias is not None: 1242 self.store(alias, module or UnresolvedName(None, name, self)) 1243 else: 1244 name_used = name.split(".")[0] 1245 self.store(name_used, module or UnresolvedName(None, name_used, self)) 1246 1247 visitInvert = _visitOperator 1248 1249 def visitKeyword(self, node): 1250 self.dispatch(node.expr) 1251 self._visitConst(node.name) 1252 self.keyword_names.add(node.name) 1253 1254 def visitLambda(self, node): 1255 fn = self._visitFunction(node, None) 1256 self.use_specific_attribute(None, fn.name) 1257 return fn 1258 1259 visitLeftShift = _visitOperator 1260 1261 def visitList(self, node): 1262 self.use_specific_attribute("__builtins__", "list") 1263 return self.OP(node) 1264 1265 def visitListComp(self, node): 1266 1267 # Note that explicit dispatch is performed. 1268 1269 if node.quals: 1270 self.visitListCompFor(node.quals[0], node.quals[1:], node.expr) 1271 return make_instance() 1272 1273 def visitListCompFor(self, node, following_quals, expr): 1274 self.new_branchpoint() 1275 1276 # Declare names which will be used by generated code. 1277 1278 self.use_name("__iter__", node.list) 1279 self.use_name("next") 1280 1281 in_loop = self.in_loop 1282 self.in_loop = True 1283 self.dispatch(node.list) 1284 1285 # NOTE: Could generate AST nodes for the actual operations instead of 1286 # NOTE: manually generating code in micropython.ast. 1287 1288 self.expr = make_instance() # each element is a result of a function call 1289 self.dispatch(node.assign) 1290 1291 # Enter the loop. 1292 # Propagate attribute usage to branches. 1293 1294 self.new_branch(node) 1295 1296 # Note that explicit dispatch is performed. 1297 1298 if node.ifs: 1299 self.visitListCompIf(node.ifs[0], node.ifs[1:], following_quals, expr) 1300 elif following_quals: 1301 self.visitListCompFor(following_quals[0], following_quals[1:], expr) 1302 else: 1303 self.dispatch(expr) 1304 1305 self.shelve_branch() 1306 self.in_loop = in_loop 1307 1308 self.merge_branches() 1309 1310 def visitListCompIf(self, node, following_ifs, following_quals, expr): 1311 self.use_name("__bool__", node) 1312 self.new_branchpoint() 1313 1314 # Propagate attribute usage to branches. 1315 1316 self.dispatch(node.test) 1317 1318 # Note that explicit dispatch is performed. 1319 1320 if following_ifs: 1321 self.visitListCompIf(following_ifs[0], following_ifs[1:], following_quals, expr) 1322 elif following_quals: 1323 self.visitListCompFor(following_quals[0], following_quals[1:], expr) 1324 else: 1325 self.new_branch(expr) 1326 self.dispatch(expr) 1327 self.shelve_branch() 1328 1329 # Maintain a branch for the else clause. 1330 1331 self.new_branch(NullBranch()) 1332 self.shelve_branch() 1333 1334 self.merge_branches() 1335 1336 visitMod = _visitOperator 1337 1338 def visitModule(self, node): 1339 1340 # Make a back reference from the node for code generation. 1341 1342 node.unit = self 1343 return self.dispatch(node.node) 1344 1345 visitMul = _visitOperator 1346 1347 def visitName(self, node): 1348 attr = self.get_namespace().get_using_node(node.name, node) or make_instance() 1349 node._attr = attr 1350 return attr 1351 1352 def visitNot(self, node): 1353 self.use_name("__bool__", node) 1354 self.dispatch(node.expr) 1355 return make_instance() 1356 1357 visitOr = TEST_OP 1358 1359 visitPass = NOP 1360 1361 visitPower = _visitOperator 1362 1363 def _visitPrint(self, node, function_name): 1364 self.NOP(node) 1365 self.use_specific_attribute("__builtins__", function_name) 1366 1367 def visitPrint(self, node): 1368 self._visitPrint(node, "_print") 1369 1370 def visitPrintnl(self, node): 1371 self._visitPrint(node, "_printnl") 1372 1373 visitRaise = NOP_ABANDON 1374 1375 visitReturn = NOP_ABANDON 1376 1377 visitRightShift = _visitOperator 1378 1379 def visitSlice(self, node): 1380 return self._visitOperator(node, self.in_assignment and "AssSlice" or "Slice") 1381 1382 visitSliceobj = OP 1383 1384 def visitStmt(self, node): 1385 for n in node.nodes: 1386 self.dispatch(n) 1387 1388 visitSub = _visitOperator 1389 1390 def visitSubscript(self, node): 1391 return self._visitOperator(node, self.in_assignment and "AssSubscript" or "Subscript") 1392 1393 def visitTryExcept(self, node): 1394 self.new_branchpoint() 1395 self.dispatch(node.body) 1396 1397 for name, var, n in node.handlers: 1398 if name is not None: 1399 self.dispatch(name) 1400 1401 self.new_branch(n) 1402 1403 # Any abandoned branches from the body can now be resumed. 1404 1405 self.resume_abandoned_branches() 1406 1407 # Establish the local for the handler. 1408 1409 if var is not None: 1410 self.dispatch(var) 1411 if n is not None: 1412 self.dispatch(n) 1413 1414 self.shelve_branch() 1415 1416 # The else clause maintains the usage from the body but without the 1417 # abandoned branches since they would never lead to the else clause 1418 # being executed. 1419 1420 self.new_branch(node.else_ or NullBranch()) 1421 if node.else_ is not None: 1422 self.dispatch(node.else_) 1423 self.shelve_branch() 1424 1425 self.merge_branches() 1426 1427 visitTryFinally = NOP 1428 1429 visitTuple = OP 1430 1431 visitUnaryAdd = _visitOperator 1432 1433 visitUnarySub = _visitOperator 1434 1435 def visitWhile(self, node): 1436 self.use_name("__bool__", node) 1437 self.new_branchpoint(node) 1438 1439 # Propagate attribute usage to branches. 1440 1441 in_loop = self.in_loop 1442 self.in_loop = True 1443 1444 # The test is evaluated initially and again in the loop. 1445 1446 self.dispatch(node.test) 1447 1448 self.new_branch(node) 1449 self.dispatch(node.body) 1450 1451 self.resume_continuing_branches() 1452 1453 self.dispatch(node.test) 1454 self.shelve_branch() 1455 1456 self.in_loop = in_loop 1457 1458 # A null branch is used to record a path around the loop. 1459 1460 self.new_branch(node.else_ or NullBranch()) 1461 self.shelve_branch() 1462 1463 self.merge_branches() 1464 1465 # The else clause is evaluated outside any branch. 1466 1467 if node.else_ is not None: 1468 self.dispatch(node.else_) 1469 1470 # Any suspended branches from the loop can now be resumed. 1471 1472 self.resume_broken_branches() 1473 1474 visitWith = NOP 1475 1476 visitYield = NOP 1477 1478 # vim: tabstop=4 expandtab shiftwidth=4