Lichen

Annotated compiler/transformer.py

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