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, Raise, Return, Slice, Stmt, Sub, Subscript, TryExcept, 55 TryFinally, Tuple, While, UnaryAdd, UnarySub. 56 57 Missing: Assert, Backquote, Bitand, Bitor, Bitxor, Decorators, Ellipsis, 58 Exec, LeftShift, ListComp, ListCompFor, ListCompIf, Print, Printnl, 59 RightShift, 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) -> 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 visitRaise(self, raise_): 1006 result = Raise(raise_, 1) 1007 if raise_.expr2 is None: 1008 result.expr = self.dispatch(raise_.expr1) 1009 else: 1010 result.expr = InvokeFunction( 1011 expr=self.dispatch(raise_.expr1), 1012 args=[self.dispatch(raise_.expr2)], 1013 star=None, 1014 dstar=None 1015 ) 1016 if raise_.expr3 is not None: 1017 result.traceback = self.dispatch(raise_.expr3) 1018 else: 1019 result.traceback = None 1020 return result 1021 1022 def visitReturn(self, return_): 1023 result = ReturnFromFunction(return_, 1, 1024 expr=self.dispatch(return_.value) 1025 ) 1026 return result 1027 1028 def _visitSlice(self, slice, expr, lower, upper, flags, value=None): 1029 if flags == "OP_ASSIGN": 1030 result = InvokeFunction(slice, 1, 1031 expr=LoadAttr( 1032 expr=expr, 1033 name="__setslice__" 1034 ), 1035 star=None, 1036 dstar=None, 1037 args=[lower, upper, value] 1038 ) 1039 elif flags == "OP_APPLY": 1040 args = [] 1041 result = InvokeFunction(slice, 1, 1042 expr=LoadAttr( 1043 expr=expr, 1044 name="__getslice__" 1045 ), 1046 star=None, 1047 dstar=None, 1048 args=[lower, upper] 1049 ) 1050 elif flags == "OP_DELETE": 1051 args = [] 1052 result = InvokeFunction(slice, 1, 1053 expr=LoadAttr( 1054 expr=expr, 1055 name="__delslice__" 1056 ), 1057 star=None, 1058 dstar=None, 1059 args=[lower, upper] 1060 ) 1061 else: 1062 raise NotImplementedError, flags 1063 1064 return result 1065 1066 def visitSlice(self, slice, in_sequence=0): 1067 return self._visitSlice(slice, self.dispatch(slice.expr), self.dispatch_or_none(slice.lower), 1068 self.dispatch_or_none(slice.upper), slice.flags, self._visitAssNameOrAttr(slice, in_sequence)) 1069 1070 def visitStmt(self, stmt): 1071 return self.dispatches(stmt.nodes) 1072 1073 def visitSub(self, sub): 1074 return self._visitBinary(sub, "__sub__", "__rsub__") 1075 1076 def _visitSubscript(self, subscript, expr, subs, flags, value=None): 1077 if flags == "OP_ASSIGN": 1078 result = InvokeFunction(subscript, 1, 1079 expr=LoadAttr( 1080 expr=expr, 1081 name="__setitem__" 1082 ), 1083 star=None, 1084 dstar=None, 1085 args=[subs, value] 1086 ) 1087 elif flags == "OP_APPLY": 1088 args = [] 1089 result = InvokeFunction(subscript, 1, 1090 expr=LoadAttr( 1091 expr=expr, 1092 name="__getitem__" 1093 ), 1094 star=None, 1095 dstar=None, 1096 args=[subs] 1097 ) 1098 elif flags == "OP_DELETE": 1099 args = [] 1100 result = InvokeFunction(subscript, 1, 1101 expr=LoadAttr( 1102 expr=expr, 1103 name="__delitem__" 1104 ), 1105 star=None, 1106 dstar=None, 1107 args=[subs] 1108 ) 1109 else: 1110 raise NotImplementedError, flags 1111 1112 return result 1113 1114 def _visitSubscriptSubs(self, node, subs): 1115 if len(subs) == 1: 1116 return self.dispatch(subs[0]) 1117 else: 1118 return InvokeFunction(node, 1, 1119 expr=LoadName(name="tuple"), 1120 args=self.dispatches(subs), 1121 star=None, 1122 dstar=None 1123 ) 1124 1125 def visitSubscript(self, subscript, in_sequence=0): 1126 return self._visitSubscript( 1127 subscript, self.dispatch(subscript.expr), self._visitSubscriptSubs(subscript, subscript.subs), subscript.flags, 1128 self._visitAssNameOrAttr(subscript, in_sequence) 1129 ) 1130 1131 def visitTryExcept(self, tryexcept): 1132 1133 """ 1134 Make conditionals for each handler associated with a 'tryexcept' node. 1135 1136 Convert... 1137 1138 TryExcept (body) 1139 (else) 1140 (spec/assign/stmt) 1141 ... 1142 1143 ...to: 1144 1145 Try (body) 1146 (else) 1147 (handler) -> Conditional (test) -> (stmt) 1148 (body) -> ... 1149 (else) -> Conditional (test) -> (stmt) 1150 (body) -> ... 1151 (else) -> ... 1152 """ 1153 1154 result = Try(tryexcept, 1, body=[], else_=[], finally_=[]) 1155 1156 if tryexcept.body is not None: 1157 result.body = self.dispatch(tryexcept.body) 1158 if tryexcept.else_ is not None: 1159 result.else_ = self.dispatch(tryexcept.else_) 1160 1161 results = nodes = [] 1162 catch_all = 0 1163 1164 for spec, assign, stmt in tryexcept.handlers: 1165 1166 # If no specification exists, produce an unconditional block. 1167 1168 if spec is None: 1169 nodes += self.dispatch(stmt) 1170 catch_all = 1 1171 1172 # Produce an exception value check. 1173 1174 else: 1175 test = Conditional( 1176 isolate_test=1, 1177 test=CheckExc(expr=LoadExc(), choices=self._visitTryExcept(spec)) 1178 ) 1179 test.body = [] 1180 1181 if assign is not None: 1182 test.body.append( 1183 Assign( 1184 code=[ 1185 StoreTemp(expr=LoadExc()), 1186 self.dispatch(assign), 1187 ReleaseTemp() 1188 ] 1189 ) 1190 ) 1191 1192 # Always return from conditional sections. 1193 1194 test.body += self.dispatch(stmt) + [ReturnFromBlock()] 1195 nodes.append(test) 1196 nodes = test.else_ = [] 1197 1198 # Add a raise operation to deal with unhandled exceptions. 1199 1200 if not catch_all: 1201 nodes.append( 1202 Raise( 1203 expr=LoadExc()) 1204 ) 1205 1206 result.handler = results 1207 return result 1208 1209 def _visitTryExcept(self, spec): 1210 1211 "Return a list of nodes for the given exception type 'spec'." 1212 1213 if isinstance(spec, compiler.ast.Tuple): 1214 nodes = [] 1215 for node in spec.nodes: 1216 nodes += self._visitTryExcept(node) 1217 else: 1218 nodes = [self.dispatch(spec)] 1219 return nodes 1220 1221 def visitTryFinally(self, tryfinally): 1222 result = Try(tryfinally, 1, body=[], else_=[], finally_=[]) 1223 if tryfinally.body is not None: 1224 result.body = self.dispatch(tryfinally.body) 1225 if tryfinally.final is not None: 1226 result.finally_ = self.dispatch(tryfinally.final) 1227 return result 1228 1229 def visitTuple(self, tuple): 1230 return self._visitBuiltin(tuple, "tuple") 1231 1232 def visitUnaryAdd(self, unaryadd): 1233 return self._visitUnary(unaryadd, "__pos__") 1234 1235 def visitUnarySub(self, unarysub): 1236 return self._visitUnary(unarysub, "__neg__") 1237 1238 def visitWhile(self, while_): 1239 1240 """ 1241 Make a subprogram for the 'while' node and record its contents inside the 1242 subprogram. Convert... 1243 1244 While (test) -> (body) 1245 (else) 1246 1247 ...to: 1248 1249 Subprogram -> Conditional (test) -> (body) -> Invoke subprogram 1250 (else) -> Conditional (test) -> ReturnFromBlock ... 1251 (else) -> ... 1252 """ 1253 1254 subprogram = Subprogram(name=None, module=self.module, internal=1, returns_value=0, params=[], star=None, dstar=None) 1255 self.current_subprograms.append(subprogram) 1256 1257 # Include a conditional statement in the subprogram. 1258 1259 test = Conditional(else_=[]) 1260 test.test = InvokeFunction(expr=LoadAttr(expr=self.dispatch(while_.test), name="__bool__"), args=[], star=None, dstar=None) 1261 1262 # Inside the conditional, add a recursive invocation to the subprogram 1263 # if the test condition was satisfied. 1264 1265 continuation = InvokeBlock() 1266 continuation.expr = LoadRef(ref=subprogram) 1267 1268 # Return within the main section of the loop. 1269 1270 test.body = self.dispatch(while_.body) + [continuation, ReturnFromBlock()] 1271 1272 # Provide the else section, if present, along with an explicit return. 1273 1274 if while_.else_ is not None: 1275 test.else_ = self.dispatch(while_.else_) + [ReturnFromBlock()] 1276 1277 # Finish the subprogram definition. 1278 1279 subprogram.code = [test] 1280 1281 self.current_subprograms.pop() 1282 self.subprograms.append(subprogram); self.subnames[subprogram.full_name()] = subprogram 1283 1284 # Make an invocation of the subprogram. 1285 1286 result = InvokeBlock(while_, 1) 1287 result.expr = LoadRef(ref=subprogram) 1288 return result 1289 1290 # Convenience methods. 1291 1292 def _visitBinary(self, binary, left_name, right_name): 1293 1294 """ 1295 Emulate the current mechanisms by producing nodes as follows: 1296 1297 InvokeBlock -> Subprogram -> Try (body) -> ReturnFromBlock (expr) -> x.__add__(y) 1298 (else) 1299 (handler) -> Conditional (test) -> CheckExc (expr) -> LoadExc 1300 (choices) -> LoadName TypeError 1301 (body) -> ReturnFromBlock (expr) -> y.__radd__(x) 1302 (else) 1303 """ 1304 1305 subprogram = Subprogram(name=None, module=self.module, internal=1, returns_value=1, params=[], star=None, dstar=None) 1306 self.current_subprograms.append(subprogram) 1307 1308 subprogram.code = [ 1309 Try(binary, 1, 1310 body=[ 1311 ReturnFromBlock( 1312 expr=InvokeFunction( 1313 expr=LoadAttr(expr=self.dispatch(binary.left), name=left_name), 1314 args=[self.dispatch(binary.right)], 1315 star=None, 1316 dstar=None) 1317 ) 1318 ], 1319 else_=[], 1320 finally_=[], 1321 handler=[ 1322 Conditional( 1323 test=CheckExc(expr=LoadExc(), choices=[LoadName(name="TypeError")]), 1324 body=[ 1325 ReturnFromBlock( 1326 expr=InvokeFunction( 1327 expr=LoadAttr(expr=self.dispatch(binary.right), name=right_name), 1328 args=[self.dispatch(binary.left)], 1329 star=None, 1330 dstar=None) 1331 ) 1332 ], 1333 else_=[] 1334 ) 1335 ] 1336 ) 1337 ] 1338 1339 self.current_subprograms.pop() 1340 self.subprograms.append(subprogram); self.subnames[subprogram.full_name()] = subprogram 1341 1342 result = InvokeBlock(produces_result=1) 1343 result.expr = LoadRef(ref=subprogram) 1344 return result 1345 1346 def _visitBuiltin(self, builtin, name): 1347 result = InvokeFunction(builtin, 1, expr=LoadName(name=name), args=self.dispatches(builtin.nodes), star=None, dstar=None) 1348 return result 1349 1350 def _visitUnary(self, unary, name): 1351 return InvokeFunction(unary, 1, 1352 expr=LoadAttr( 1353 expr=self.dispatch(unary.expr), 1354 name=name 1355 ), 1356 args=[], 1357 star=None, 1358 dstar=None 1359 ) 1360 1361 # Convenience functions. 1362 1363 def simplify(filename, builtins=0): 1364 1365 """ 1366 Simplify the module stored in the file with the given 'filename'. 1367 1368 If the optional 'builtins' parameter is set to a true value (the default 1369 being a false value), then the module is considered as the builtins module. 1370 """ 1371 1372 simplifier = Simplifier(builtins) 1373 module = compiler.parseFile(filename) 1374 compiler.misc.set_filename(filename, module) 1375 if builtins: 1376 name = "__builtins__" 1377 else: 1378 path, ext = os.path.splitext(filename) 1379 path, name = os.path.split(path) 1380 simplified = simplifier.process(module, name) 1381 return simplified 1382 1383 # vim: tabstop=4 expandtab shiftwidth=4