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 if not self.constants.has_key(const.value): 586 self.constants[const.value] = Constant(name=repr(const.value), value=const.value) 587 result = LoadRef(const, 1, ref=self.constants[const.value]) 588 return result 589 590 def visitContinue(self, continue_): 591 result = InvokeBlock(continue_, 1, 592 expr=LoadRef(ref=self.current_subprograms[-1]) 593 ) 594 return result 595 596 def visitDict(self, dict): 597 result = InvokeFunction(dict, 1, expr=LoadName(name="dict"), star=None, dstar=None) 598 args = [] 599 for key, value in dict.items: 600 tuple = InvokeFunction(expr=LoadName(name="tuple"), star=None, dstar=None) 601 tuple.set_args([self.dispatch(key), self.dispatch(value)]) 602 args.append(tuple) 603 result.set_args(args) 604 return result 605 606 def visitDiscard(self, discard): 607 return self.dispatch(discard.expr) 608 609 def visitDiv(self, div): 610 return self._visitBinary(div, "__div__", "__rdiv__") 611 612 def visitFloorDiv(self, floordiv): 613 return self._visitBinary(floordiv, "__floordiv__", "__rfloordiv__") 614 615 def visitFor(self, for_): 616 617 """ 618 Make a subprogram for the 'for_' node and record its contents inside the 619 subprogram. Convert... 620 621 For (assign) 622 (body) 623 (else) 624 625 ...to: 626 627 Assign (assign #1) 628 Invoke -> Subprogram -> Try (body) -> (assign #2) 629 (body) 630 Invoke subprogram 631 (handler) -> ... 632 (else) -> ... 633 """ 634 635 subprogram = Subprogram(name=None, module=self.module, internal=1, returns_value=0, params=[], star=None, dstar=None) 636 self.current_subprograms.append(subprogram) 637 638 # Always return from conditional sections/subprograms. 639 640 if for_.else_ is not None: 641 else_stmt = self.dispatch(for_.else_) + [ReturnFromBlock()] 642 else: 643 else_stmt = [ReturnFromBlock()] 644 645 # Wrap the assignment in a try...except statement. 646 # Inside the body, add a recursive invocation to the subprogram. 647 648 subprogram.code = [ 649 Try( 650 body=[ 651 Assign( 652 code=[ 653 StoreTemp(expr=InvokeFunction(expr=LoadAttr(expr=LoadTemp(), name="next"))), 654 self.dispatch(for_.assign), 655 ReleaseTemp() 656 ]) 657 ] + self.dispatch(for_.body) + [ 658 InvokeBlock( 659 expr=LoadRef(ref=subprogram) 660 ) 661 ], 662 handler=[ 663 Conditional( 664 test=InvokeFunction( 665 expr=LoadName(name="isinstance"), 666 args=[LoadExc(), LoadName(name="StopIteration")], 667 star=None, 668 dstar=None), 669 body=else_stmt, 670 else_=[Raise(expr=LoadExc())] 671 ) 672 ], 673 else_=[], 674 finally_=[] 675 ), 676 ReturnFromBlock() 677 ] 678 679 # Finish the subprogram definition. 680 681 self.current_subprograms.pop() 682 self.subprograms.append(subprogram); self.subnames[subprogram.full_name()] = subprogram 683 684 # Obtain an iterator for the sequence involved. 685 # Then, make an invocation of the subprogram. 686 687 result = Assign(for_, 1, 688 code=[ 689 StoreTemp( 690 expr=InvokeFunction( 691 expr=LoadAttr( 692 name="__iter__", 693 expr=self.dispatch(for_.list) 694 ) 695 ) 696 ), 697 InvokeBlock(expr=LoadRef(ref=subprogram)), 698 ReleaseTemp() 699 ] 700 ) 701 702 # Make nice annotations for the viewer. 703 704 for_._iter_call = result.code[0].expr 705 for_._next_call = subprogram.code[0].body[0].code[0].expr 706 707 return result 708 709 def visitFrom(self, from_): 710 result = Assign(from_, 1) 711 code = [] 712 code.append(StoreTemp(expr=Import(name=from_.modname))) 713 for name, alias in from_.names: 714 code.append( 715 StoreName( 716 expr=LoadAttr( 717 expr=LoadTemp(), 718 name=name), 719 name=(alias or name) 720 ) 721 ) 722 code.append(ReleaseTemp()) 723 result.code = code 724 return result 725 726 def _visitFunction(self, function, subprogram): 727 728 """ 729 A common function generator which transforms the given 'function' node 730 and initialises the given 'subprogram' appropriately. 731 """ 732 733 # Discover star and dstar parameters. 734 735 if function.flags & 4 != 0: 736 has_star = 1 737 else: 738 has_star = 0 739 if function.flags & 8 != 0: 740 has_dstar = 1 741 else: 742 has_dstar = 0 743 744 # Discover the number of defaults and positional parameters. 745 746 ndefaults = len(function.defaults) 747 npositional = len(function.argnames) - has_star - has_dstar 748 749 # Produce star and dstar parameters with appropriate defaults. 750 751 if has_star: 752 star = ( 753 function.argnames[npositional], 754 InvokeFunction(expr=LoadName(name="list")) 755 ) 756 else: 757 star = None 758 if has_dstar: 759 dstar = ( 760 function.argnames[npositional + has_star], 761 InvokeFunction(expr=LoadName(name="dict")) 762 ) 763 else: 764 dstar = None 765 766 params = [] 767 for i in range(0, npositional - ndefaults): 768 params.append((function.argnames[i], None)) 769 770 # Process defaults. 771 772 for i in range(0, ndefaults): 773 default = function.defaults[i] 774 if default is not None: 775 params.append((function.argnames[npositional - ndefaults + i], self.dispatch(default))) 776 else: 777 params.append((function.argnames[npositional - ndefaults + i], None)) 778 779 subprogram.params = params 780 subprogram.star = star 781 subprogram.dstar = dstar 782 self.subprograms.append(subprogram); self.subnames[subprogram.full_name()] = subprogram 783 784 def visitFunction(self, function): 785 786 """ 787 Make a subprogram for the 'function' and record it outside the main 788 tree. Produce something like the following: 789 790 StoreName (name) 791 (expr) -> LoadRef (ref) -> Subprogram (params) 792 (star) 793 (dstar) 794 """ 795 796 subprogram = Subprogram(name=function.name, module=self.module, structures=self.current_structures[:], 797 internal=0, returns_value=1, star=None, dstar=None) 798 799 self.current_subprograms.append(subprogram) 800 subprogram.code = self.dispatch(function.code) + [ReturnFromFunction()] 801 self.current_subprograms.pop() 802 self._visitFunction(function, subprogram) 803 804 # Make a definition of the function associating it with a name. 805 806 result = StoreName(function, 1, name=function.name, expr=LoadRef(ref=subprogram)) 807 return result 808 809 def visitGetattr(self, getattr): 810 result = LoadAttr(getattr, 1, 811 name=getattr.attrname, 812 expr=self.dispatch(getattr.expr) 813 ) 814 return result 815 816 def visitGlobal(self, global_): 817 result = Global(global_, 1, 818 names=global_.names 819 ) 820 return result 821 822 def visitIf(self, if_): 823 824 """ 825 Make conditionals for each test from an 'if_' AST node, adding the body 826 and putting each subsequent test as part of the conditional's else 827 section. 828 829 Convert... 830 831 If (test/body) 832 (test/body) 833 ... 834 (else/body) 835 836 ...to: 837 838 Conditional (test) -> (body) 839 (else) -> Conditional (test) -> (body) 840 (else) -> ... 841 """ 842 843 844 results = nodes = [] 845 846 # Produce something like... 847 # expr.__bool__() ? body 848 849 first = 1 850 for compare, stmt in if_.tests: 851 852 # Set the first as the defining node. 853 854 test = Conditional(if_, first, 855 test=InvokeFunction( 856 expr=LoadAttr( 857 expr=self.dispatch(compare), 858 name="__bool__" 859 ), 860 ) 861 ) 862 test.body = self.dispatch(stmt) 863 nodes.append(test) 864 nodes = test.else_ = [] 865 first = 0 866 867 # Add the compound statement from any else clause to the end. 868 869 if if_.else_ is not None: 870 nodes += self.dispatch(if_.else_) 871 872 result = results[0] 873 return result 874 875 def visitImport(self, import_): 876 result = Assign(import_, 1) 877 code = [] 878 for path, alias in import_.names: 879 importer = Import(name=path) 880 top = alias or path.split(".")[0] 881 code.append(StoreName(expr=importer, name=top)) 882 result.code = code 883 return result 884 885 def visitInvert(self, invert): 886 return self._visitUnary(invert, "__invert__") 887 888 def visitKeyword(self, keyword): 889 result = Keyword(keyword, 1, 890 name=keyword.name, 891 expr=self.dispatch(keyword.expr) 892 ) 893 return result 894 895 def visitLambda(self, lambda_): 896 897 # Make a subprogram for the function and record it outside the main 898 # tree. 899 900 subprogram = Subprogram(name=None, module=self.module, internal=0, returns_value=1, star=None, dstar=None) 901 self.current_subprograms.append(subprogram) 902 subprogram.code = [ReturnFromFunction(expr=self.dispatch(lambda_.code))] 903 self.current_subprograms.pop() 904 self._visitFunction(lambda_, subprogram) 905 906 # Get the subprogram reference to the lambda. 907 908 return LoadRef(lambda_, 1, ref=subprogram) 909 910 def visitList(self, list): 911 return self._visitBuiltin(list, "list") 912 913 def visitMul(self, mul): 914 return self._visitBinary(mul, "__mul__", "__rmul__") 915 916 def visitName(self, name): 917 result = LoadName(name, 1, name=name.name) 918 return result 919 920 def _visitNot(self, expr, not_=None): 921 invocation = InvokeFunction( 922 expr=LoadAttr( 923 expr=expr, 924 name="__bool__" 925 ), 926 ) 927 if not_ is not None: 928 result = Not(not_, 1, expr=invocation) 929 else: 930 result = Not(expr=invocation) 931 return result 932 933 def visitNot(self, not_): 934 return self._visitNot(self.dispatch(not_.expr), not_) 935 936 def visitOr(self, or_): 937 938 """ 939 Make a subprogram for the 'or_' node and record its contents inside the 940 subprogram. Convert... 941 942 Or (test) 943 (test) 944 ... 945 946 ...to: 947 948 Subprogram -> Conditional (test) -> ReturnFromBlock ... 949 (else) -> Conditional (test) -> ReturnFromBlock ... 950 (else) -> ... 951 """ 952 953 subprogram = Subprogram(name=None, module=self.module, internal=1, returns_value=1, params=[], star=None, dstar=None) 954 self.current_subprograms.append(subprogram) 955 956 # In the subprogram, make instructions which store each operand, test 957 # for each operand's truth status, and if appropriate return from the 958 # subprogram with the value of the operand. 959 960 last = or_.nodes[-1] 961 results = nodes = [] 962 963 for node in or_.nodes: 964 expr = self.dispatch(node) 965 966 # Return from the subprogram where the test is satisfied. 967 968 if node is not last: 969 nodes.append(StoreTemp(expr=expr)) 970 invocation = InvokeFunction(expr=LoadAttr(expr=LoadTemp(), name="__bool__")) 971 test = Conditional(test=invocation, body=[ReturnFromBlock(expr=LoadTemp())]) 972 nodes.append(test) 973 974 # Put subsequent operations in the else section of this conditional. 975 976 nodes = test.else_ = [ReleaseTemp()] 977 978 # For the last operation, return the result. 979 980 else: 981 nodes.append( 982 ReturnFromBlock(expr=expr) 983 ) 984 985 # Finish the subprogram definition. 986 987 subprogram.code = results 988 989 self.current_subprograms.pop() 990 self.subprograms.append(subprogram); self.subnames[subprogram.full_name()] = subprogram 991 992 # Make an invocation of the subprogram. 993 994 result = InvokeBlock(or_, 1, produces_result=1) 995 result.expr = LoadRef(ref=subprogram) 996 return result 997 998 def visitPass(self, pass_): 999 return Pass(pass_, 1) 1000 1001 def visitPower(self, power): 1002 return self._visitBinary(power, "__pow__", "__rpow__") 1003 1004 def visitPrint(self, print_): 1005 1006 """ 1007 Convert... 1008 1009 Print (dest) -> 1010 (nodes) 1011 1012 ...to: 1013 1014 StoreTemp (index) -> "print" 1015 (expr) -> LoadAttr (expr) -> (dest) 1016 (name) -> "write" 1017 InvokeFunction (expr) -> LoadTemp (index) -> "print" 1018 (args) -> [(node)] 1019 ReleaseTemp (index) -> "print" 1020 """ 1021 1022 if print_.dest is not None: 1023 dest = self.dispatch(print_.dest) 1024 else: 1025 dest = self.dispatch(compiler.ast.Name("stdout")) 1026 1027 result = Assign(print_, 1, 1028 code=[ 1029 StoreTemp( 1030 index="print", 1031 expr=LoadAttr( 1032 expr=dest, 1033 name="write" 1034 ) 1035 ) 1036 ] 1037 ) 1038 1039 for node in print_.nodes: 1040 result.code.append( 1041 InvokeFunction( 1042 expr=LoadTemp(index="print"), 1043 args=[self.dispatch(node)], 1044 star=None, 1045 dstar=None 1046 ) 1047 ) 1048 1049 result.code.append( 1050 ReleaseTemp(index="print") 1051 ) 1052 1053 return result 1054 1055 def visitPrintnl(self, printnl): 1056 result = self.visitPrint(printnl) 1057 result.code.insert( 1058 len(result.code) - 1, 1059 InvokeFunction( 1060 expr=LoadTemp(index="print"), 1061 args=[self.dispatch(compiler.ast.Const("\n"))], 1062 star=None, 1063 dstar=None 1064 ) 1065 ) 1066 return result 1067 1068 def visitRaise(self, raise_): 1069 result = Raise(raise_, 1) 1070 if raise_.expr2 is None: 1071 result.expr = self.dispatch(raise_.expr1) 1072 else: 1073 result.expr = InvokeFunction( 1074 expr=self.dispatch(raise_.expr1), 1075 args=[self.dispatch(raise_.expr2)], 1076 star=None, 1077 dstar=None 1078 ) 1079 if raise_.expr3 is not None: 1080 result.traceback = self.dispatch(raise_.expr3) 1081 else: 1082 result.traceback = None 1083 return result 1084 1085 def visitReturn(self, return_): 1086 result = ReturnFromFunction(return_, 1, 1087 expr=self.dispatch(return_.value) 1088 ) 1089 return result 1090 1091 def _visitSlice(self, slice, expr, lower, upper, flags, value=None): 1092 if flags == "OP_ASSIGN": 1093 result = InvokeFunction(slice, 1, 1094 expr=LoadAttr( 1095 expr=expr, 1096 name="__setslice__" 1097 ), 1098 star=None, 1099 dstar=None, 1100 args=[lower, upper, value] 1101 ) 1102 elif flags == "OP_APPLY": 1103 args = [] 1104 result = InvokeFunction(slice, 1, 1105 expr=LoadAttr( 1106 expr=expr, 1107 name="__getslice__" 1108 ), 1109 star=None, 1110 dstar=None, 1111 args=[lower, upper] 1112 ) 1113 elif flags == "OP_DELETE": 1114 args = [] 1115 result = InvokeFunction(slice, 1, 1116 expr=LoadAttr( 1117 expr=expr, 1118 name="__delslice__" 1119 ), 1120 star=None, 1121 dstar=None, 1122 args=[lower, upper] 1123 ) 1124 else: 1125 raise NotImplementedError, flags 1126 1127 return result 1128 1129 def visitSlice(self, slice, in_sequence=0): 1130 return self._visitSlice(slice, self.dispatch(slice.expr), self.dispatch_or_none(slice.lower), 1131 self.dispatch_or_none(slice.upper), slice.flags, self._visitAssNameOrAttr(slice, in_sequence)) 1132 1133 def visitStmt(self, stmt): 1134 return self.dispatches(stmt.nodes) 1135 1136 def visitSub(self, sub): 1137 return self._visitBinary(sub, "__sub__", "__rsub__") 1138 1139 def _visitSubscript(self, subscript, expr, subs, flags, value=None): 1140 if flags == "OP_ASSIGN": 1141 result = InvokeFunction(subscript, 1, 1142 expr=LoadAttr( 1143 expr=expr, 1144 name="__setitem__" 1145 ), 1146 star=None, 1147 dstar=None, 1148 args=[subs, value] 1149 ) 1150 elif flags == "OP_APPLY": 1151 args = [] 1152 result = InvokeFunction(subscript, 1, 1153 expr=LoadAttr( 1154 expr=expr, 1155 name="__getitem__" 1156 ), 1157 star=None, 1158 dstar=None, 1159 args=[subs] 1160 ) 1161 elif flags == "OP_DELETE": 1162 args = [] 1163 result = InvokeFunction(subscript, 1, 1164 expr=LoadAttr( 1165 expr=expr, 1166 name="__delitem__" 1167 ), 1168 star=None, 1169 dstar=None, 1170 args=[subs] 1171 ) 1172 else: 1173 raise NotImplementedError, flags 1174 1175 return result 1176 1177 def _visitSubscriptSubs(self, node, subs): 1178 if len(subs) == 1: 1179 return self.dispatch(subs[0]) 1180 else: 1181 return InvokeFunction(node, 1, 1182 expr=LoadName(name="tuple"), 1183 args=self.dispatches(subs), 1184 star=None, 1185 dstar=None 1186 ) 1187 1188 def visitSubscript(self, subscript, in_sequence=0): 1189 return self._visitSubscript( 1190 subscript, self.dispatch(subscript.expr), self._visitSubscriptSubs(subscript, subscript.subs), subscript.flags, 1191 self._visitAssNameOrAttr(subscript, in_sequence) 1192 ) 1193 1194 def visitTryExcept(self, tryexcept): 1195 1196 """ 1197 Make conditionals for each handler associated with a 'tryexcept' node. 1198 1199 Convert... 1200 1201 TryExcept (body) 1202 (else) 1203 (spec/assign/stmt) 1204 ... 1205 1206 ...to: 1207 1208 Try (body) 1209 (else) 1210 (handler) -> Conditional (test) -> (stmt) 1211 (body) -> ... 1212 (else) -> Conditional (test) -> (stmt) 1213 (body) -> ... 1214 (else) -> ... 1215 """ 1216 1217 result = Try(tryexcept, 1, body=[], else_=[], finally_=[]) 1218 1219 if tryexcept.body is not None: 1220 result.body = self.dispatch(tryexcept.body) 1221 if tryexcept.else_ is not None: 1222 result.else_ = self.dispatch(tryexcept.else_) 1223 1224 results = nodes = [] 1225 catch_all = 0 1226 1227 for spec, assign, stmt in tryexcept.handlers: 1228 1229 # If no specification exists, produce an unconditional block. 1230 1231 if spec is None: 1232 nodes += self.dispatch(stmt) 1233 catch_all = 1 1234 1235 # Produce an exception value check. 1236 1237 else: 1238 test = Conditional( 1239 isolate_test=1, 1240 test=CheckExc(expr=LoadExc(), choices=self._visitTryExcept(spec)) 1241 ) 1242 test.body = [] 1243 1244 if assign is not None: 1245 test.body.append( 1246 Assign( 1247 code=[ 1248 StoreTemp(expr=LoadExc()), 1249 self.dispatch(assign), 1250 ReleaseTemp() 1251 ] 1252 ) 1253 ) 1254 1255 # Always return from conditional sections. 1256 1257 test.body += self.dispatch(stmt) + [ReturnFromBlock()] 1258 nodes.append(test) 1259 nodes = test.else_ = [] 1260 1261 # Add a raise operation to deal with unhandled exceptions. 1262 1263 if not catch_all: 1264 nodes.append( 1265 Raise( 1266 expr=LoadExc()) 1267 ) 1268 1269 result.handler = results 1270 return result 1271 1272 def _visitTryExcept(self, spec): 1273 1274 "Return a list of nodes for the given exception type 'spec'." 1275 1276 if isinstance(spec, compiler.ast.Tuple): 1277 nodes = [] 1278 for node in spec.nodes: 1279 nodes += self._visitTryExcept(node) 1280 else: 1281 nodes = [self.dispatch(spec)] 1282 return nodes 1283 1284 def visitTryFinally(self, tryfinally): 1285 result = Try(tryfinally, 1, body=[], else_=[], finally_=[]) 1286 if tryfinally.body is not None: 1287 result.body = self.dispatch(tryfinally.body) 1288 if tryfinally.final is not None: 1289 result.finally_ = self.dispatch(tryfinally.final) 1290 return result 1291 1292 def visitTuple(self, tuple): 1293 return self._visitBuiltin(tuple, "tuple") 1294 1295 def visitUnaryAdd(self, unaryadd): 1296 return self._visitUnary(unaryadd, "__pos__") 1297 1298 def visitUnarySub(self, unarysub): 1299 return self._visitUnary(unarysub, "__neg__") 1300 1301 def visitWhile(self, while_): 1302 1303 """ 1304 Make a subprogram for the 'while' node and record its contents inside the 1305 subprogram. Convert... 1306 1307 While (test) -> (body) 1308 (else) 1309 1310 ...to: 1311 1312 Subprogram -> Conditional (test) -> (body) -> Invoke subprogram 1313 (else) -> Conditional (test) -> ReturnFromBlock ... 1314 (else) -> ... 1315 """ 1316 1317 subprogram = Subprogram(name=None, module=self.module, internal=1, returns_value=0, params=[], star=None, dstar=None) 1318 self.current_subprograms.append(subprogram) 1319 1320 # Include a conditional statement in the subprogram. 1321 # Inside the conditional, add a recursive invocation to the subprogram 1322 # if the test condition was satisfied. 1323 # Return within the main section of the loop. 1324 1325 test = Conditional( 1326 test=InvokeFunction( 1327 expr=LoadAttr( 1328 expr=self.dispatch(while_.test), 1329 name="__bool__"), 1330 ), 1331 body=self.dispatch(while_.body) + [ 1332 InvokeBlock( 1333 expr=LoadRef(ref=subprogram) 1334 ), 1335 ReturnFromBlock() 1336 ], 1337 else_=[] 1338 ) 1339 1340 # Provide the else section, if present, along with an explicit return. 1341 1342 if while_.else_ is not None: 1343 test.else_ = self.dispatch(while_.else_) + [ReturnFromBlock()] 1344 1345 # Finish the subprogram definition. 1346 1347 subprogram.code = [test] 1348 1349 self.current_subprograms.pop() 1350 self.subprograms.append(subprogram); self.subnames[subprogram.full_name()] = subprogram 1351 1352 # Make an invocation of the subprogram. 1353 1354 result = InvokeBlock(while_, 1, 1355 expr=LoadRef(ref=subprogram) 1356 ) 1357 1358 # Make nice annotations for the viewer. 1359 1360 while_._test_call = subprogram.code[0].test 1361 1362 return result 1363 1364 # Convenience methods. 1365 1366 def _visitBinary(self, binary, left_name, right_name): 1367 1368 """ 1369 Emulate the current mechanisms by producing nodes as follows: 1370 1371 InvokeBlock -> Subprogram -> Try (body) -> ReturnFromBlock (expr) -> x.__add__(y) 1372 (else) 1373 (handler) -> Conditional (test) -> CheckExc (expr) -> LoadExc 1374 (choices) -> LoadName TypeError 1375 (body) -> ReturnFromBlock (expr) -> y.__radd__(x) 1376 (else) 1377 """ 1378 1379 subprogram = Subprogram(name=None, module=self.module, internal=1, returns_value=1, params=[], star=None, dstar=None) 1380 self.current_subprograms.append(subprogram) 1381 1382 subprogram.code = [ 1383 Try(binary, 1, 1384 body=[ 1385 ReturnFromBlock( 1386 expr=InvokeFunction( 1387 expr=LoadAttr(expr=self.dispatch(binary.left), name=left_name), 1388 args=[self.dispatch(binary.right)], 1389 star=None, 1390 dstar=None) 1391 ) 1392 ], 1393 else_=[], 1394 finally_=[], 1395 handler=[ 1396 Conditional( 1397 test=CheckExc(expr=LoadExc(), choices=[LoadName(name="TypeError")]), 1398 body=[ 1399 ReturnFromBlock( 1400 expr=InvokeFunction( 1401 expr=LoadAttr(expr=self.dispatch(binary.right), name=right_name), 1402 args=[self.dispatch(binary.left)], 1403 star=None, 1404 dstar=None) 1405 ) 1406 ], 1407 else_=[] 1408 ) 1409 ] 1410 ) 1411 ] 1412 1413 self.current_subprograms.pop() 1414 self.subprograms.append(subprogram); self.subnames[subprogram.full_name()] = subprogram 1415 1416 result = InvokeBlock( 1417 produces_result=1, 1418 expr=LoadRef(ref=subprogram) 1419 ) 1420 1421 # Make nice annotations for the viewer. 1422 1423 binary._left_call = subprogram.code[0].body[0].expr 1424 binary._right_call = subprogram.code[0].handler[0].body[0].expr 1425 1426 return result 1427 1428 def _visitBuiltin(self, builtin, name): 1429 result = InvokeFunction(builtin, 1, expr=LoadName(name=name), args=self.dispatches(builtin.nodes), star=None, dstar=None) 1430 return result 1431 1432 def _visitUnary(self, unary, name): 1433 result = InvokeFunction(unary, 1, 1434 expr=LoadAttr( 1435 expr=self.dispatch(unary.expr), 1436 name=name 1437 ) 1438 ) 1439 1440 # Make nice annotations for the viewer. 1441 1442 unary._unary_call = result 1443 1444 return result 1445 1446 # Convenience functions. 1447 1448 def simplify(filename, builtins=0): 1449 1450 """ 1451 Simplify the module stored in the file with the given 'filename'. 1452 1453 If the optional 'builtins' parameter is set to a true value (the default 1454 being a false value), then the module is considered as the builtins module. 1455 """ 1456 1457 simplifier = Simplifier(builtins) 1458 module = compiler.parseFile(filename) 1459 compiler.misc.set_filename(filename, module) 1460 if builtins: 1461 name = "__builtins__" 1462 else: 1463 path, ext = os.path.splitext(filename) 1464 path, name = os.path.split(path) 1465 simplified = simplifier.process(module, name) 1466 return simplified 1467 1468 # vim: tabstop=4 expandtab shiftwidth=4