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