1 #!/usr/bin/env python 2 3 """ 4 Simplify AST structures for easier type propagation and analysis. The code in 5 this module processes AST trees originating from the compiler module and 6 produces a result tree consisting of instruction-oriented program nodes. 7 8 Copyright (C) 2006 Paul Boddie <paul@boddie.org.uk> 9 10 This software is free software; you can redistribute it and/or 11 modify it under the terms of the GNU General Public License as 12 published by the Free Software Foundation; either version 2 of 13 the License, or (at your option) any later version. 14 15 This software is distributed in the hope that it will be useful, 16 but WITHOUT ANY WARRANTY; without even the implied warranty of 17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 GNU General Public License for more details. 19 20 You should have received a copy of the GNU General Public 21 License along with this library; see the file LICENCE.txt 22 If not, write to the Free Software Foundation, Inc., 23 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA 24 25 -------- 26 27 To use this module, the easiest approach is to use the simplify function: 28 29 simplify(filename) 30 31 The more complicated approach involves first instantiating a Simplifier object: 32 33 simplifier = Simplifier() 34 35 Then, applying the simplifier to an AST tree: 36 37 module = compiler.parseFile(filename) 38 simplifier.process(module) 39 """ 40 41 from simplified import * 42 import compiler.ast 43 import os 44 45 class Simplifier(Visitor): 46 47 """ 48 A simplifying visitor for AST nodes. 49 50 Covered: Add, And, AssAttr, AssList, AssName, AssTuple, Assign, AugAssign, 51 Break, CallFunc, Class, Compare, Const, Continue, Dict, Discard, 52 Div, FloorDiv, For, From, Function, Getattr, Global, If, Import, 53 Invert, Keyword, Lambda, List, Module, Mul, Name, Not, Or, Pass, 54 Power, Print, Printnl, Raise, Return, Slice, Stmt, Sub, Subscript, 55 TryExcept, TryFinally, Tuple, While, UnaryAdd, UnarySub. 56 57 Missing: Assert, Backquote, Bitand, Bitor, Bitxor, Decorators, Ellipsis, 58 Exec, LeftShift, ListComp, ListCompFor, ListCompIf, RightShift, 59 Sliceobj, Yield. 60 """ 61 62 def __init__(self, builtins=0): 63 64 """ 65 Initialise the simplifier with the optional 'builtins' parameter 66 indicating whether the module contains the built-in classes and 67 functions. 68 """ 69 70 Visitor.__init__(self) 71 self.subprograms = [] # Subprograms outside the tree. 72 self.structures = [] # Structures/classes. 73 self.constants = {} # Constants. 74 self.current_subprograms = [] # Current subprograms being processed. 75 self.current_structures = [] # Current structures being processed. 76 self.builtins = builtins # Whether the builtins are being processed. 77 78 # Convenience attributes. 79 80 self.subnames = {} 81 82 # For compiler package mechanisms. 83 84 self.visitor = self 85 86 def process(self, node, name): 87 result = self.dispatch(node, name) 88 result.simplifier = self 89 return result 90 91 def dispatch_or_none(self, node, *args): 92 if node is not None: 93 return self.dispatch(node, *args) 94 else: 95 return LoadName(node, name="None") 96 97 # Top-level transformation. 98 99 def visitModule(self, module, name=None): 100 101 """ 102 Process the given 'module', producing a Module object which contains the 103 resulting program nodes. If the optional 'name' is provided, the 'name' 104 attribute is set on the Module object using a value other than None. 105 """ 106 107 result = self.module = Module(module, 1, name=name) 108 module_code = self.dispatch(module.node) 109 110 # NOTE: Constant initialisation necessary for annotation but perhaps 111 # NOTE: redundant in the program. 112 113 init_code = [] 114 for value, constant in self.constants.items(): 115 init_code.append( 116 StoreAttr( 117 lvalue=LoadRef(ref=constant), 118 name="__class__", 119 expr=LoadName(name=constant.typename) 120 ) 121 ) 122 123 # NOTE: Hack to ensure correct initialisation of constants. 124 125 if self.builtins: 126 result.code = module_code + init_code 127 else: 128 result.code = init_code + module_code 129 return result 130 131 # Node transformations. 132 133 def visitAdd(self, add): 134 return self._visitBinary(add, "__add__", "__radd__") 135 136 def visitAnd(self, and_): 137 138 """ 139 Make a subprogram for the 'and_' node and record its contents inside the 140 subprogram. Convert... 141 142 And (test) 143 (test) 144 ... 145 146 ...to: 147 148 Subprogram -> Conditional (test) -> ReturnFromBlock ... 149 (else) -> Conditional (test) -> ReturnFromBlock ... 150 (else) -> ... 151 """ 152 153 subprogram = Subprogram(name=None, module=self.module, internal=1, returns_value=1, params=[], star=None, dstar=None) 154 self.current_subprograms.append(subprogram) 155 156 # In the subprogram, make instructions which store each operand, test 157 # for each operand's truth status, and if appropriate return from the 158 # subprogram with the value of the operand. 159 160 last = and_.nodes[-1] 161 results = nodes = [] 162 163 for node in and_.nodes: 164 expr = self.dispatch(node) 165 166 # Return from the subprogram where the test is not satisfied. 167 168 if node is not last: 169 nodes += [ 170 StoreTemp(expr=expr), 171 Conditional( 172 test=self._visitNot(LoadTemp()), 173 body=[ 174 ReturnFromBlock( 175 expr=LoadTemp() 176 ) 177 ], 178 else_=[ 179 ReleaseTemp() 180 # Subsequent operations go here! 181 ] 182 ) 183 ] 184 185 # Put subsequent operations in the else section of this conditional. 186 187 nodes = nodes[-1].else_ 188 189 # For the last operation, return the result. 190 191 else: 192 nodes.append(ReturnFromBlock(expr=expr)) 193 194 # Finish the subprogram definition. 195 196 subprogram.code = results 197 198 self.current_subprograms.pop() 199 self.subprograms.append(subprogram); self.subnames[subprogram.full_name()] = subprogram 200 201 # Make an invocation of the subprogram. 202 203 result = InvokeBlock(and_, 1, produces_result=1) 204 result.expr = LoadRef(ref=subprogram) 205 return result 206 207 # Assignments. 208 209 def visitAssAttr(self, assattr, in_sequence=0): 210 expr = self._visitAssNameOrAttr(assattr, in_sequence) 211 lvalue = self.dispatch(assattr.expr) 212 result = StoreAttr(assattr, 1, name=assattr.attrname, lvalue=lvalue, expr=expr) 213 return result 214 215 def visitAssign(self, assign): 216 result = Assign(assign, 1) 217 store = StoreTemp(expr=self.dispatch(assign.expr)) 218 release = ReleaseTemp() 219 result.code = [store] + self.dispatches(assign.nodes, 0) + [release] 220 return result 221 222 def visitAssList(self, asslist, in_sequence=0): 223 if not in_sequence: 224 expr = LoadTemp() 225 else: 226 expr = InvokeFunction(expr=LoadAttr(expr=LoadTemp(), name="next")) 227 result = Assign(asslist, 1) 228 store = StoreTemp(expr=InvokeFunction(expr=LoadAttr(name="__iter__", expr=expr))) 229 release = ReleaseTemp() 230 result.code = [store] + self.dispatches(asslist.nodes, 1) + [release] 231 return result 232 233 visitAssTuple = visitAssList 234 235 def _visitAssNameOrAttr(self, node, in_sequence): 236 if not in_sequence: 237 return LoadTemp() 238 else: 239 return InvokeFunction(expr=LoadAttr(expr=LoadTemp(), name="next")) 240 241 def visitAssName(self, assname, in_sequence=0): 242 expr = self._visitAssNameOrAttr(assname, in_sequence) 243 result = StoreName(assname, 1, name=assname.name, expr=expr) 244 return result 245 246 augassign_methods = { 247 "+=" : "__iadd__", "-=" : "__isub__", "*=" : "__imul__", "/=" : "__idiv__", 248 "%=" : "__imod__", "**=" : "__ipow__", "<<=" : "__ilshift__", ">>=" : "__irshift__", 249 "&=" : "__iand__", "^=" : "__ixor__", "|=" : "__ior__" 250 } 251 252 def visitAugAssign(self, augassign): 253 254 """ 255 Convert the augmented assignment... 256 257 AugAssign (node) -> Name | Getattr | Slice | Subscript 258 (op) 259 (expr) 260 261 ...to: 262 263 Assign (code) -> StoreTemp (expr) -> InvokeFunction (expr) -> LoadAttr (expr) -> <name> 264 (name) -> <op> 265 StoreName (name) -> <name> 266 (expr) -> LoadTemp 267 ReleaseTemp 268 """ 269 270 result = Assign(augassign, 1) 271 expr = self.dispatch(augassign.expr) 272 273 # Simple augmented assignment: name += expr 274 275 if isinstance(augassign.node, compiler.ast.Name): 276 result.code = [ 277 StoreTemp( 278 expr=InvokeFunction( 279 args=[expr], 280 star=None, 281 dstar=None, 282 expr=LoadAttr( 283 expr=self.dispatch(augassign.node), 284 name=self.augassign_methods[augassign.op] 285 ) 286 ) 287 ), 288 StoreName( 289 expr=LoadTemp(), 290 name=augassign.node.name), 291 ReleaseTemp() 292 ] 293 294 # Complicated augmented assignment: lvalue.attr += expr 295 296 elif isinstance(augassign.node, compiler.ast.Getattr): 297 298 # <lvalue> -> setattr(<lvalue>, getattr(<lvalue>, "attr").__xxx__(expr)) 299 300 result.code = [ 301 StoreTemp( 302 index="expr", 303 expr=self.dispatch(augassign.node.expr) 304 ), 305 StoreTemp( 306 expr=InvokeFunction( 307 args=[expr], star=None, dstar=None, 308 expr=LoadAttr( 309 expr=LoadAttr(augassign.node, 1, 310 expr=LoadTemp(index="expr"), 311 name=augassign.node.attrname 312 ), 313 name=self.augassign_methods[augassign.op] 314 ) 315 ) 316 ), 317 StoreAttr( 318 expr=LoadTemp(), 319 lvalue=LoadTemp(index="expr"), 320 name=augassign.node.attrname 321 ), 322 ReleaseTemp(index="expr"), 323 ReleaseTemp() 324 ] 325 326 # Complicated augassign using slices: lvalue[lower:upper] += expr 327 328 elif isinstance(augassign.node, compiler.ast.Slice): 329 330 # <lvalue>, <lower>, <upper> -> <lvalue>.__setslice__(<lower>, <upper>, <lvalue>.__getslice__(<lower>, <upper>).__xxx__(expr)) 331 332 result.code = [ 333 StoreTemp( 334 index="expr", 335 expr=self.dispatch(augassign.node.expr) 336 ), 337 StoreTemp( 338 index="lower", 339 expr=self.dispatch_or_none(augassign.node.lower) 340 ), 341 StoreTemp( 342 index="upper", 343 expr=self.dispatch_or_none(augassign.node.upper) 344 ), 345 StoreTemp( 346 expr=InvokeFunction( 347 args=[expr], star=None, dstar=None, 348 expr=LoadAttr( 349 expr=self._visitSlice( 350 augassign.node, 351 LoadTemp(index="expr"), 352 LoadTemp(index="lower"), 353 LoadTemp(index="upper"), 354 "OP_APPLY"), 355 name=self.augassign_methods[augassign.op] 356 ) 357 ) 358 ), 359 self._visitSlice( 360 augassign.node, 361 LoadTemp(index="expr"), 362 LoadTemp(index="lower"), 363 LoadTemp(index="upper"), 364 "OP_ASSIGN", 365 LoadTemp() 366 ), 367 ReleaseTemp(index="expr"), 368 ReleaseTemp(index="lower"), 369 ReleaseTemp(index="upper"), 370 ReleaseTemp() 371 ] 372 373 # Complicated augassign using subscripts: lvalue[subs] += expr 374 375 elif isinstance(augassign.node, compiler.ast.Subscript): 376 377 # <lvalue>, <subs> -> <lvalue>.__setitem__(<subs>, <lvalue>.__getitem__(<subs>).__xxx__(expr)) 378 379 result.code = [ 380 StoreTemp(index="expr", expr=self.dispatch(augassign.node.expr)), 381 StoreTemp(index="subs", expr=self._visitSubscriptSubs(augassign.node, augassign.node.subs)), 382 StoreTemp( 383 expr=InvokeFunction( 384 args=[expr], star=None, dstar=None, 385 expr=LoadAttr( 386 expr=self._visitSubscript( 387 augassign.node, 388 LoadTemp(index="expr"), 389 LoadTemp(index="subs"), 390 "OP_APPLY" 391 ), 392 name=self.augassign_methods[augassign.op] 393 ) 394 ) 395 ), 396 self._visitSubscript( 397 augassign.node, 398 LoadTemp(index="expr"), 399 LoadTemp(index="subs"), 400 "OP_ASSIGN", 401 LoadTemp() 402 ), 403 ReleaseTemp(index="expr"), 404 ReleaseTemp(index="subs"), 405 ReleaseTemp() 406 ] 407 408 else: 409 raise NotImplementedError, augassign.node.__class__ 410 411 return result 412 413 def visitBreak(self, break_): 414 result = ReturnFromBlock(break_, 1) 415 return result 416 417 def visitCallFunc(self, callfunc): 418 result = InvokeFunction(callfunc, 1, star=None, dstar=None, args=self.dispatches(callfunc.args)) 419 if callfunc.star_args is not None: 420 result.star = self.dispatch(callfunc.star_args) 421 if callfunc.dstar_args is not None: 422 result.dstar = self.dispatch(callfunc.dstar_args) 423 result.expr = self.dispatch(callfunc.node) 424 return result 425 426 def visitClass(self, class_): 427 428 # Add "object" if the class is not "object" and has an empty bases list. 429 430 if class_.name != "object" and not class_.bases: 431 bases = [compiler.ast.Name("object")] 432 else: 433 bases = class_.bases 434 435 structure = Class(name=class_.name, module=self.module, bases=self.dispatches(bases)) 436 self.structures.append(structure) 437 438 # Make a subprogram which initialises the class structure. 439 440 subprogram = Subprogram(name=None, module=self.module, structure=structure, params=[], star=None, dstar=None) 441 self.current_subprograms.append(subprogram) 442 self.current_structures.append(structure) # mostly for name construction 443 444 # The class is initialised using the code found inside. 445 446 subprogram.code = self.dispatch(class_.code) + [ReturnFromBlock()] 447 448 self.current_structures.pop() 449 self.current_subprograms.pop() 450 self.subprograms.append(subprogram); self.subnames[subprogram.full_name()] = subprogram 451 452 # Make a definition of the class associating it with a name. 453 454 result = Assign( 455 code=[ 456 StoreName(class_, 1, # defines the class 457 name=class_.name, 458 expr=LoadRef(ref=structure) 459 ), 460 InvokeBlock( 461 share_locals=0, # override the local sharing usually in InvokeBlock 462 expr=LoadRef(ref=subprogram) 463 ) 464 ] 465 ) 466 return result 467 468 comparison_methods = { 469 "==" : "__eq__", "!=" : "__ne__", "<" : "__lt__", "<=" : "__le__", 470 ">=" : "__ge__", ">" : "__gt__", "is" : None, "is not" : None 471 } 472 473 def visitCompare(self, compare): 474 475 """ 476 Make a subprogram for the 'compare' node and record its contents inside 477 the subprogram. Convert... 478 479 Compare (expr) 480 (name/node) 481 ... 482 483 ...to: 484 485 InvokeBlock -> Subprogram -> Conditional (test) -> (body) 486 (else) -> Conditional (test) -> (body) 487 (else) -> ... 488 """ 489 490 subprogram = Subprogram(name=None, module=self.module, internal=1, returns_value=1, params=[], star=None, dstar=None) 491 self.current_subprograms.append(subprogram) 492 493 # In the subprogram, make instructions which invoke a method on the 494 # first operand of each operand pair and, if appropriate, return with 495 # the value from that method. 496 497 last = compare.ops[-1] 498 previous = self.dispatch(compare.expr) 499 results = nodes = [] 500 501 # For viewing purposes, record invocations on the AST node. 502 503 compare._ops = [] 504 505 for op in compare.ops: 506 op_name, node = op 507 expr = self.dispatch(node) 508 509 # Identify the operation and produce the appropriate method call. 510 511 method_name = self.comparison_methods[op_name] 512 if method_name: 513 invocation = InvokeFunction( 514 expr=LoadAttr( 515 expr=previous, 516 name=method_name), 517 args=[expr], 518 star=None, 519 dstar=None) 520 521 elif op_name == "is": 522 invocation = InvokeFunction( 523 expr=LoadName(name="__is__"), 524 args=[previous, expr], 525 star=None, 526 dstar=None) 527 528 elif op_name == "is not": 529 invocation = Not( 530 expr=InvokeFunction( 531 expr=LoadName(name="__is__"), 532 args=[previous, expr], 533 star=None, 534 dstar=None) 535 ) 536 else: 537 raise NotImplementedError, op_name 538 539 nodes.append(StoreTemp(expr=invocation)) 540 compare._ops.append(invocation) 541 542 # Return from the subprogram where the test is not satisfied. 543 544 if op is not last: 545 nodes.append( 546 Conditional( 547 test=self._visitNot(LoadTemp()), 548 body=[ 549 ReturnFromBlock(expr=LoadTemp()) 550 ], 551 else_=[ 552 ReleaseTemp() 553 # Subsequent operations go here! 554 ] 555 ) 556 ) 557 558 # Put subsequent operations in the else section of this conditional. 559 560 nodes = nodes[-1].else_ 561 562 # For the last operation, return the result. 563 564 else: 565 nodes.append( 566 ReturnFromBlock(expr=LoadTemp(release=1)) 567 ) 568 569 previous = expr 570 571 # Finish the subprogram definition. 572 573 subprogram.code = results 574 575 self.current_subprograms.pop() 576 self.subprograms.append(subprogram); self.subnames[subprogram.full_name()] = subprogram 577 578 # Make an invocation of the subprogram. 579 580 result = InvokeBlock(compare, 1, produces_result=1) 581 result.expr = LoadRef(ref=subprogram) 582 return result 583 584 def visitConst(self, const): 585 key = "%s-%s" % (const.value.__class__.__name__, const.value) 586 if not self.constants.has_key(key): 587 self.constants[key] = Constant(name=repr(const.value), value=const.value) 588 result = LoadRef(const, 1, ref=self.constants[key]) 589 return result 590 591 def visitContinue(self, continue_): 592 result = InvokeBlock(continue_, 1, 593 expr=LoadRef(ref=self.current_subprograms[-1]) 594 ) 595 return result 596 597 def visitDict(self, dict): 598 result = InvokeFunction(dict, 1, expr=LoadName(name="dict"), star=None, dstar=None) 599 args = [] 600 for key, value in dict.items: 601 tuple = InvokeFunction(expr=LoadName(name="tuple"), star=None, dstar=None) 602 tuple.set_args([self.dispatch(key), self.dispatch(value)]) 603 args.append(tuple) 604 result.set_args(args) 605 return result 606 607 def visitDiscard(self, discard): 608 return self.dispatch(discard.expr) 609 610 def visitDiv(self, div): 611 return self._visitBinary(div, "__div__", "__rdiv__") 612 613 def visitFloorDiv(self, floordiv): 614 return self._visitBinary(floordiv, "__floordiv__", "__rfloordiv__") 615 616 def visitFor(self, for_): 617 618 """ 619 Make a subprogram for the 'for_' node and record its contents inside the 620 subprogram. Convert... 621 622 For (assign) 623 (body) 624 (else) 625 626 ...to: 627 628 Assign (assign #1) 629 Invoke -> Subprogram -> Try (body) -> (assign #2) 630 (body) 631 Invoke subprogram 632 (handler) -> ... 633 (else) -> ... 634 """ 635 636 subprogram = Subprogram(name=None, module=self.module, internal=1, returns_value=0, params=[], star=None, dstar=None) 637 self.current_subprograms.append(subprogram) 638 639 # Always return from conditional sections/subprograms. 640 641 if for_.else_ is not None: 642 else_stmt = self.dispatch(for_.else_) + [ReturnFromBlock()] 643 else: 644 else_stmt = [ReturnFromBlock()] 645 646 # Wrap the assignment in a try...except statement. 647 # Inside the body, add a recursive invocation to the subprogram. 648 649 subprogram.code = [ 650 Try( 651 body=[ 652 Assign( 653 code=[ 654 StoreTemp(expr=InvokeFunction(expr=LoadAttr(expr=LoadTemp(), name="next"))), 655 self.dispatch(for_.assign), 656 ReleaseTemp() 657 ]) 658 ] + self.dispatch(for_.body) + [ 659 InvokeBlock( 660 expr=LoadRef(ref=subprogram) 661 ) 662 ], 663 handler=[ 664 Conditional( 665 test=InvokeFunction( 666 expr=LoadName(name="isinstance"), 667 args=[LoadExc(), LoadName(name="StopIteration")], 668 star=None, 669 dstar=None), 670 body=else_stmt, 671 else_=[Raise(expr=LoadExc())] 672 ) 673 ], 674 else_=[], 675 finally_=[] 676 ), 677 ReturnFromBlock() 678 ] 679 680 # Finish the subprogram definition. 681 682 self.current_subprograms.pop() 683 self.subprograms.append(subprogram); self.subnames[subprogram.full_name()] = subprogram 684 685 # Obtain an iterator for the sequence involved. 686 # Then, make an invocation of the subprogram. 687 688 result = Assign(for_, 1, 689 code=[ 690 StoreTemp( 691 expr=InvokeFunction( 692 expr=LoadAttr( 693 name="__iter__", 694 expr=self.dispatch(for_.list) 695 ) 696 ) 697 ), 698 InvokeBlock(expr=LoadRef(ref=subprogram)), 699 ReleaseTemp() 700 ] 701 ) 702 703 # Make nice annotations for the viewer. 704 705 for_._iter_call = result.code[0].expr 706 for_._next_call = subprogram.code[0].body[0].code[0].expr 707 708 return result 709 710 def visitFrom(self, from_): 711 result = Assign(from_, 1) 712 code = [] 713 code.append(StoreTemp(expr=Import(name=from_.modname))) 714 for name, alias in from_.names: 715 code.append( 716 StoreName( 717 expr=LoadAttr( 718 expr=LoadTemp(), 719 name=name), 720 name=(alias or name) 721 ) 722 ) 723 code.append(ReleaseTemp()) 724 result.code = code 725 return result 726 727 def _visitFunction(self, function, subprogram): 728 729 """ 730 A common function generator which transforms the given 'function' node 731 and initialises the given 'subprogram' appropriately. 732 """ 733 734 # Discover star and dstar parameters. 735 736 if function.flags & 4 != 0: 737 has_star = 1 738 else: 739 has_star = 0 740 if function.flags & 8 != 0: 741 has_dstar = 1 742 else: 743 has_dstar = 0 744 745 # Discover the number of defaults and positional parameters. 746 747 ndefaults = len(function.defaults) 748 npositional = len(function.argnames) - has_star - has_dstar 749 750 # Produce star and dstar parameters with appropriate defaults. 751 752 if has_star: 753 star = ( 754 function.argnames[npositional], 755 InvokeFunction(expr=LoadName(name="list")) 756 ) 757 else: 758 star = None 759 if has_dstar: 760 dstar = ( 761 function.argnames[npositional + has_star], 762 InvokeFunction(expr=LoadName(name="dict")) 763 ) 764 else: 765 dstar = None 766 767 params = [] 768 for i in range(0, npositional - ndefaults): 769 params.append((function.argnames[i], None)) 770 771 # Process defaults. 772 773 for i in range(0, ndefaults): 774 default = function.defaults[i] 775 if default is not None: 776 params.append((function.argnames[npositional - ndefaults + i], self.dispatch(default))) 777 else: 778 params.append((function.argnames[npositional - ndefaults + i], None)) 779 780 subprogram.params = params 781 subprogram.star = star 782 subprogram.dstar = dstar 783 self.subprograms.append(subprogram); self.subnames[subprogram.full_name()] = subprogram 784 785 def visitFunction(self, function): 786 787 """ 788 Make a subprogram for the 'function' and record it outside the main 789 tree. Produce something like the following: 790 791 StoreName (name) 792 (expr) -> LoadRef (ref) -> Subprogram (params) 793 (star) 794 (dstar) 795 """ 796 797 subprogram = Subprogram(name=function.name, module=self.module, structures=self.current_structures[:], 798 internal=0, returns_value=1, star=None, dstar=None) 799 800 self.current_subprograms.append(subprogram) 801 subprogram.code = self.dispatch(function.code) + [ReturnFromFunction()] 802 self.current_subprograms.pop() 803 self._visitFunction(function, subprogram) 804 805 # Make a definition of the function associating it with a name. 806 807 result = StoreName(function, 1, name=function.name, expr=LoadRef(ref=subprogram)) 808 return result 809 810 def visitGetattr(self, getattr): 811 result = LoadAttr(getattr, 1, 812 name=getattr.attrname, 813 expr=self.dispatch(getattr.expr) 814 ) 815 return result 816 817 def visitGlobal(self, global_): 818 result = Global(global_, 1, 819 names=global_.names 820 ) 821 return result 822 823 def visitIf(self, if_): 824 825 """ 826 Make conditionals for each test from an 'if_' AST node, adding the body 827 and putting each subsequent test as part of the conditional's else 828 section. 829 830 Convert... 831 832 If (test/body) 833 (test/body) 834 ... 835 (else/body) 836 837 ...to: 838 839 Conditional (test) -> (body) 840 (else) -> Conditional (test) -> (body) 841 (else) -> ... 842 """ 843 844 845 results = nodes = [] 846 847 # Produce something like... 848 # expr.__bool__() ? body 849 850 first = 1 851 for compare, stmt in if_.tests: 852 853 # Set the first as the defining node. 854 855 test = Conditional(if_, first, 856 test=InvokeFunction( 857 expr=LoadAttr( 858 expr=self.dispatch(compare), 859 name="__bool__" 860 ), 861 ) 862 ) 863 test.body = self.dispatch(stmt) 864 nodes.append(test) 865 nodes = test.else_ = [] 866 first = 0 867 868 # Add the compound statement from any else clause to the end. 869 870 if if_.else_ is not None: 871 nodes += self.dispatch(if_.else_) 872 873 result = results[0] 874 return result 875 876 def visitImport(self, import_): 877 result = Assign(import_, 1) 878 code = [] 879 for path, alias in import_.names: 880 importer = Import(name=path) 881 top = alias or path.split(".")[0] 882 code.append(StoreName(expr=importer, name=top)) 883 result.code = code 884 return result 885 886 def visitInvert(self, invert): 887 return self._visitUnary(invert, "__invert__") 888 889 def visitKeyword(self, keyword): 890 result = Keyword(keyword, 1, 891 name=keyword.name, 892 expr=self.dispatch(keyword.expr) 893 ) 894 return result 895 896 def visitLambda(self, lambda_): 897 898 # Make a subprogram for the function and record it outside the main 899 # tree. 900 901 subprogram = Subprogram(name=None, module=self.module, internal=0, returns_value=1, star=None, dstar=None) 902 self.current_subprograms.append(subprogram) 903 subprogram.code = [ReturnFromFunction(expr=self.dispatch(lambda_.code))] 904 self.current_subprograms.pop() 905 self._visitFunction(lambda_, subprogram) 906 907 # Get the subprogram reference to the lambda. 908 909 return LoadRef(lambda_, 1, ref=subprogram) 910 911 def visitList(self, list): 912 return self._visitBuiltin(list, "list") 913 914 def visitMul(self, mul): 915 return self._visitBinary(mul, "__mul__", "__rmul__") 916 917 def visitName(self, name): 918 result = LoadName(name, 1, name=name.name) 919 return result 920 921 def _visitNot(self, expr, not_=None): 922 invocation = InvokeFunction( 923 expr=LoadAttr( 924 expr=expr, 925 name="__bool__" 926 ), 927 ) 928 if not_ is not None: 929 result = Not(not_, 1, expr=invocation) 930 else: 931 result = Not(expr=invocation) 932 return result 933 934 def visitNot(self, not_): 935 return self._visitNot(self.dispatch(not_.expr), not_) 936 937 def visitOr(self, or_): 938 939 """ 940 Make a subprogram for the 'or_' node and record its contents inside the 941 subprogram. Convert... 942 943 Or (test) 944 (test) 945 ... 946 947 ...to: 948 949 Subprogram -> Conditional (test) -> ReturnFromBlock ... 950 (else) -> Conditional (test) -> ReturnFromBlock ... 951 (else) -> ... 952 """ 953 954 subprogram = Subprogram(name=None, module=self.module, internal=1, returns_value=1, params=[], star=None, dstar=None) 955 self.current_subprograms.append(subprogram) 956 957 # In the subprogram, make instructions which store each operand, test 958 # for each operand's truth status, and if appropriate return from the 959 # subprogram with the value of the operand. 960 961 last = or_.nodes[-1] 962 results = nodes = [] 963 964 for node in or_.nodes: 965 expr = self.dispatch(node) 966 967 # Return from the subprogram where the test is satisfied. 968 969 if node is not last: 970 nodes.append(StoreTemp(expr=expr)) 971 invocation = InvokeFunction(expr=LoadAttr(expr=LoadTemp(), name="__bool__")) 972 test = Conditional(test=invocation, body=[ReturnFromBlock(expr=LoadTemp())]) 973 nodes.append(test) 974 975 # Put subsequent operations in the else section of this conditional. 976 977 nodes = test.else_ = [ReleaseTemp()] 978 979 # For the last operation, return the result. 980 981 else: 982 nodes.append( 983 ReturnFromBlock(expr=expr) 984 ) 985 986 # Finish the subprogram definition. 987 988 subprogram.code = results 989 990 self.current_subprograms.pop() 991 self.subprograms.append(subprogram); self.subnames[subprogram.full_name()] = subprogram 992 993 # Make an invocation of the subprogram. 994 995 result = InvokeBlock(or_, 1, produces_result=1) 996 result.expr = LoadRef(ref=subprogram) 997 return result 998 999 def visitPass(self, pass_): 1000 return Pass(pass_, 1) 1001 1002 def visitPower(self, power): 1003 return self._visitBinary(power, "__pow__", "__rpow__") 1004 1005 def visitPrint(self, print_): 1006 1007 """ 1008 Convert... 1009 1010 Print (dest) -> 1011 (nodes) 1012 1013 ...to: 1014 1015 StoreTemp (index) -> "print" 1016 (expr) -> LoadAttr (expr) -> (dest) 1017 (name) -> "write" 1018 InvokeFunction (expr) -> LoadTemp (index) -> "print" 1019 (args) -> [(node)] 1020 ReleaseTemp (index) -> "print" 1021 """ 1022 1023 if print_.dest is not None: 1024 dest = self.dispatch(print_.dest) 1025 else: 1026 dest = self.dispatch(compiler.ast.Name("stdout")) 1027 1028 result = Assign(print_, 1, 1029 code=[ 1030 StoreTemp( 1031 index="print", 1032 expr=LoadAttr( 1033 expr=dest, 1034 name="write" 1035 ) 1036 ) 1037 ] 1038 ) 1039 1040 for node in print_.nodes: 1041 result.code.append( 1042 InvokeFunction( 1043 expr=LoadTemp(index="print"), 1044 args=[self.dispatch(node)], 1045 star=None, 1046 dstar=None 1047 ) 1048 ) 1049 1050 result.code.append( 1051 ReleaseTemp(index="print") 1052 ) 1053 1054 return result 1055 1056 def visitPrintnl(self, printnl): 1057 result = self.visitPrint(printnl) 1058 result.code.insert( 1059 len(result.code) - 1, 1060 InvokeFunction( 1061 expr=LoadTemp(index="print"), 1062 args=[self.dispatch(compiler.ast.Const("\n"))], 1063 star=None, 1064 dstar=None 1065 ) 1066 ) 1067 return result 1068 1069 def visitRaise(self, raise_): 1070 result = Raise(raise_, 1) 1071 if raise_.expr2 is None: 1072 result.expr = self.dispatch(raise_.expr1) 1073 else: 1074 result.expr = InvokeFunction( 1075 expr=self.dispatch(raise_.expr1), 1076 args=[self.dispatch(raise_.expr2)], 1077 star=None, 1078 dstar=None 1079 ) 1080 if raise_.expr3 is not None: 1081 result.traceback = self.dispatch(raise_.expr3) 1082 else: 1083 result.traceback = None 1084 return result 1085 1086 def visitReturn(self, return_): 1087 result = ReturnFromFunction(return_, 1, 1088 expr=self.dispatch(return_.value) 1089 ) 1090 return result 1091 1092 def _visitSlice(self, slice, expr, lower, upper, flags, value=None): 1093 if flags == "OP_ASSIGN": 1094 result = InvokeFunction(slice, 1, 1095 expr=LoadAttr( 1096 expr=expr, 1097 name="__setslice__" 1098 ), 1099 star=None, 1100 dstar=None, 1101 args=[lower, upper, value] 1102 ) 1103 elif flags == "OP_APPLY": 1104 args = [] 1105 result = InvokeFunction(slice, 1, 1106 expr=LoadAttr( 1107 expr=expr, 1108 name="__getslice__" 1109 ), 1110 star=None, 1111 dstar=None, 1112 args=[lower, upper] 1113 ) 1114 elif flags == "OP_DELETE": 1115 args = [] 1116 result = InvokeFunction(slice, 1, 1117 expr=LoadAttr( 1118 expr=expr, 1119 name="__delslice__" 1120 ), 1121 star=None, 1122 dstar=None, 1123 args=[lower, upper] 1124 ) 1125 else: 1126 raise NotImplementedError, flags 1127 1128 return result 1129 1130 def visitSlice(self, slice, in_sequence=0): 1131 return self._visitSlice(slice, self.dispatch(slice.expr), self.dispatch_or_none(slice.lower), 1132 self.dispatch_or_none(slice.upper), slice.flags, self._visitAssNameOrAttr(slice, in_sequence)) 1133 1134 def visitStmt(self, stmt): 1135 return self.dispatches(stmt.nodes) 1136 1137 def visitSub(self, sub): 1138 return self._visitBinary(sub, "__sub__", "__rsub__") 1139 1140 def _visitSubscript(self, subscript, expr, subs, flags, value=None): 1141 if flags == "OP_ASSIGN": 1142 result = InvokeFunction(subscript, 1, 1143 expr=LoadAttr( 1144 expr=expr, 1145 name="__setitem__" 1146 ), 1147 star=None, 1148 dstar=None, 1149 args=[subs, value] 1150 ) 1151 elif flags == "OP_APPLY": 1152 args = [] 1153 result = InvokeFunction(subscript, 1, 1154 expr=LoadAttr( 1155 expr=expr, 1156 name="__getitem__" 1157 ), 1158 star=None, 1159 dstar=None, 1160 args=[subs] 1161 ) 1162 elif flags == "OP_DELETE": 1163 args = [] 1164 result = InvokeFunction(subscript, 1, 1165 expr=LoadAttr( 1166 expr=expr, 1167 name="__delitem__" 1168 ), 1169 star=None, 1170 dstar=None, 1171 args=[subs] 1172 ) 1173 else: 1174 raise NotImplementedError, flags 1175 1176 return result 1177 1178 def _visitSubscriptSubs(self, node, subs): 1179 if len(subs) == 1: 1180 return self.dispatch(subs[0]) 1181 else: 1182 return InvokeFunction(node, 1, 1183 expr=LoadName(name="tuple"), 1184 args=self.dispatches(subs), 1185 star=None, 1186 dstar=None 1187 ) 1188 1189 def visitSubscript(self, subscript, in_sequence=0): 1190 return self._visitSubscript( 1191 subscript, self.dispatch(subscript.expr), self._visitSubscriptSubs(subscript, subscript.subs), subscript.flags, 1192 self._visitAssNameOrAttr(subscript, in_sequence) 1193 ) 1194 1195 def visitTryExcept(self, tryexcept): 1196 1197 """ 1198 Make conditionals for each handler associated with a 'tryexcept' node. 1199 1200 Convert... 1201 1202 TryExcept (body) 1203 (else) 1204 (spec/assign/stmt) 1205 ... 1206 1207 ...to: 1208 1209 Try (body) 1210 (else) 1211 (handler) -> Conditional (test) -> (stmt) 1212 (body) -> ... 1213 (else) -> Conditional (test) -> (stmt) 1214 (body) -> ... 1215 (else) -> ... 1216 """ 1217 1218 result = Try(tryexcept, 1, body=[], else_=[], finally_=[]) 1219 1220 if tryexcept.body is not None: 1221 result.body = self.dispatch(tryexcept.body) 1222 if tryexcept.else_ is not None: 1223 result.else_ = self.dispatch(tryexcept.else_) 1224 1225 results = nodes = [] 1226 catch_all = 0 1227 1228 for spec, assign, stmt in tryexcept.handlers: 1229 1230 # If no specification exists, produce an unconditional block. 1231 1232 if spec is None: 1233 nodes += self.dispatch(stmt) 1234 catch_all = 1 1235 1236 # Produce an exception value check. 1237 1238 else: 1239 test = Conditional( 1240 isolate_test=1, 1241 test=CheckExc(expr=LoadExc(), choices=self._visitTryExcept(spec)) 1242 ) 1243 test.body = [] 1244 1245 if assign is not None: 1246 test.body.append( 1247 Assign( 1248 code=[ 1249 StoreTemp(expr=LoadExc()), 1250 self.dispatch(assign), 1251 ReleaseTemp() 1252 ] 1253 ) 1254 ) 1255 1256 # Always return from conditional sections. 1257 1258 test.body += self.dispatch(stmt) + [ReturnFromBlock()] 1259 nodes.append(test) 1260 nodes = test.else_ = [] 1261 1262 # Add a raise operation to deal with unhandled exceptions. 1263 1264 if not catch_all: 1265 nodes.append( 1266 Raise( 1267 expr=LoadExc()) 1268 ) 1269 1270 result.handler = results 1271 return result 1272 1273 def _visitTryExcept(self, spec): 1274 1275 "Return a list of nodes for the given exception type 'spec'." 1276 1277 if isinstance(spec, compiler.ast.Tuple): 1278 nodes = [] 1279 for node in spec.nodes: 1280 nodes += self._visitTryExcept(node) 1281 else: 1282 nodes = [self.dispatch(spec)] 1283 return nodes 1284 1285 def visitTryFinally(self, tryfinally): 1286 result = Try(tryfinally, 1, body=[], else_=[], finally_=[]) 1287 if tryfinally.body is not None: 1288 result.body = self.dispatch(tryfinally.body) 1289 if tryfinally.final is not None: 1290 result.finally_ = self.dispatch(tryfinally.final) 1291 return result 1292 1293 def visitTuple(self, tuple): 1294 return self._visitBuiltin(tuple, "tuple") 1295 1296 def visitUnaryAdd(self, unaryadd): 1297 return self._visitUnary(unaryadd, "__pos__") 1298 1299 def visitUnarySub(self, unarysub): 1300 return self._visitUnary(unarysub, "__neg__") 1301 1302 def visitWhile(self, while_): 1303 1304 """ 1305 Make a subprogram for the 'while' node and record its contents inside the 1306 subprogram. Convert... 1307 1308 While (test) -> (body) 1309 (else) 1310 1311 ...to: 1312 1313 Subprogram -> Conditional (test) -> (body) -> Invoke subprogram 1314 (else) -> Conditional (test) -> ReturnFromBlock ... 1315 (else) -> ... 1316 """ 1317 1318 subprogram = Subprogram(name=None, module=self.module, internal=1, returns_value=0, params=[], star=None, dstar=None) 1319 self.current_subprograms.append(subprogram) 1320 1321 # Include a conditional statement in the subprogram. 1322 # Inside the conditional, add a recursive invocation to the subprogram 1323 # if the test condition was satisfied. 1324 # Return within the main section of the loop. 1325 1326 test = Conditional( 1327 test=InvokeFunction( 1328 expr=LoadAttr( 1329 expr=self.dispatch(while_.test), 1330 name="__bool__"), 1331 ), 1332 body=self.dispatch(while_.body) + [ 1333 InvokeBlock( 1334 expr=LoadRef(ref=subprogram) 1335 ), 1336 ReturnFromBlock() 1337 ], 1338 else_=[] 1339 ) 1340 1341 # Provide the else section, if present, along with an explicit return. 1342 1343 if while_.else_ is not None: 1344 test.else_ = self.dispatch(while_.else_) + [ReturnFromBlock()] 1345 1346 # Finish the subprogram definition. 1347 1348 subprogram.code = [test] 1349 1350 self.current_subprograms.pop() 1351 self.subprograms.append(subprogram); self.subnames[subprogram.full_name()] = subprogram 1352 1353 # Make an invocation of the subprogram. 1354 1355 result = InvokeBlock(while_, 1, 1356 expr=LoadRef(ref=subprogram) 1357 ) 1358 1359 # Make nice annotations for the viewer. 1360 1361 while_._test_call = subprogram.code[0].test 1362 1363 return result 1364 1365 # Convenience methods. 1366 1367 def _visitBinary(self, binary, left_name, right_name): 1368 1369 """ 1370 Emulate the current mechanisms by producing nodes as follows: 1371 1372 InvokeBlock -> Subprogram -> Try (body) -> ReturnFromBlock (expr) -> x.__add__(y) 1373 (else) 1374 (handler) -> Conditional (test) -> CheckExc (expr) -> LoadExc 1375 (choices) -> LoadName TypeError 1376 (body) -> ReturnFromBlock (expr) -> y.__radd__(x) 1377 (else) 1378 """ 1379 1380 subprogram = Subprogram(name=None, module=self.module, internal=1, returns_value=1, params=[], star=None, dstar=None) 1381 self.current_subprograms.append(subprogram) 1382 1383 subprogram.code = [ 1384 Try(binary, 1, 1385 body=[ 1386 ReturnFromBlock( 1387 expr=InvokeFunction( 1388 expr=LoadAttr(expr=self.dispatch(binary.left), name=left_name), 1389 args=[self.dispatch(binary.right)], 1390 star=None, 1391 dstar=None) 1392 ) 1393 ], 1394 else_=[], 1395 finally_=[], 1396 handler=[ 1397 Conditional( 1398 test=CheckExc(expr=LoadExc(), choices=[LoadName(name="TypeError")]), 1399 body=[ 1400 ReturnFromBlock( 1401 expr=InvokeFunction( 1402 expr=LoadAttr(expr=self.dispatch(binary.right), name=right_name), 1403 args=[self.dispatch(binary.left)], 1404 star=None, 1405 dstar=None) 1406 ) 1407 ], 1408 else_=[] 1409 ) 1410 ] 1411 ) 1412 ] 1413 1414 self.current_subprograms.pop() 1415 self.subprograms.append(subprogram); self.subnames[subprogram.full_name()] = subprogram 1416 1417 result = InvokeBlock( 1418 produces_result=1, 1419 expr=LoadRef(ref=subprogram) 1420 ) 1421 1422 # Make nice annotations for the viewer. 1423 1424 binary._left_call = subprogram.code[0].body[0].expr 1425 binary._right_call = subprogram.code[0].handler[0].body[0].expr 1426 1427 return result 1428 1429 def _visitBuiltin(self, builtin, name): 1430 result = InvokeFunction(builtin, 1, expr=LoadName(name=name), args=self.dispatches(builtin.nodes), star=None, dstar=None) 1431 return result 1432 1433 def _visitUnary(self, unary, name): 1434 result = InvokeFunction(unary, 1, 1435 expr=LoadAttr( 1436 expr=self.dispatch(unary.expr), 1437 name=name 1438 ) 1439 ) 1440 1441 # Make nice annotations for the viewer. 1442 1443 unary._unary_call = result 1444 1445 return result 1446 1447 # Convenience functions. 1448 1449 def simplify(filename, builtins=0): 1450 1451 """ 1452 Simplify the module stored in the file with the given 'filename'. 1453 1454 If the optional 'builtins' parameter is set to a true value (the default 1455 being a false value), then the module is considered as the builtins module. 1456 """ 1457 1458 simplifier = Simplifier(builtins) 1459 module = compiler.parseFile(filename) 1460 compiler.misc.set_filename(filename, module) 1461 if builtins: 1462 name = "__builtins__" 1463 else: 1464 path, ext = os.path.splitext(filename) 1465 path, name = os.path.split(path) 1466 simplified = simplifier.process(module, name) 1467 return simplified 1468 1469 # vim: tabstop=4 expandtab shiftwidth=4