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 attribute 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). 604 605 if expr.parent is self.get_namespace() and not self.get_namespace() is self: 606 self.define_attribute_accessor(expr.name, attrname, node, value) 607 else: 608 self.use_name(attrname, node.expr, value, ns=expr.parent) 609 610 def _visitConst(self, value): 611 612 """ 613 Register the constant given by 'value', if necessary, returning the 614 resulting object. The type name is noted as being used, thus preserving 615 the class in any generated program. 616 """ 617 618 self.use_specific_attribute("__builtins__", self.importer.get_constant_type_name(value)) 619 const = self.importer.make_constant(value) 620 self.use_constant(const) 621 return const 622 623 def _visitFunction(self, node, name): 624 625 """ 626 Return a function object for the function defined by 'node' with the 627 given 'name'. If a lambda expression is being visited, 'name' should be 628 None. 629 """ 630 631 # Define the function object. 632 633 function = Function( 634 name, 635 self.get_namespace(), 636 node.argnames, 637 node.defaults, 638 (node.flags & 4 != 0), 639 (node.flags & 8 != 0), 640 self.in_loop or self.in_function, 641 self, 642 node 643 ) 644 645 self.add_object(function, any_scope=1) 646 647 # Make a back reference from the node for code generation. 648 649 node.unit = function 650 651 # Process the defaults. 652 653 for n in node.defaults: 654 self.expr = self.dispatch(n) 655 function.store_default(self.expr) 656 657 # Note attribute usage where tuple parameters are involved. 658 659 if function.tuple_parameters(): 660 self.use_name("__getitem__", node) 661 662 # Record the namespace context of the function for later processing. 663 664 self.functions.append((node, self.namespaces + [function])) 665 666 # Store the function. 667 668 if name is not None: 669 self.store(name, function) 670 else: 671 self.store_lambda(function) 672 673 # Test the defaults and assess whether an dynamic object will result. 674 675 function.make_dynamic() 676 return function 677 678 def _visitFunctionBody(self, node, namespaces): 679 680 "Enter the function." 681 682 # Current namespace is the function. 683 # Previous namespace is the class. 684 685 if self.in_class(namespaces): 686 self.in_method = 1 687 688 in_function = self.in_function 689 in_loop = self.in_loop 690 self.in_function = 1 691 self.in_loop = 0 692 693 self.namespaces = namespaces 694 self.dispatch(node.code) 695 696 self.in_loop = in_loop 697 self.in_function = in_function 698 self.in_method = 0 699 700 # Specific handler methods. 701 702 visitAdd = _visitBinary 703 704 visitAnd = TEST_OP 705 706 visitAssert = NOP 707 708 def visitAssign(self, node): 709 self.expr = self.dispatch(node.expr) 710 self.in_assignment = 1 711 for n in node.nodes: 712 self.dispatch(n) 713 self.in_assignment = 0 714 715 def visitAssAttr(self, node): 716 expr = self.dispatch(node.expr) 717 attrname = node.attrname 718 719 # Record the attribute on the presumed target. 720 721 if isinstance(expr, Attr): 722 value = expr.get_value() 723 724 if expr.name == "self": 725 self.store_instance_attr(attrname) 726 self.use_attribute(expr.name, attrname, value) 727 self._visitAttrUser(expr, attrname, node, self.expr) 728 729 elif isinstance(value, Module): 730 self.store_module_attr(attrname, value) 731 print >>sys.stderr, "Warning: attribute %r of module %r set outside the module." % (node.attrname, expr.get_value().name) 732 733 elif isinstance(value, Class): 734 self.store_class_attr(attrname, value) 735 736 # Note usage of the attribute where a local is involved. 737 738 else: 739 self._visitAttrUser(expr, attrname, node, self.expr) 740 741 else: 742 self.use_name(attrname, node) 743 744 def visitAssList(self, node): 745 746 # Declare names which will be used by generated code. 747 748 self.use_name("__getitem__", node) 749 750 # Process the assignment. 751 752 for i, n in enumerate(node.nodes): 753 self.dispatch(n) 754 self._visitConst(i) # for __getitem__(i) at run-time 755 756 def visitAssName(self, node): 757 if hasattr(node, "flags") and node.flags == "OP_DELETE": 758 print >>sys.stderr, "Warning: deletion of attribute %r in %r is not supported." % (node.name, self.full_name()) 759 #raise InspectError("Deletion of attribute %r is not supported." % node.name) 760 761 self.store(node.name, self.expr) 762 self.define_attribute_user(node) 763 764 # Ensure the presence of the given name in this namespace. 765 # NOTE: Consider not registering assignments involving methods, since 766 # NOTE: this is merely creating aliases for such methods. 767 768 if isinstance(self.get_namespace(), (Class, Module)): 769 if not isinstance(self.expr, Attr) or not isinstance(self.expr.get_value(), Function): 770 self.use_specific_attribute(None, node.name) 771 else: 772 fn = self.expr.get_value() 773 ns = self.get_namespace().full_name() 774 self.use_specific_attribute(fn.parent.full_name(), fn.name, "%s.%s" % (ns, node.name)) 775 776 visitAssTuple = visitAssList 777 778 def visitAugAssign(self, node): 779 780 # Accounting. 781 782 operator_fn = operator_functions.get(node.op) 783 operator_module = self._ensureOperators() 784 self.use_specific_attribute(operator_module.full_name(), operator_fn) 785 786 # Process the assignment. 787 788 self.expr = self.dispatch(node.expr) 789 790 # NOTE: Similar to micropython.ast handler code. 791 # NOTE: Slices and subscripts are supported by __setitem__(slice) and 792 # NOTE: not __setslice__. 793 794 if isinstance(node.node, compiler.ast.Name): 795 self.visitAssName(node.node) 796 elif isinstance(node.node, compiler.ast.Getattr): 797 self.visitAssAttr(node.node) 798 else: 799 self.use_specific_attribute("__builtins__", "slice") 800 self.use_name("__setitem__", node) 801 802 visitBackquote = OP 803 804 visitBitand = _visitBinary 805 806 visitBitor = _visitBinary 807 808 visitBitxor = _visitBinary 809 810 def visitBreak(self, node): 811 self.NOP(node) 812 self.suspend_broken_branch() 813 814 visitCallFunc = OP 815 816 def visitClass(self, node): 817 818 """ 819 Register the class at the given 'node' subject to the restrictions 820 mentioned in the module docstring. 821 """ 822 823 if self.namespaces: 824 print >>sys.stderr, "Warning: class %r in %r is not global: ignored." % (node.name, self.namespaces[-1].full_name()) 825 return 826 else: 827 if self.in_loop: 828 print >>sys.stderr, "Warning: class %r in %r defined in a loop." % (node.name, self.full_name()) 829 830 cls = get_class(node.name, self.get_namespace(), self, node) 831 832 # Make a back reference from the node for code generation. 833 834 node.unit = cls 835 836 # Process base classes in the context of the class's namespace. 837 # This confines references to such classes to the class instead of 838 # the namespace in which it is defined. 839 840 self.namespaces.append(cls) 841 842 # Visit the base class expressions, attempting to find concrete 843 # definitions of classes. 844 845 for base in node.bases: 846 expr = self.dispatch(base) 847 848 # Each base class must be constant and known at compile-time. 849 850 if isinstance(expr, Attr): 851 if expr.assignments != 1: 852 raise InspectError("Base class %r for %r is not constant: %r" % (base, cls.full_name(), expr)) 853 elif not isinstance(expr.get_value(), Class): 854 raise InspectError("Base class %r for %r is not a class: %r" % (base, cls.full_name(), expr.get_value())) 855 else: 856 cls.add_base(expr.get_value()) 857 858 # Where no expression value is available, the base class is 859 # not identifiable. 860 861 else: 862 raise InspectError("Base class %r for %r is not found: it may be hidden in some way." % (base, cls.full_name())) 863 864 # NOTE: Potentially dubious measure to permit __init__ availability. 865 # If no bases exist, adopt the 'object' class. 866 867 if not node.bases and not (self.name == "__builtins__" and node.name == "object") : 868 expr = self.dispatch(compiler.ast.Name("object")) 869 cls.add_base(expr.get_value()) 870 871 # Make an entry for the class in the parent namespace. 872 873 self.namespaces.pop() 874 self.store(node.name, cls) 875 self.add_object(cls) 876 877 # Process the class body in its own namespace. 878 # Add __name__ to the namespace. 879 880 self.namespaces.append(cls) 881 self.store("__name__", self._visitConst(node.name)) 882 self.dispatch(node.code) 883 self.namespaces.pop() 884 885 cls.finalise_attribute_usage() 886 return cls 887 888 def visitCompare(self, node): 889 890 # Accounting. 891 # NOTE: Replicates some code in micropython.ast.visitCompare. 892 893 self.use_name("__bool__", node) 894 895 this_node = node 896 897 for op in node.ops: 898 op_name, next_node = op 899 900 # Define name/attribute usage. 901 # Get the applicable operation. 902 903 operator_fn = operator_functions.get(op_name) 904 905 # For operators, reference the specific function involved. 906 907 if operator_fn is not None: 908 operator_module = self._ensureOperators() 909 self.use_specific_attribute(operator_module.full_name(), operator_fn) 910 911 # Define __contains__ usage on the next node. 912 913 elif op_name.endswith("in"): 914 self.use_name("__contains__", next_node) 915 916 this_node = next_node 917 918 return self.OP(node) 919 920 def visitConst(self, node): 921 return self._visitConst(node.value) 922 923 def visitContinue(self, node): 924 self.NOP(node) 925 self.suspend_continuing_branch() 926 927 visitDecorators = NOP 928 929 visitDict = OP 930 931 visitDiscard = NOP 932 933 visitDiv = _visitBinary 934 935 visitEllipsis = NOP 936 937 visitExec = NOP 938 939 visitExpression = OP 940 941 visitFloorDiv = _visitBinary 942 943 def visitFor(self, node): 944 self.new_branchpoint(node) 945 946 # Declare names which will be used by generated code. 947 948 self.use_name("__iter__", node.list) 949 self.use_name("next") 950 self.use_name("StopIteration") 951 952 in_loop = self.in_loop 953 self.in_loop = 1 954 self.dispatch(node.list) 955 956 # NOTE: Could generate AST nodes for the actual operations instead of 957 # NOTE: manually generating code in micropython.ast. 958 959 self.expr = make_instance() # each element is a result of a function call 960 self.dispatch(node.assign) 961 962 # Enter the loop. 963 # Propagate attribute usage to branches. 964 965 self.new_branch(node) 966 self.dispatch(node.body) 967 968 self.resume_continuing_branches() 969 970 self.shelve_branch() 971 972 self.in_loop = in_loop 973 974 # A null branch is used to record a path around the loop. 975 976 self.new_branch(node.else_ or NullBranch()) 977 self.shelve_branch() 978 979 self.merge_branches() 980 981 # The else clause is evaluated outside any branch. 982 983 if node.else_ is not None: 984 self.dispatch(node.else_) 985 986 # Any suspended branches from the loop can now be resumed. 987 988 self.resume_broken_branches() 989 990 def visitFrom(self, node): 991 module = self.importer.load(node.modname, 1) 992 if module and not module.loaded: 993 print >>sys.stderr, "Warning: a circular import of %s is being attempted in %s" % (node.modname, self.full_name()) 994 995 #if module is None: 996 # print >>sys.stderr, "Warning:", node.modname, "not imported." 997 998 for name, alias in node.names: 999 if name != "*": 1000 if module: 1001 1002 # Missing names may refer to submodules. 1003 1004 if not module.has_key(name): 1005 submodule = self.importer.load(node.modname + "." + name, 1) 1006 if submodule: 1007 if not submodule.loaded: 1008 print >>sys.stderr, "Warning: a circular import of %s.%s is being attempted in %s" % ( 1009 node.modname, name, self.full_name()) 1010 1011 module.store(name, submodule) 1012 1013 # Complete the import if the name was found. 1014 1015 if module.has_key(name): 1016 attr = module[name] 1017 self.store(alias or name, attr) 1018 self.use_specific_attribute(module.full_name(), name) 1019 if isinstance(attr.get_value(), Module) and not attr.get_value().loaded: 1020 self.importer.load(attr.get_value().name) 1021 continue 1022 1023 # Support the import of names from missing modules. 1024 1025 self.store(alias or name, UnresolvedName(name, node.modname, self)) 1026 1027 else: 1028 if module: 1029 for n in module.keys(): 1030 attr = module[n] 1031 self.store(n, attr) 1032 self.use_specific_attribute(module.full_name(), n) 1033 if isinstance(attr.get_value(), Module) and not attr.get_value().loaded: 1034 self.importer.load(attr.get_value().name) 1035 1036 def visitFunction(self, node): 1037 return self._visitFunction(node, node.name) 1038 1039 visitGenExpr = OP 1040 1041 visitGenExprFor = NOP 1042 1043 visitGenExprIf = NOP 1044 1045 visitGenExprInner = NOP 1046 1047 def visitGetattr(self, node): 1048 expr = self.dispatch(node.expr) 1049 attrname = node.attrname 1050 node._attr = self._visitAttr(expr, attrname, node) 1051 return node._attr 1052 1053 def visitGlobal(self, node): 1054 if self.namespaces: 1055 for name in node.names: 1056 ns = self.namespaces[-1] 1057 if not ns.make_global(name): 1058 raise InspectError("Name %r is global and local in %r" % (name, ns.full_name())) 1059 1060 # The name is recorded in an earlier process. 1061 1062 def visitIf(self, node): 1063 self.use_name("__bool__", node) 1064 self.new_branchpoint() 1065 1066 # Propagate attribute usage to branches. 1067 1068 for test, body in node.tests: 1069 self.dispatch(test) 1070 1071 self.new_branch(body) 1072 self.dispatch(body) 1073 self.shelve_branch() 1074 1075 # Maintain a branch for the else clause. 1076 1077 self.new_branch(node.else_ or NullBranch()) 1078 if node.else_ is not None: 1079 self.dispatch(node.else_) 1080 self.shelve_branch() 1081 1082 self.merge_branches() 1083 1084 def visitIfExp(self, node): 1085 self.use_name("__bool__", node) 1086 self.new_branchpoint() 1087 1088 # Propagate attribute usage to branches. 1089 1090 self.dispatch(node.test) 1091 1092 self.new_branch(node.then) 1093 self.dispatch(node.then) 1094 self.shelve_branch() 1095 1096 self.new_branch(node.else_) 1097 self.dispatch(node.else_) 1098 self.shelve_branch() 1099 1100 self.merge_branches() 1101 return make_instance() # either outcome is possible 1102 1103 def visitImport(self, node): 1104 for name, alias in node.names: 1105 if alias is not None: 1106 module = self.importer.load(name, 1) or UnresolvedName(None, name, self) 1107 self.store(alias, module) 1108 else: 1109 module = self.importer.load(name) or UnresolvedName(None, name.split(".")[0], self) 1110 self.store(name.split(".")[0], module) 1111 1112 visitInvert = _visitUnary 1113 1114 def visitKeyword(self, node): 1115 self.dispatch(node.expr) 1116 self._visitConst(node.name) 1117 self.keyword_names.add(node.name) 1118 1119 def visitLambda(self, node): 1120 fn = self._visitFunction(node, None) 1121 self.use_specific_attribute(None, fn.name) 1122 return fn 1123 1124 visitLeftShift = _visitBinary 1125 1126 def visitList(self, node): 1127 self.use_specific_attribute("__builtins__", "list") 1128 return self.OP(node) 1129 1130 def visitListComp(self, node): 1131 1132 # Note that explicit dispatch is performed. 1133 1134 if node.quals: 1135 self.visitListCompFor(node.quals[0], node.quals[1:], node.expr) 1136 return make_instance() 1137 1138 def visitListCompFor(self, node, following_quals, expr): 1139 self.new_branchpoint() 1140 1141 # Declare names which will be used by generated code. 1142 1143 self.use_name("__iter__", node.list) 1144 self.use_name("next") 1145 1146 in_loop = self.in_loop 1147 self.in_loop = 1 1148 self.dispatch(node.list) 1149 1150 # NOTE: Could generate AST nodes for the actual operations instead of 1151 # NOTE: manually generating code in micropython.ast. 1152 1153 self.expr = make_instance() # each element is a result of a function call 1154 self.dispatch(node.assign) 1155 1156 # Enter the loop. 1157 # Propagate attribute usage to branches. 1158 1159 self.new_branch(node) 1160 1161 # Note that explicit dispatch is performed. 1162 1163 if node.ifs: 1164 self.visitListCompIf(node.ifs[0], node.ifs[1:], following_quals, expr) 1165 elif following_quals: 1166 self.visitListCompFor(following_quals[0], following_quals[1:], expr) 1167 else: 1168 self.dispatch(expr) 1169 1170 self.shelve_branch() 1171 self.in_loop = in_loop 1172 1173 self.merge_branches() 1174 1175 def visitListCompIf(self, node, following_ifs, following_quals, expr): 1176 self.use_name("__bool__", node) 1177 self.new_branchpoint() 1178 1179 # Propagate attribute usage to branches. 1180 1181 self.dispatch(node.test) 1182 1183 # Note that explicit dispatch is performed. 1184 1185 if following_ifs: 1186 self.visitListCompIf(following_ifs[0], following_ifs[1:], following_quals, expr) 1187 elif following_quals: 1188 self.visitListCompFor(following_quals[0], following_quals[1:], expr) 1189 else: 1190 self.new_branch(expr) 1191 self.dispatch(expr) 1192 self.shelve_branch() 1193 1194 # Maintain a branch for the else clause. 1195 1196 self.new_branch(NullBranch()) 1197 self.shelve_branch() 1198 1199 self.merge_branches() 1200 1201 visitMod = _visitBinary 1202 1203 def visitModule(self, node): 1204 1205 # Make a back reference from the node for code generation. 1206 1207 node.unit = self 1208 return self.dispatch(node.node) 1209 1210 visitMul = _visitBinary 1211 1212 def visitName(self, node): 1213 return self.get_namespace().get_using_node(node.name, node) or make_instance() 1214 1215 def visitNot(self, node): 1216 self.use_name("__bool__", node) 1217 self.dispatch(node.expr) 1218 return make_instance() 1219 1220 visitOr = TEST_OP 1221 1222 visitPass = NOP 1223 1224 visitPower = _visitBinary 1225 1226 def _visitPrint(self, node, function_name): 1227 self.NOP(node) 1228 self.use_specific_attribute("__builtins__", function_name) 1229 1230 def visitPrint(self, node): 1231 self._visitPrint(node, "_print") 1232 1233 def visitPrintnl(self, node): 1234 self._visitPrint(node, "_printnl") 1235 1236 visitRaise = NOP_ABANDON 1237 1238 visitReturn = NOP_ABANDON 1239 1240 visitRightShift = _visitBinary 1241 1242 def visitSlice(self, node): 1243 return self._visitOperator(node, self.in_assignment and "AssSlice" or "Slice") 1244 1245 visitSliceobj = OP 1246 1247 def visitStmt(self, node): 1248 for n in node.nodes: 1249 self.dispatch(n) 1250 1251 visitSub = _visitBinary 1252 1253 def visitSubscript(self, node): 1254 return self._visitOperator(node, self.in_assignment and "AssSubscript" or "Subscript") 1255 1256 def visitTryExcept(self, node): 1257 self.new_branchpoint() 1258 self.dispatch(node.body) 1259 1260 for name, var, n in node.handlers: 1261 self.new_branch(n) 1262 1263 # Any abandoned branches from the body can now be resumed. 1264 1265 self.resume_abandoned_branches() 1266 1267 # Establish the local for the handler. 1268 1269 if var is not None: 1270 self.dispatch(var) 1271 if n is not None: 1272 self.dispatch(n) 1273 1274 self.shelve_branch() 1275 1276 # The else clause maintains the usage from the body but without the 1277 # abandoned branches since they would never lead to the else clause 1278 # being executed. 1279 1280 self.new_branch(node.else_ or NullBranch()) 1281 if node.else_ is not None: 1282 self.dispatch(node.else_) 1283 self.shelve_branch() 1284 1285 self.merge_branches() 1286 1287 visitTryFinally = NOP 1288 1289 visitTuple = OP 1290 1291 visitUnaryAdd = _visitUnary 1292 1293 visitUnarySub = _visitUnary 1294 1295 def visitWhile(self, node): 1296 self.use_name("__bool__", node) 1297 self.new_branchpoint(node) 1298 1299 # Propagate attribute usage to branches. 1300 1301 in_loop = self.in_loop 1302 self.in_loop = 1 1303 1304 # The test is evaluated initially and again in the loop. 1305 1306 self.dispatch(node.test) 1307 1308 self.new_branch(node) 1309 self.dispatch(node.body) 1310 1311 self.resume_continuing_branches() 1312 1313 self.dispatch(node.test) 1314 self.shelve_branch() 1315 1316 self.in_loop = in_loop 1317 1318 # A null branch is used to record a path around the loop. 1319 1320 self.new_branch(node.else_ or NullBranch()) 1321 self.shelve_branch() 1322 1323 self.merge_branches() 1324 1325 # The else clause is evaluated outside any branch. 1326 1327 if node.else_ is not None: 1328 self.dispatch(node.else_) 1329 1330 # Any suspended branches from the loop can now be resumed. 1331 1332 self.resume_broken_branches() 1333 1334 visitWith = NOP 1335 1336 visitYield = NOP 1337 1338 # vim: tabstop=4 expandtab shiftwidth=4