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