1 """Parse tree transformation module. 2 3 Transforms Python source code into an abstract syntax tree (AST) 4 defined in the ast module. 5 6 The simplest ways to invoke this module are via parse and parseFile. 7 parse(buf) -> AST 8 parseFile(path) -> AST 9 """ 10 11 # Original version written by Greg Stein (gstein@lyra.org) 12 # and Bill Tutt (rassilon@lima.mudlib.org) 13 # February 1997. 14 # 15 # Modifications and improvements for Python 2.0 by Jeremy Hylton and 16 # Mark Hammond 17 # 18 # Some fixes to try to have correct line number on almost all nodes 19 # (except Module, Discard and Stmt) added by Sylvain Thenault 20 # 21 # Portions of this file are: 22 # Copyright (C) 1997-1998 Greg Stein. All Rights Reserved. 23 # 24 # This module is provided under a BSD-ish license. See 25 # http://www.opensource.org/licenses/bsd-license.html 26 # and replace OWNER, ORGANIZATION, and YEAR as appropriate. 27 28 from compiler.ast import * 29 from pyparser.pygram import syms as symbol, sym_name, tokens as token, tok_name 30 import pyparser.pyparse as parser 31 32 class WalkerError(StandardError): 33 pass 34 35 from compiler.consts import CO_VARARGS, CO_VARKEYWORDS 36 from compiler.consts import OP_ASSIGN, OP_DELETE, OP_APPLY 37 38 def parseFile(path): 39 f = open(path, "U") 40 # XXX The parser API tolerates files without a trailing newline, 41 # but not strings without a trailing newline. Always add an extra 42 # newline to the file contents, since we're going through the string 43 # version of the API. 44 src = f.read() + "\n" 45 f.close() 46 return parse(src) 47 48 def parse(buf, mode="exec"): 49 if mode == "exec" or mode == "single": 50 return Transformer().parsesuite(buf) 51 elif mode == "eval": 52 return Transformer().parseexpr(buf) 53 else: 54 raise ValueError("compile() arg 3 must be" 55 " 'exec' or 'eval' or 'single'") 56 57 def extractLineNo(ast): 58 if not isinstance(ast[1], tuple): 59 # get a terminal node 60 return ast[2] 61 for child in ast[1:]: 62 if isinstance(child, tuple): 63 lineno = extractLineNo(child) 64 if lineno is not None: 65 return lineno 66 67 def Node(*args): 68 kind = args[0] 69 if kind in nodes: 70 try: 71 return nodes[kind](*args[1:]) 72 except TypeError: 73 print nodes[kind], len(args), args 74 raise 75 else: 76 raise WalkerError, "Can't find appropriate Node type: %s" % str(args) 77 #return apply(ast.Node, args) 78 79 class Transformer: 80 """Utility object for transforming Python parse trees. 81 82 Exposes the following methods: 83 tree = transform(ast_tree) 84 tree = parsesuite(text) 85 tree = parseexpr(text) 86 tree = parsefile(fileob | filename) 87 """ 88 89 def __init__(self): 90 self._dispatch = {} 91 for value, name in sym_name.items(): 92 if hasattr(self, name): 93 self._dispatch[value] = getattr(self, name) 94 self._dispatch[token["NEWLINE"]] = self.com_NEWLINE 95 self._atom_dispatch = {token["LPAR"]: self.atom_lpar, 96 token["LSQB"]: self.atom_lsqb, 97 token["LBRACE"]: self.atom_lbrace, 98 token["BACKQUOTE"]: self.atom_backquote, 99 token["NUMBER"]: self.atom_number, 100 token["STRING"]: self.atom_string, 101 token["NAME"]: self.atom_name, 102 } 103 self.encoding = None 104 105 def transform(self, tree): 106 """Transform an AST into a modified parse tree.""" 107 if not (isinstance(tree, tuple) or isinstance(tree, list)): 108 tree = parser.st2tuple(tree, line_info=1) 109 return self.compile_node(tree) 110 111 def parsesuite(self, text): 112 """Return a modified parse tree for the given suite text.""" 113 return self.transform(parser.suite(text)) 114 115 def parseexpr(self, text): 116 """Return a modified parse tree for the given expression text.""" 117 return self.transform(parser.expr(text)) 118 119 def parsefile(self, file): 120 """Return a modified parse tree for the contents of the given file.""" 121 if type(file) == type(''): 122 file = open(file) 123 return self.parsesuite(file.read()) 124 125 # -------------------------------------------------------------- 126 # 127 # PRIVATE METHODS 128 # 129 130 def compile_node(self, node): 131 ### emit a line-number node? 132 n = node[0] 133 134 if n == symbol["encoding_decl"]: 135 self.encoding = node[2] 136 node = node[1] 137 n = node[0] 138 139 if n == symbol["single_input"]: 140 return self.single_input(node[1:]) 141 if n == symbol["file_input"]: 142 return self.file_input(node[1:]) 143 if n == symbol["eval_input"]: 144 return self.eval_input(node[1:]) 145 if n == symbol["lambdef"]: 146 return self.lambdef(node[1:]) 147 if n == symbol["funcdef"]: 148 return self.funcdef(node[1:]) 149 if n == symbol["classdef"]: 150 return self.classdef(node[1:]) 151 152 raise WalkerError, ('unexpected node type', n) 153 154 def single_input(self, node): 155 ### do we want to do anything about being "interactive" ? 156 157 # NEWLINE | simple_stmt | compound_stmt NEWLINE 158 n = node[0][0] 159 if n != token["NEWLINE"]: 160 return self.com_stmt(node[0]) 161 162 return Pass() 163 164 def file_input(self, nodelist): 165 doc = self.get_docstring(nodelist, symbol["file_input"]) 166 if doc is not None: 167 i = 1 168 else: 169 i = 0 170 stmts = [] 171 for node in nodelist[i:]: 172 if node[0] != token["ENDMARKER"] and node[0] != token["NEWLINE"]: 173 self.com_append_stmt(stmts, node) 174 return Module(doc, Stmt(stmts)) 175 176 def eval_input(self, nodelist): 177 # from the built-in function input() 178 ### is this sufficient? 179 return Expression(self.com_node(nodelist[0])) 180 181 def funcdef(self, nodelist): 182 # -5 -4 -3 -2 -1 183 # funcdef: 'def' NAME parameters ':' suite 184 # parameters: '(' [varargslist] ')' 185 186 assert len(nodelist) == 5 187 decorators = None 188 189 lineno = nodelist[-4][2] 190 name = nodelist[-4][1] 191 args = nodelist[-3][2] 192 193 if args[0] == symbol["varargslist"]: 194 names, defaults, flags = self.com_arglist(args[1:]) 195 else: 196 names = defaults = () 197 flags = 0 198 doc = self.get_docstring(nodelist[-1]) 199 200 # code for function 201 code = self.com_node(nodelist[-1]) 202 203 if doc is not None: 204 assert isinstance(code, Stmt) 205 assert isinstance(code.nodes[0], Discard) 206 del code.nodes[0] 207 return Function(decorators, name, names, defaults, flags, doc, code, 208 lineno=lineno) 209 210 def lambdef(self, nodelist): 211 # lambdef: 'lambda' [varargslist] ':' test 212 if nodelist[2][0] == symbol["varargslist"]: 213 names, defaults, flags = self.com_arglist(nodelist[2][1:]) 214 else: 215 names = defaults = () 216 flags = 0 217 218 # code for lambda 219 code = self.com_node(nodelist[-1]) 220 221 return Lambda(names, defaults, flags, code, lineno=nodelist[1][2]) 222 old_lambdef = lambdef 223 224 def classdef(self, nodelist): 225 # classdef: 'class' NAME ['(' [testlist] ')'] ':' suite 226 227 name = nodelist[1][1] 228 doc = self.get_docstring(nodelist[-1]) 229 if nodelist[2][0] == token["COLON"]: 230 bases = [] 231 elif nodelist[3][0] == token["RPAR"]: 232 bases = [] 233 else: 234 bases = self.com_bases(nodelist[3]) 235 236 # code for class 237 code = self.com_node(nodelist[-1]) 238 239 if doc is not None: 240 assert isinstance(code, Stmt) 241 assert isinstance(code.nodes[0], Discard) 242 del code.nodes[0] 243 244 return Class(name, bases, doc, code, lineno=nodelist[1][2]) 245 246 def stmt(self, nodelist): 247 return self.com_stmt(nodelist[0]) 248 249 small_stmt = stmt 250 flow_stmt = stmt 251 compound_stmt = stmt 252 253 def simple_stmt(self, nodelist): 254 # small_stmt (';' small_stmt)* [';'] NEWLINE 255 stmts = [] 256 for i in range(0, len(nodelist), 2): 257 self.com_append_stmt(stmts, nodelist[i]) 258 return Stmt(stmts) 259 260 def parameters(self, nodelist): 261 raise WalkerError 262 263 def varargslist(self, nodelist): 264 raise WalkerError 265 266 def fpdef(self, nodelist): 267 raise WalkerError 268 269 def fplist(self, nodelist): 270 raise WalkerError 271 272 def dotted_name(self, nodelist): 273 raise WalkerError 274 275 def comp_op(self, nodelist): 276 raise WalkerError 277 278 def trailer(self, nodelist): 279 raise WalkerError 280 281 def sliceop(self, nodelist): 282 raise WalkerError 283 284 def argument(self, nodelist): 285 raise WalkerError 286 287 # -------------------------------------------------------------- 288 # 289 # STATEMENT NODES (invoked by com_node()) 290 # 291 292 def expr_stmt(self, nodelist): 293 # augassign testlist | testlist ('=' testlist)* 294 en = nodelist[-1] 295 exprNode = self.lookup_node(en)(en[1:]) 296 if len(nodelist) == 1: 297 return Discard(exprNode, lineno=exprNode.lineno) 298 if nodelist[1][0] == token["EQUAL"]: 299 nodesl = [] 300 for i in range(0, len(nodelist) - 2, 2): 301 nodesl.append(self.com_assign(nodelist[i], OP_ASSIGN)) 302 return Assign(nodesl, exprNode, lineno=nodelist[1][2]) 303 else: 304 lval = self.com_augassign(nodelist[0]) 305 op = self.com_augassign_op(nodelist[1]) 306 return AugAssign(lval, op[1], exprNode, lineno=op[2]) 307 raise WalkerError, "can't get here" 308 309 def print_stmt(self, nodelist): 310 # print ([ test (',' test)* [','] ] | '>>' test [ (',' test)+ [','] ]) 311 items = [] 312 if len(nodelist) == 1: 313 start = 1 314 dest = None 315 elif nodelist[1][0] == token["RIGHTSHIFT"]: 316 assert len(nodelist) == 3 \ 317 or nodelist[3][0] == token["COMMA"] 318 dest = self.com_node(nodelist[2]) 319 start = 4 320 else: 321 dest = None 322 start = 1 323 for i in range(start, len(nodelist), 2): 324 items.append(self.com_node(nodelist[i])) 325 if nodelist[-1][0] == token["COMMA"]: 326 return Print(items, dest, lineno=nodelist[0][2]) 327 return Printnl(items, dest, lineno=nodelist[0][2]) 328 329 def del_stmt(self, nodelist): 330 return self.com_assign(nodelist[1], OP_DELETE) 331 332 def pass_stmt(self, nodelist): 333 return Pass(lineno=nodelist[0][2]) 334 335 def break_stmt(self, nodelist): 336 return Break(lineno=nodelist[0][2]) 337 338 def continue_stmt(self, nodelist): 339 return Continue(lineno=nodelist[0][2]) 340 341 def return_stmt(self, nodelist): 342 # return: [testlist] 343 if len(nodelist) < 2: 344 return Return(Const(None), lineno=nodelist[0][2]) 345 return Return(self.com_node(nodelist[1]), lineno=nodelist[0][2]) 346 347 def raise_stmt(self, nodelist): 348 # raise: [test [',' test [',' test]]] 349 if len(nodelist) > 5: 350 expr3 = self.com_node(nodelist[5]) 351 else: 352 expr3 = None 353 if len(nodelist) > 3: 354 expr2 = self.com_node(nodelist[3]) 355 else: 356 expr2 = None 357 if len(nodelist) > 1: 358 expr1 = self.com_node(nodelist[1]) 359 else: 360 expr1 = None 361 return Raise(expr1, expr2, expr3, lineno=nodelist[0][2]) 362 363 def import_stmt(self, nodelist): 364 # import_stmt: import_name | import_from 365 assert len(nodelist) == 1 366 return self.com_node(nodelist[0]) 367 368 def import_name(self, nodelist): 369 # import_name: 'import' dotted_as_names 370 return Import(self.com_dotted_as_names(nodelist[1]), 371 lineno=nodelist[0][2]) 372 373 def import_from(self, nodelist): 374 # import_from: 'from' ('.'* dotted_name | '.') 'import' ('*' | 375 # '(' import_as_names ')' | import_as_names) 376 assert nodelist[0][1] == 'from' 377 idx = 1 378 while nodelist[idx][1] == '.': 379 idx += 1 380 level = idx - 1 381 if nodelist[idx][0] == symbol["dotted_name"]: 382 fromname = self.com_dotted_name(nodelist[idx]) 383 idx += 1 384 else: 385 fromname = "" 386 assert nodelist[idx][1] == 'import' 387 if nodelist[idx + 1][0] == token["STAR"]: 388 return From(fromname, [('*', None)], level, 389 lineno=nodelist[0][2]) 390 else: 391 node = nodelist[idx + 1 + (nodelist[idx + 1][0] == token["LPAR"])] 392 return From(fromname, self.com_import_as_names(node), level, 393 lineno=nodelist[0][2]) 394 395 def global_stmt(self, nodelist): 396 # global: NAME (',' NAME)* 397 names = [] 398 for i in range(1, len(nodelist), 2): 399 names.append(nodelist[i][1]) 400 return Global(names, lineno=nodelist[0][2]) 401 402 def exec_stmt(self, nodelist): 403 # exec_stmt: 'exec' expr ['in' expr [',' expr]] 404 expr1 = self.com_node(nodelist[1]) 405 if len(nodelist) >= 4: 406 expr2 = self.com_node(nodelist[3]) 407 if len(nodelist) >= 6: 408 expr3 = self.com_node(nodelist[5]) 409 else: 410 expr3 = None 411 else: 412 expr2 = expr3 = None 413 414 return Exec(expr1, expr2, expr3, lineno=nodelist[0][2]) 415 416 def assert_stmt(self, nodelist): 417 # 'assert': test, [',' test] 418 expr1 = self.com_node(nodelist[1]) 419 if (len(nodelist) == 4): 420 expr2 = self.com_node(nodelist[3]) 421 else: 422 expr2 = None 423 return Assert(expr1, expr2, lineno=nodelist[0][2]) 424 425 def if_stmt(self, nodelist): 426 # if: test ':' suite ('elif' test ':' suite)* ['else' ':' suite] 427 tests = [] 428 for i in range(0, len(nodelist) - 3, 4): 429 testNode = self.com_node(nodelist[i + 1]) 430 suiteNode = self.com_node(nodelist[i + 3]) 431 tests.append((testNode, suiteNode)) 432 433 if len(nodelist) % 4 == 3: 434 elseNode = self.com_node(nodelist[-1]) 435 ## elseNode.lineno = nodelist[-1][1][2] 436 else: 437 elseNode = None 438 return If(tests, elseNode, lineno=nodelist[0][2]) 439 440 def while_stmt(self, nodelist): 441 # 'while' test ':' suite ['else' ':' suite] 442 443 testNode = self.com_node(nodelist[1]) 444 bodyNode = self.com_node(nodelist[3]) 445 446 if len(nodelist) > 4: 447 elseNode = self.com_node(nodelist[6]) 448 else: 449 elseNode = None 450 451 return While(testNode, bodyNode, elseNode, lineno=nodelist[0][2]) 452 453 def for_stmt(self, nodelist): 454 # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] 455 456 assignNode = self.com_assign(nodelist[1], OP_ASSIGN) 457 listNode = self.com_node(nodelist[3]) 458 bodyNode = self.com_node(nodelist[5]) 459 460 if len(nodelist) > 8: 461 elseNode = self.com_node(nodelist[8]) 462 else: 463 elseNode = None 464 465 return For(assignNode, listNode, bodyNode, elseNode, 466 lineno=nodelist[0][2]) 467 468 def try_stmt(self, nodelist): 469 return self.com_try_except_finally(nodelist) 470 471 def with_stmt(self, nodelist): 472 return self.com_with(nodelist) 473 474 def suite(self, nodelist): 475 # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT 476 if len(nodelist) == 1: 477 return self.com_stmt(nodelist[0]) 478 479 stmts = [] 480 for node in nodelist: 481 if node[0] == symbol["stmt"]: 482 self.com_append_stmt(stmts, node) 483 return Stmt(stmts) 484 485 # -------------------------------------------------------------- 486 # 487 # EXPRESSION NODES (invoked by com_node()) 488 # 489 490 def testlist(self, nodelist): 491 # testlist: expr (',' expr)* [','] 492 # testlist_safe: test [(',' test)+ [',']] 493 # exprlist: expr (',' expr)* [','] 494 return self.com_binary(Tuple, nodelist) 495 496 testlist_safe = testlist # XXX 497 testlist1 = testlist 498 exprlist = testlist 499 500 def testlist_comp(self, nodelist): 501 # test ( (',' test)* [','] ) 502 assert nodelist[0][0] == symbol["test"] 503 return self.testlist(nodelist) 504 505 def test(self, nodelist): 506 # or_test | lambdef 507 if len(nodelist) == 1 and nodelist[0][0] == symbol["lambdef"]: 508 return self.lambdef(nodelist[0]) 509 then = self.com_node(nodelist[0]) 510 return then 511 512 def or_test(self, nodelist): 513 # and_test ('or' and_test)* | lambdef 514 if len(nodelist) == 1 and nodelist[0][0] == symbol["lambdef"]: 515 return self.lambdef(nodelist[0]) 516 return self.com_binary(Or, nodelist) 517 old_test = or_test 518 519 def and_test(self, nodelist): 520 # not_test ('and' not_test)* 521 return self.com_binary(And, nodelist) 522 523 def not_test(self, nodelist): 524 # 'not' not_test | comparison 525 result = self.com_node(nodelist[-1]) 526 if len(nodelist) == 2: 527 return Not(result, lineno=nodelist[0][2]) 528 return result 529 530 def comparison(self, nodelist): 531 # comparison: expr (comp_op expr)* 532 node = self.com_node(nodelist[0]) 533 if len(nodelist) == 1: 534 return node 535 536 results = [] 537 for i in range(2, len(nodelist), 2): 538 nl = nodelist[i-1] 539 540 # comp_op: '<' | '>' | '=' | '>=' | '<=' | '<>' | '!=' | '==' 541 # | 'in' | 'not' 'in' | 'is' | 'is' 'not' 542 n = nl[1] 543 if n[0] == token["NAME"]: 544 type = n[1] 545 if len(nl) == 3: 546 if type == 'not': 547 type = 'not in' 548 else: 549 type = 'is not' 550 else: 551 type = _cmp_types[n[0]] 552 553 lineno = nl[1][2] 554 results.append((type, self.com_node(nodelist[i]))) 555 556 # we need a special "compare" node so that we can distinguish 557 # 3 < x < 5 from (3 < x) < 5 558 # the two have very different semantics and results (note that the 559 # latter form is always true) 560 561 return Compare(node, results, lineno=lineno) 562 563 def expr(self, nodelist): 564 # xor_expr ('|' xor_expr)* 565 return self.com_binary(Bitor, nodelist) 566 567 def xor_expr(self, nodelist): 568 # xor_expr ('^' xor_expr)* 569 return self.com_binary(Bitxor, nodelist) 570 571 def and_expr(self, nodelist): 572 # xor_expr ('&' xor_expr)* 573 return self.com_binary(Bitand, nodelist) 574 575 def shift_expr(self, nodelist): 576 # shift_expr ('<<'|'>>' shift_expr)* 577 node = self.com_node(nodelist[0]) 578 for i in range(2, len(nodelist), 2): 579 right = self.com_node(nodelist[i]) 580 if nodelist[i-1][0] == token["LEFTSHIFT"]: 581 node = LeftShift([node, right], lineno=nodelist[1][2]) 582 elif nodelist[i-1][0] == token["RIGHTSHIFT"]: 583 node = RightShift([node, right], lineno=nodelist[1][2]) 584 else: 585 raise ValueError, "unexpected token: %s" % nodelist[i-1][0] 586 return node 587 588 def arith_expr(self, nodelist): 589 node = self.com_node(nodelist[0]) 590 for i in range(2, len(nodelist), 2): 591 right = self.com_node(nodelist[i]) 592 if nodelist[i-1][0] == token["PLUS"]: 593 node = Add([node, right], lineno=nodelist[1][2]) 594 elif nodelist[i-1][0] == token["MINUS"]: 595 node = Sub([node, right], lineno=nodelist[1][2]) 596 else: 597 raise ValueError, "unexpected token: %s" % nodelist[i-1][0] 598 return node 599 600 def term(self, nodelist): 601 node = self.com_node(nodelist[0]) 602 for i in range(2, len(nodelist), 2): 603 right = self.com_node(nodelist[i]) 604 t = nodelist[i-1][0] 605 if t == token["STAR"]: 606 node = Mul([node, right]) 607 elif t == token["SLASH"]: 608 node = Div([node, right]) 609 elif t == token["PERCENT"]: 610 node = Mod([node, right]) 611 elif t == token["DOUBLESLASH"]: 612 node = FloorDiv([node, right]) 613 else: 614 raise ValueError, "unexpected token: %s" % t 615 node.lineno = nodelist[1][2] 616 return node 617 618 def factor(self, nodelist): 619 elt = nodelist[0] 620 t = elt[0] 621 node = self.lookup_node(nodelist[-1])(nodelist[-1][1:]) 622 # need to handle (unary op)constant here... 623 if t == token["PLUS"]: 624 return UnaryAdd(node, lineno=elt[2]) 625 elif t == token["MINUS"]: 626 return UnarySub(node, lineno=elt[2]) 627 elif t == token["TILDE"]: 628 node = Invert(node, lineno=elt[2]) 629 return node 630 631 def power(self, nodelist): 632 # power: atom trailer* ('**' factor)* 633 node = self.com_node(nodelist[0]) 634 for i in range(1, len(nodelist)): 635 elt = nodelist[i] 636 if elt[0] == token["DOUBLESTAR"]: 637 return Power([node, self.com_node(nodelist[i+1])], 638 lineno=elt[2]) 639 640 node = self.com_apply_trailer(node, elt) 641 642 return node 643 644 def atom(self, nodelist): 645 return self._atom_dispatch[nodelist[0][0]](nodelist) 646 647 def atom_lpar(self, nodelist): 648 if nodelist[1][0] == token["RPAR"]: 649 return Tuple((), lineno=nodelist[0][2]) 650 return self.com_node(nodelist[1]) 651 652 def atom_lsqb(self, nodelist): 653 if nodelist[1][0] == token["RSQB"]: 654 return List((), lineno=nodelist[0][2]) 655 return self.com_list_constructor(nodelist[1]) 656 657 def atom_lbrace(self, nodelist): 658 if nodelist[1][0] == token["RBRACE"]: 659 return Dict((), lineno=nodelist[0][2]) 660 return self.com_dictorsetmaker(nodelist[1]) 661 662 def atom_backquote(self, nodelist): 663 return Backquote(self.com_node(nodelist[1])) 664 665 def atom_number(self, nodelist): 666 ### need to verify this matches compile.c 667 k = eval(nodelist[0][1]) 668 return Const(k, nodelist[0][1], lineno=nodelist[0][2]) 669 670 def decode_literal(self, lit): 671 if self.encoding: 672 return eval("# coding: %s\n%s" % (self.encoding, lit)) 673 else: 674 return eval(lit) 675 676 def atom_string(self, nodelist): 677 k = '' 678 for node in nodelist: 679 k += self.decode_literal(node[1]) 680 return Const(k, node[1], lineno=nodelist[0][2]) 681 682 def atom_name(self, nodelist): 683 return Name(nodelist[0][1], lineno=nodelist[0][2]) 684 685 # -------------------------------------------------------------- 686 # 687 # INTERNAL PARSING UTILITIES 688 # 689 690 # The use of com_node() introduces a lot of extra stack frames, 691 # enough to cause a stack overflow compiling test.test_parser with 692 # the standard interpreter recursionlimit. The com_node() is a 693 # convenience function that hides the dispatch details, but comes 694 # at a very high cost. It is more efficient to dispatch directly 695 # in the callers. In these cases, use lookup_node() and call the 696 # dispatched node directly. 697 698 def lookup_node(self, node): 699 return self._dispatch[node[0]] 700 701 def com_node(self, node): 702 # Note: compile.c has handling in com_node for del_stmt, pass_stmt, 703 # break_stmt, stmt, small_stmt, flow_stmt, simple_stmt, 704 # and compound_stmt. 705 # We'll just dispatch them. 706 return self._dispatch[node[0]](node[1:]) 707 708 def com_NEWLINE(self, *args): 709 # A ';' at the end of a line can make a NEWLINE token appear 710 # here, Render it harmless. (genc discards ('discard', 711 # ('const', xxxx)) Nodes) 712 return Discard(Const(None)) 713 714 def com_arglist(self, nodelist): 715 # varargslist: 716 # (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] | '**' NAME) 717 # | fpdef ['=' test] (',' fpdef ['=' test])* [','] 718 # fpdef: NAME | '(' fplist ')' 719 # fplist: fpdef (',' fpdef)* [','] 720 names = [] 721 defaults = [] 722 flags = 0 723 724 i = 0 725 while i < len(nodelist): 726 node = nodelist[i] 727 if node[0] == token["STAR"] or node[0] == token["DOUBLESTAR"]: 728 if node[0] == token["STAR"]: 729 node = nodelist[i+1] 730 if node[0] == token["NAME"]: 731 names.append(node[1]) 732 flags = flags | CO_VARARGS 733 i = i + 3 734 735 if i < len(nodelist): 736 # should be DOUBLESTAR 737 t = nodelist[i][0] 738 if t == token["DOUBLESTAR"]: 739 node = nodelist[i+1] 740 else: 741 raise ValueError, "unexpected token: %s" % t 742 names.append(node[1]) 743 flags = flags | CO_VARKEYWORDS 744 745 break 746 747 # fpdef: NAME | '(' fplist ')' 748 names.append(self.com_fpdef(node)) 749 750 i = i + 1 751 if i < len(nodelist) and nodelist[i][0] == token["EQUAL"]: 752 defaults.append(self.com_node(nodelist[i + 1])) 753 i = i + 2 754 elif len(defaults): 755 # we have already seen an argument with default, but here 756 # came one without 757 raise SyntaxError, "non-default argument follows default argument" 758 759 # skip the comma 760 i = i + 1 761 762 return names, defaults, flags 763 764 def com_fpdef(self, node): 765 # fpdef: NAME | '(' fplist ')' 766 if node[1][0] == token["LPAR"]: 767 return self.com_fplist(node[2]) 768 return node[1][1] 769 770 def com_fplist(self, node): 771 # fplist: fpdef (',' fpdef)* [','] 772 if len(node) == 2: 773 return self.com_fpdef(node[1]) 774 list = [] 775 for i in range(1, len(node), 2): 776 list.append(self.com_fpdef(node[i])) 777 return tuple(list) 778 779 def com_dotted_name(self, node): 780 # String together the dotted names and return the string 781 name = "" 782 for n in node: 783 if type(n) == type(()) and n[0] == 1: 784 name = name + n[1] + '.' 785 return name[:-1] 786 787 def com_dotted_as_name(self, node): 788 assert node[0] == symbol["dotted_as_name"] 789 node = node[1:] 790 dot = self.com_dotted_name(node[0][1:]) 791 if len(node) == 1: 792 return dot, None 793 assert node[1][1] == 'as' 794 assert node[2][0] == token["NAME"] 795 return dot, node[2][1] 796 797 def com_dotted_as_names(self, node): 798 assert node[0] == symbol["dotted_as_names"] 799 node = node[1:] 800 names = [self.com_dotted_as_name(node[0])] 801 for i in range(2, len(node), 2): 802 names.append(self.com_dotted_as_name(node[i])) 803 return names 804 805 def com_import_as_name(self, node): 806 assert node[0] == symbol["import_as_name"] 807 node = node[1:] 808 assert node[0][0] == token["NAME"] 809 if len(node) == 1: 810 return node[0][1], None 811 assert node[1][1] == 'as', node 812 assert node[2][0] == token["NAME"] 813 return node[0][1], node[2][1] 814 815 def com_import_as_names(self, node): 816 assert node[0] == symbol["import_as_names"] 817 node = node[1:] 818 names = [self.com_import_as_name(node[0])] 819 for i in range(2, len(node), 2): 820 names.append(self.com_import_as_name(node[i])) 821 return names 822 823 def com_bases(self, node): 824 bases = [] 825 for i in range(1, len(node), 2): 826 bases.append(self.com_node(node[i])) 827 return bases 828 829 def com_try_except_finally(self, nodelist): 830 # ('try' ':' suite 831 # ((except_clause ':' suite)+ ['else' ':' suite] ['finally' ':' suite] 832 # | 'finally' ':' suite)) 833 834 if nodelist[3][0] == token["NAME"]: 835 # first clause is a finally clause: only try-finally 836 return TryFinally(self.com_node(nodelist[2]), 837 self.com_node(nodelist[5]), 838 lineno=nodelist[0][2]) 839 840 #tryexcept: [TryNode, [except_clauses], elseNode)] 841 clauses = [] 842 elseNode = None 843 finallyNode = None 844 for i in range(3, len(nodelist), 3): 845 node = nodelist[i] 846 if node[0] == symbol["except_clause"]: 847 # except_clause: 'except' [expr [(',' | 'as') expr]] */ 848 if len(node) > 2: 849 expr1 = self.com_node(node[2]) 850 if len(node) > 4: 851 expr2 = self.com_assign(node[4], OP_ASSIGN) 852 else: 853 expr2 = None 854 else: 855 expr1 = expr2 = None 856 clauses.append((expr1, expr2, self.com_node(nodelist[i+2]))) 857 858 if node[0] == token["NAME"]: 859 if node[1] == 'else': 860 elseNode = self.com_node(nodelist[i+2]) 861 elif node[1] == 'finally': 862 finallyNode = self.com_node(nodelist[i+2]) 863 try_except = TryExcept(self.com_node(nodelist[2]), clauses, elseNode, 864 lineno=nodelist[0][2]) 865 if finallyNode: 866 return TryFinally(try_except, finallyNode, lineno=nodelist[0][2]) 867 else: 868 return try_except 869 870 def com_with(self, nodelist): 871 # with_stmt: 'with' with_item (',' with_item)* ':' suite 872 body = self.com_node(nodelist[-1]) 873 for i in range(len(nodelist) - 3, 0, -2): 874 ret = self.com_with_item(nodelist[i], body, nodelist[0][2]) 875 if i == 1: 876 return ret 877 body = ret 878 879 def com_with_item(self, nodelist, body, lineno): 880 # with_item: test ['as' expr] 881 if len(nodelist) == 4: 882 var = self.com_assign(nodelist[3], OP_ASSIGN) 883 else: 884 var = None 885 expr = self.com_node(nodelist[1]) 886 return With(expr, var, body, lineno=lineno) 887 888 def com_augassign_op(self, node): 889 assert node[0] == symbol["augassign"] 890 return node[1] 891 892 def com_augassign(self, node): 893 """Return node suitable for lvalue of augmented assignment 894 895 Names, slices, and attributes are the only allowable nodes. 896 """ 897 l = self.com_node(node) 898 if l.__class__ in (Name, Slice, Subscript, Getattr): 899 return l 900 raise SyntaxError, "can't assign to %s" % l.__class__.__name__ 901 902 def com_assign(self, node, assigning): 903 # return a node suitable for use as an "lvalue" 904 # loop to avoid trivial recursion 905 while 1: 906 t = node[0] 907 if t in (symbol["exprlist"], symbol["testlist"], symbol["testlist_safe"], symbol["testlist_comp"]): 908 if len(node) > 2: 909 return self.com_assign_tuple(node, assigning) 910 node = node[1] 911 elif t in _assign_types: 912 if len(node) > 2: 913 raise SyntaxError, "can't assign to operator" 914 node = node[1] 915 elif t == symbol["power"]: 916 if node[1][0] != symbol["atom"]: 917 raise SyntaxError, "can't assign to operator" 918 if len(node) > 2: 919 primary = self.com_node(node[1]) 920 for i in range(2, len(node)-1): 921 ch = node[i] 922 if ch[0] == token["DOUBLESTAR"]: 923 raise SyntaxError, "can't assign to operator" 924 primary = self.com_apply_trailer(primary, ch) 925 return self.com_assign_trailer(primary, node[-1], 926 assigning) 927 node = node[1] 928 elif t == symbol["atom"]: 929 t = node[1][0] 930 if t == token["LPAR"]: 931 node = node[2] 932 if node[0] == token["RPAR"]: 933 raise SyntaxError, "can't assign to ()" 934 elif t == token["LSQB"]: 935 node = node[2] 936 if node[0] == token["RSQB"]: 937 raise SyntaxError, "can't assign to []" 938 return self.com_assign_list(node, assigning) 939 elif t == token["NAME"]: 940 return self.com_assign_name(node[1], assigning) 941 else: 942 raise SyntaxError, "can't assign to literal" 943 else: 944 raise SyntaxError, "bad assignment (%s)" % t 945 946 def com_assign_tuple(self, node, assigning): 947 assigns = [] 948 for i in range(1, len(node), 2): 949 assigns.append(self.com_assign(node[i], assigning)) 950 return AssTuple(assigns, lineno=extractLineNo(node)) 951 952 def com_assign_list(self, node, assigning): 953 assigns = [] 954 for i in range(1, len(node), 2): 955 if i + 1 < len(node): 956 if node[i + 1][0] == symbol["list_for"]: 957 raise SyntaxError, "can't assign to list comprehension" 958 assert node[i + 1][0] == token["COMMA"], node[i + 1] 959 assigns.append(self.com_assign(node[i], assigning)) 960 return AssList(assigns, lineno=extractLineNo(node)) 961 962 def com_assign_name(self, node, assigning): 963 return AssName(node[1], assigning, lineno=node[2]) 964 965 def com_assign_trailer(self, primary, node, assigning): 966 t = node[1][0] 967 if t == token["DOT"]: 968 return self.com_assign_attr(primary, node[2], assigning) 969 if t == token["LSQB"]: 970 return self.com_subscriptlist(primary, node[2], assigning) 971 if t == token["LPAR"]: 972 raise SyntaxError, "can't assign to function call" 973 raise SyntaxError, "unknown trailer type: %s" % t 974 975 def com_assign_attr(self, primary, node, assigning): 976 return AssAttr(primary, node[1], assigning, lineno=node[-1]) 977 978 def com_binary(self, constructor, nodelist): 979 "Compile 'NODE (OP NODE)*' into (type, [ node1, ..., nodeN ])." 980 l = len(nodelist) 981 if l == 1: 982 n = nodelist[0] 983 return self.lookup_node(n)(n[1:]) 984 items = [] 985 for i in range(0, l, 2): 986 n = nodelist[i] 987 items.append(self.lookup_node(n)(n[1:])) 988 return constructor(items, lineno=extractLineNo(nodelist)) 989 990 def com_stmt(self, node): 991 result = self.lookup_node(node)(node[1:]) 992 assert result is not None 993 if isinstance(result, Stmt): 994 return result 995 return Stmt([result]) 996 997 def com_append_stmt(self, stmts, node): 998 result = self.lookup_node(node)(node[1:]) 999 assert result is not None 1000 if isinstance(result, Stmt): 1001 stmts.extend(result.nodes) 1002 else: 1003 stmts.append(result) 1004 1005 def com_list_constructor(self, nodelist): 1006 # listmaker: test ( (',' test)* [','] ) 1007 values = [] 1008 for i in range(1, len(nodelist)): 1009 if nodelist[i][0] == token["COMMA"]: 1010 continue 1011 values.append(self.com_node(nodelist[i])) 1012 return List(values, lineno=values[0].lineno) 1013 1014 def com_dictorsetmaker(self, nodelist): 1015 # dictorsetmaker: ( (test ':' test ( (',' test ':' test)* [','])) | 1016 # (test ( (',' test)* [','])) ) 1017 assert nodelist[0] == symbol["dictorsetmaker"] 1018 nodelist = nodelist[1:] 1019 if len(nodelist) == 1 or nodelist[1][0] == token["COMMA"]: 1020 # set literal 1021 items = [] 1022 for i in range(0, len(nodelist), 2): 1023 items.append(self.com_node(nodelist[i])) 1024 return Set(items, lineno=items[0].lineno) 1025 else: 1026 # dict literal 1027 items = [] 1028 for i in range(0, len(nodelist), 4): 1029 items.append((self.com_node(nodelist[i]), 1030 self.com_node(nodelist[i+2]))) 1031 return Dict(items, lineno=items[0][0].lineno) 1032 1033 def com_apply_trailer(self, primaryNode, nodelist): 1034 t = nodelist[1][0] 1035 if t == token["LPAR"]: 1036 return self.com_call_function(primaryNode, nodelist[2]) 1037 if t == token["DOT"]: 1038 return self.com_select_member(primaryNode, nodelist[2]) 1039 if t == token["LSQB"]: 1040 return self.com_subscriptlist(primaryNode, nodelist[2], OP_APPLY) 1041 1042 raise SyntaxError, 'unknown node type: %s' % t 1043 1044 def com_select_member(self, primaryNode, nodelist): 1045 if nodelist[0] != token["NAME"]: 1046 raise SyntaxError, "member must be a name" 1047 return Getattr(primaryNode, nodelist[1], lineno=nodelist[2]) 1048 1049 def com_call_function(self, primaryNode, nodelist): 1050 if nodelist[0] == token["RPAR"]: 1051 return CallFunc(primaryNode, [], lineno=extractLineNo(nodelist)) 1052 args = [] 1053 kw = 0 1054 star_node = dstar_node = None 1055 len_nodelist = len(nodelist) 1056 i = 1 1057 while i < len_nodelist: 1058 node = nodelist[i] 1059 1060 if node[0]==token["STAR"]: 1061 if star_node is not None: 1062 raise SyntaxError, 'already have the varargs indentifier' 1063 star_node = self.com_node(nodelist[i+1]) 1064 i = i + 3 1065 continue 1066 elif node[0]==token["DOUBLESTAR"]: 1067 if dstar_node is not None: 1068 raise SyntaxError, 'already have the kwargs indentifier' 1069 dstar_node = self.com_node(nodelist[i+1]) 1070 i = i + 3 1071 continue 1072 1073 # positional or named parameters 1074 kw, result = self.com_argument(node, kw, star_node) 1075 1076 args.append(result) 1077 i = i + 2 1078 1079 return CallFunc(primaryNode, args, star_node, dstar_node, 1080 lineno=extractLineNo(nodelist)) 1081 1082 def com_argument(self, nodelist, kw, star_node): 1083 if len(nodelist) == 2: 1084 if kw: 1085 raise SyntaxError, "non-keyword arg after keyword arg" 1086 if star_node: 1087 raise SyntaxError, "only named arguments may follow *expression" 1088 return 0, self.com_node(nodelist[1]) 1089 result = self.com_node(nodelist[3]) 1090 n = nodelist[1] 1091 while len(n) == 2 and n[0] != token["NAME"]: 1092 n = n[1] 1093 if n[0] != token["NAME"]: 1094 raise SyntaxError, "keyword can't be an expression (%s)"%n[0] 1095 node = Keyword(n[1], result, lineno=n[2]) 1096 return 1, node 1097 1098 def com_subscriptlist(self, primary, nodelist, assigning): 1099 # slicing: simple_slicing | extended_slicing 1100 # simple_slicing: primary "[" short_slice "]" 1101 # extended_slicing: primary "[" slice_list "]" 1102 # slice_list: slice_item ("," slice_item)* [","] 1103 1104 # backwards compat slice for '[i:j]' 1105 if len(nodelist) == 2: 1106 sub = nodelist[1] 1107 if (sub[1][0] == token["COLON"] or \ 1108 (len(sub) > 2 and sub[2][0] == token["COLON"])) and \ 1109 sub[-1][0] != symbol["sliceop"]: 1110 return self.com_slice(primary, sub, assigning) 1111 1112 subscripts = [] 1113 for i in range(1, len(nodelist), 2): 1114 subscripts.append(self.com_subscript(nodelist[i])) 1115 return Subscript(primary, assigning, subscripts, 1116 lineno=extractLineNo(nodelist)) 1117 1118 def com_subscript(self, node): 1119 # slice_item: expression | proper_slice | ellipsis 1120 ch = node[1] 1121 t = ch[0] 1122 if t == token["DOT"] and node[2][0] == token["DOT"]: 1123 return Ellipsis() 1124 if t == token["COLON"] or len(node) > 2: 1125 return self.com_sliceobj(node) 1126 return self.com_node(ch) 1127 1128 def com_sliceobj(self, node): 1129 # proper_slice: short_slice | long_slice 1130 # short_slice: [lower_bound] ":" [upper_bound] 1131 # long_slice: short_slice ":" [stride] 1132 # lower_bound: expression 1133 # upper_bound: expression 1134 # stride: expression 1135 # 1136 # Note: a stride may be further slicing... 1137 1138 items = [] 1139 1140 if node[1][0] == token["COLON"]: 1141 items.append(Const(None)) 1142 i = 2 1143 else: 1144 items.append(self.com_node(node[1])) 1145 # i == 2 is a COLON 1146 i = 3 1147 1148 if i < len(node) and node[i][0] == symbol["test"]: 1149 items.append(self.com_node(node[i])) 1150 i = i + 1 1151 else: 1152 items.append(Const(None)) 1153 1154 # a short_slice has been built. look for long_slice now by looking 1155 # for strides... 1156 for j in range(i, len(node)): 1157 ch = node[j] 1158 if len(ch) == 2: 1159 items.append(Const(None)) 1160 else: 1161 items.append(self.com_node(ch[2])) 1162 return Sliceobj(items, lineno=extractLineNo(node)) 1163 1164 def com_slice(self, primary, node, assigning): 1165 # short_slice: [lower_bound] ":" [upper_bound] 1166 lower = upper = None 1167 if len(node) == 3: 1168 if node[1][0] == token["COLON"]: 1169 upper = self.com_node(node[2]) 1170 else: 1171 lower = self.com_node(node[1]) 1172 elif len(node) == 4: 1173 lower = self.com_node(node[1]) 1174 upper = self.com_node(node[3]) 1175 return Slice(primary, assigning, lower, upper, 1176 lineno=extractLineNo(node)) 1177 1178 def get_docstring(self, node, n=None): 1179 if n is None: 1180 n = node[0] 1181 node = node[1:] 1182 if n == symbol["suite"]: 1183 if len(node) == 1: 1184 return self.get_docstring(node[0]) 1185 for sub in node: 1186 if sub[0] == symbol["stmt"]: 1187 return self.get_docstring(sub) 1188 return None 1189 if n == symbol["file_input"]: 1190 for sub in node: 1191 if sub[0] == symbol["stmt"]: 1192 return self.get_docstring(sub) 1193 return None 1194 if n == symbol["atom"]: 1195 if node[0][0] == token["STRING"]: 1196 s = '' 1197 for t in node: 1198 s = s + eval(t[1]) 1199 return s 1200 return None 1201 if n == symbol["stmt"] or n == symbol["simple_stmt"] \ 1202 or n == symbol["small_stmt"]: 1203 return self.get_docstring(node[0]) 1204 if n in _doc_nodes and len(node) == 1: 1205 return self.get_docstring(node[0]) 1206 return None 1207 1208 1209 _doc_nodes = [ 1210 symbol["expr_stmt"], 1211 symbol["testlist"], 1212 symbol["testlist_safe"], 1213 symbol["test"], 1214 symbol["or_test"], 1215 symbol["and_test"], 1216 symbol["not_test"], 1217 symbol["comparison"], 1218 symbol["expr"], 1219 symbol["xor_expr"], 1220 symbol["and_expr"], 1221 symbol["shift_expr"], 1222 symbol["arith_expr"], 1223 symbol["term"], 1224 symbol["factor"], 1225 symbol["power"], 1226 ] 1227 1228 # comp_op: '<' | '>' | '=' | '>=' | '<=' | '<>' | '!=' | '==' 1229 # | 'in' | 'not' 'in' | 'is' | 'is' 'not' 1230 _cmp_types = { 1231 token["LESS"] : '<', 1232 token["GREATER"] : '>', 1233 token["EQEQUAL"] : '==', 1234 token["EQUAL"] : '==', 1235 token["LESSEQUAL"] : '<=', 1236 token["GREATEREQUAL"] : '>=', 1237 token["NOTEQUAL"] : '!=', 1238 } 1239 1240 _legal_node_types = [ 1241 symbol["funcdef"], 1242 symbol["classdef"], 1243 symbol["stmt"], 1244 symbol["small_stmt"], 1245 symbol["flow_stmt"], 1246 symbol["simple_stmt"], 1247 symbol["compound_stmt"], 1248 symbol["expr_stmt"], 1249 symbol["print_stmt"], 1250 symbol["del_stmt"], 1251 symbol["pass_stmt"], 1252 symbol["break_stmt"], 1253 symbol["continue_stmt"], 1254 symbol["return_stmt"], 1255 symbol["raise_stmt"], 1256 symbol["import_stmt"], 1257 symbol["global_stmt"], 1258 symbol["exec_stmt"], 1259 symbol["assert_stmt"], 1260 symbol["if_stmt"], 1261 symbol["while_stmt"], 1262 symbol["for_stmt"], 1263 symbol["try_stmt"], 1264 symbol["with_stmt"], 1265 symbol["suite"], 1266 symbol["testlist"], 1267 symbol["testlist_safe"], 1268 symbol["test"], 1269 symbol["and_test"], 1270 symbol["not_test"], 1271 symbol["comparison"], 1272 symbol["exprlist"], 1273 symbol["expr"], 1274 symbol["xor_expr"], 1275 symbol["and_expr"], 1276 symbol["shift_expr"], 1277 symbol["arith_expr"], 1278 symbol["term"], 1279 symbol["factor"], 1280 symbol["power"], 1281 symbol["atom"], 1282 ] 1283 1284 _assign_types = [ 1285 symbol["test"], 1286 symbol["or_test"], 1287 symbol["and_test"], 1288 symbol["not_test"], 1289 symbol["comparison"], 1290 symbol["expr"], 1291 symbol["xor_expr"], 1292 symbol["and_expr"], 1293 symbol["shift_expr"], 1294 symbol["arith_expr"], 1295 symbol["term"], 1296 symbol["factor"], 1297 ] 1298 1299 _names = {} 1300 for k, v in sym_name.items(): 1301 _names[k] = v 1302 for k, v in tok_name.items(): 1303 _names[k] = v 1304 1305 def debug_tree(tree): 1306 l = [] 1307 for elt in tree: 1308 if isinstance(elt, int): 1309 l.append(_names.get(elt, elt)) 1310 elif isinstance(elt, str): 1311 l.append(elt) 1312 else: 1313 l.append(debug_tree(elt)) 1314 return l