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