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"), star=None, dstar=None, args=[]) 227 result = Assign(asslist, 1) 228 store = StoreTemp(expr=InvokeFunction(expr=LoadAttr(name="__iter__", expr=expr), star=None, dstar=None, args=[])) 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"), star=None, dstar=None, args=[]) 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"), args=[], star=None, dstar=None)), 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 result.code = [ 689 StoreTemp( 690 expr=InvokeFunction( 691 expr=LoadAttr( 692 name="__iter__", 693 expr=self.dispatch(for_.list) 694 ), 695 args=[], 696 star=None, 697 dstar=None 698 ) 699 ), 700 InvokeBlock(expr=LoadRef(ref=subprogram)), 701 ReleaseTemp() 702 ] 703 return result 704 705 def visitFrom(self, from_): 706 result = Assign(from_, 1) 707 code = [] 708 code.append(StoreTemp(expr=Import(name=from_.modname))) 709 for name, alias in from_.names: 710 code.append( 711 StoreName( 712 expr=LoadAttr( 713 expr=LoadTemp(), 714 name=name), 715 name=(alias or name) 716 ) 717 ) 718 code.append(ReleaseTemp()) 719 result.code = code 720 return result 721 722 def _visitFunction(self, function, subprogram): 723 724 """ 725 A common function generator which transforms the given 'function' node 726 and initialises the given 'subprogram' appropriately. 727 """ 728 729 # Discover star and dstar parameters. 730 731 if function.flags & 4 != 0: 732 has_star = 1 733 else: 734 has_star = 0 735 if function.flags & 8 != 0: 736 has_dstar = 1 737 else: 738 has_dstar = 0 739 740 # Discover the number of defaults and positional parameters. 741 742 ndefaults = len(function.defaults) 743 npositional = len(function.argnames) - has_star - has_dstar 744 745 # Produce star and dstar parameters with appropriate defaults. 746 747 if has_star: 748 star = ( 749 function.argnames[npositional], 750 InvokeFunction(expr=LoadName(name="list"), args=[], star=None, dstar=None) 751 ) 752 else: 753 star = None 754 if has_dstar: 755 dstar = ( 756 function.argnames[npositional + has_star], 757 InvokeFunction(expr=LoadName(name="dict"), args=[], star=None, dstar=None) 758 ) 759 else: 760 dstar = None 761 762 params = [] 763 for i in range(0, npositional - ndefaults): 764 params.append((function.argnames[i], None)) 765 766 # Process defaults. 767 768 for i in range(0, ndefaults): 769 default = function.defaults[i] 770 if default is not None: 771 params.append((function.argnames[npositional - ndefaults + i], self.dispatch(default))) 772 else: 773 params.append((function.argnames[npositional - ndefaults + i], None)) 774 775 subprogram.params = params 776 subprogram.star = star 777 subprogram.dstar = dstar 778 self.subprograms.append(subprogram); self.subnames[subprogram.full_name()] = subprogram 779 780 def visitFunction(self, function): 781 782 """ 783 Make a subprogram for the 'function' and record it outside the main 784 tree. Produce something like the following: 785 786 StoreName (name) 787 (expr) -> LoadRef (ref) -> Subprogram (params) 788 (star) 789 (dstar) 790 """ 791 792 subprogram = Subprogram(name=function.name, module=self.module, structures=self.current_structures[:], 793 internal=0, returns_value=1, star=None, dstar=None) 794 795 self.current_subprograms.append(subprogram) 796 subprogram.code = self.dispatch(function.code) + [ReturnFromFunction()] 797 self.current_subprograms.pop() 798 self._visitFunction(function, subprogram) 799 800 # Make a definition of the function associating it with a name. 801 802 result = StoreName(function, 1, name=function.name, expr=LoadRef(ref=subprogram)) 803 return result 804 805 def visitGetattr(self, getattr): 806 result = LoadAttr(getattr, 1, 807 name=getattr.attrname, 808 expr=self.dispatch(getattr.expr) 809 ) 810 return result 811 812 def visitGlobal(self, global_): 813 result = Global(global_, 1, 814 names=global_.names 815 ) 816 return result 817 818 def visitIf(self, if_): 819 820 """ 821 Make conditionals for each test from an 'if_' AST node, adding the body 822 and putting each subsequent test as part of the conditional's else 823 section. 824 825 Convert... 826 827 If (test/body) 828 (test/body) 829 ... 830 (else/body) 831 832 ...to: 833 834 Conditional (test) -> (body) 835 (else) -> Conditional (test) -> (body) 836 (else) -> ... 837 """ 838 839 840 results = nodes = [] 841 842 # Produce something like... 843 # expr.__bool__() ? body 844 845 first = 1 846 for compare, stmt in if_.tests: 847 848 # Set the first as the defining node. 849 850 test = Conditional(if_, first, 851 test=InvokeFunction( 852 expr=LoadAttr( 853 expr=self.dispatch(compare), 854 name="__bool__" 855 ), 856 args=[], 857 star=None, 858 dstar=None) 859 ) 860 test.body = self.dispatch(stmt) 861 nodes.append(test) 862 nodes = test.else_ = [] 863 first = 0 864 865 # Add the compound statement from any else clause to the end. 866 867 if if_.else_ is not None: 868 nodes += self.dispatch(if_.else_) 869 870 result = results[0] 871 return result 872 873 def visitImport(self, import_): 874 result = Assign(import_, 1) 875 code = [] 876 for path, alias in import_.names: 877 importer = Import(name=path) 878 top = alias or path.split(".")[0] 879 code.append(StoreName(expr=importer, name=top)) 880 result.code = code 881 return result 882 883 def visitInvert(self, invert): 884 return self._visitUnary(invert, "__invert__") 885 886 def visitKeyword(self, keyword): 887 result = Keyword(keyword, 1, 888 name=keyword.name, 889 expr=self.dispatch(keyword.expr) 890 ) 891 return result 892 893 def visitLambda(self, lambda_): 894 895 # Make a subprogram for the function and record it outside the main 896 # tree. 897 898 subprogram = Subprogram(name=None, module=self.module, internal=0, returns_value=1, star=None, dstar=None) 899 self.current_subprograms.append(subprogram) 900 subprogram.code = [ReturnFromFunction(expr=self.dispatch(lambda_.code))] 901 self.current_subprograms.pop() 902 self._visitFunction(lambda_, subprogram) 903 904 # Get the subprogram reference to the lambda. 905 906 return LoadRef(lambda_, 1, ref=subprogram) 907 908 def visitList(self, list): 909 return self._visitBuiltin(list, "list") 910 911 def visitMul(self, mul): 912 return self._visitBinary(mul, "__mul__", "__rmul__") 913 914 def visitName(self, name): 915 result = LoadName(name, 1, name=name.name) 916 return result 917 918 def _visitNot(self, expr, not_=None): 919 invocation = InvokeFunction( 920 expr=LoadAttr( 921 expr=expr, 922 name="__bool__" 923 ), 924 args=[], 925 star=None, 926 dstar=None 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__"), args=[], star=None, dstar=None) 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 args=[], 1332 star=None, 1333 dstar=None 1334 ), 1335 body=self.dispatch(while_.body) + [ 1336 InvokeBlock( 1337 expr=LoadRef(ref=subprogram) 1338 ), 1339 ReturnFromBlock() 1340 ], 1341 else_=[] 1342 ) 1343 1344 # Provide the else section, if present, along with an explicit return. 1345 1346 if while_.else_ is not None: 1347 test.else_ = self.dispatch(while_.else_) + [ReturnFromBlock()] 1348 1349 # Finish the subprogram definition. 1350 1351 subprogram.code = [test] 1352 1353 self.current_subprograms.pop() 1354 self.subprograms.append(subprogram); self.subnames[subprogram.full_name()] = subprogram 1355 1356 # Make an invocation of the subprogram. 1357 1358 result = InvokeBlock(while_, 1, 1359 expr=LoadRef(ref=subprogram) 1360 ) 1361 return result 1362 1363 # Convenience methods. 1364 1365 def _visitBinary(self, binary, left_name, right_name): 1366 1367 """ 1368 Emulate the current mechanisms by producing nodes as follows: 1369 1370 InvokeBlock -> Subprogram -> Try (body) -> ReturnFromBlock (expr) -> x.__add__(y) 1371 (else) 1372 (handler) -> Conditional (test) -> CheckExc (expr) -> LoadExc 1373 (choices) -> LoadName TypeError 1374 (body) -> ReturnFromBlock (expr) -> y.__radd__(x) 1375 (else) 1376 """ 1377 1378 subprogram = Subprogram(name=None, module=self.module, internal=1, returns_value=1, params=[], star=None, dstar=None) 1379 self.current_subprograms.append(subprogram) 1380 1381 subprogram.code = [ 1382 Try(binary, 1, 1383 body=[ 1384 ReturnFromBlock( 1385 expr=InvokeFunction( 1386 expr=LoadAttr(expr=self.dispatch(binary.left), name=left_name), 1387 args=[self.dispatch(binary.right)], 1388 star=None, 1389 dstar=None) 1390 ) 1391 ], 1392 else_=[], 1393 finally_=[], 1394 handler=[ 1395 Conditional( 1396 test=CheckExc(expr=LoadExc(), choices=[LoadName(name="TypeError")]), 1397 body=[ 1398 ReturnFromBlock( 1399 expr=InvokeFunction( 1400 expr=LoadAttr(expr=self.dispatch(binary.right), name=right_name), 1401 args=[self.dispatch(binary.left)], 1402 star=None, 1403 dstar=None) 1404 ) 1405 ], 1406 else_=[] 1407 ) 1408 ] 1409 ) 1410 ] 1411 1412 self.current_subprograms.pop() 1413 self.subprograms.append(subprogram); self.subnames[subprogram.full_name()] = subprogram 1414 1415 result = InvokeBlock(produces_result=1) 1416 result.expr = LoadRef(ref=subprogram) 1417 return result 1418 1419 def _visitBuiltin(self, builtin, name): 1420 result = InvokeFunction(builtin, 1, expr=LoadName(name=name), args=self.dispatches(builtin.nodes), star=None, dstar=None) 1421 return result 1422 1423 def _visitUnary(self, unary, name): 1424 return InvokeFunction(unary, 1, 1425 expr=LoadAttr( 1426 expr=self.dispatch(unary.expr), 1427 name=name 1428 ), 1429 args=[], 1430 star=None, 1431 dstar=None 1432 ) 1433 1434 # Convenience functions. 1435 1436 def simplify(filename, builtins=0): 1437 1438 """ 1439 Simplify the module stored in the file with the given 'filename'. 1440 1441 If the optional 'builtins' parameter is set to a true value (the default 1442 being a false value), then the module is considered as the builtins module. 1443 """ 1444 1445 simplifier = Simplifier(builtins) 1446 module = compiler.parseFile(filename) 1447 compiler.misc.set_filename(filename, module) 1448 if builtins: 1449 name = "__builtins__" 1450 else: 1451 path, ext = os.path.splitext(filename) 1452 path, name = os.path.split(path) 1453 simplified = simplifier.process(module, name) 1454 return simplified 1455 1456 # vim: tabstop=4 expandtab shiftwidth=4