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