581ab9980360c82cc31073bdfa188bf833c3e55b
"""Parse tree transformation module.
Transforms Python source code into an abstract syntax tree (AST)
defined in the ast module.
The simplest ways to invoke this module are via parse and parseFile.
# Original version written by Greg Stein (gstein@lyra.org)
# and Bill Tutt (rassilon@lima.mudlib.org)
# Modifications and improvements for Python 2.0 by Jeremy Hylton and
# Some fixes to try to have correct line number on almost all nodes
# (except Module, Discard and Stmt) added by Sylvain Thenault
# Portions of this file are:
# Copyright (C) 1997-1998 Greg Stein. All Rights Reserved.
# This module is provided under a BSD-ish license. See
# http://www.opensource.org/licenses/bsd-license.html
# and replace OWNER, ORGANIZATION, and YEAR as appropriate.
from compiler
.ast
import *
class WalkerError(StandardError):
from consts
import CO_VARARGS
, CO_VARKEYWORDS
from consts
import OP_ASSIGN
, OP_DELETE
, OP_APPLY
# XXX The parser API tolerates files without a trailing newline,
# but not strings without a trailing newline. Always add an extra
# newline to the file contents, since we're going through the string
def parse(buf
, mode
="exec"):
if mode
== "exec" or mode
== "single":
return Transformer().parsesuite(buf
)
return Transformer().parseexpr(buf
)
raise ValueError("compile() arg 3 must be"
" 'exec' or 'eval' or 'single'")
if hasattr(item
, "asList"):
if type(item
) is type( (None, None) ):
l
.append(tuple(asList(item
)))
elif type(item
) is type( [] ):
if not isinstance(ast
[1], tuple):
if isinstance(child
, tuple):
lineno
= extractLineNo(child
)
return nodes
[kind
](*args
[1:])
print nodes
[kind
], len(args
), args
raise WalkerError
, "Can't find appropriate Node type: %s" % str(args
)
#return apply(ast.Node, args)
"""Utility object for transforming Python parse trees.
Exposes the following methods:
tree = transform(ast_tree)
tree = parsefile(fileob | filename)
for value
, name
in symbol
.sym_name
.items():
self
._dispatch
[value
] = getattr(self
, name
)
self
._dispatch
[token
.NEWLINE
] = self
.com_NEWLINE
self
._atom
_dispatch
= {token
.LPAR
: self
.atom_lpar
,
token
.LSQB
: self
.atom_lsqb
,
token
.LBRACE
: self
.atom_lbrace
,
token
.BACKQUOTE
: self
.atom_backquote
,
token
.NUMBER
: self
.atom_number
,
token
.STRING
: self
.atom_string
,
token
.NAME
: self
.atom_name
,
def transform(self
, tree
):
"""Transform an AST into a modified parse tree."""
if not (isinstance(tree
, tuple) or isinstance(tree
, list)):
tree
= parser
.ast2tuple(tree
, line_info
=1)
return self
.compile_node(tree
)
def parsesuite(self
, text
):
"""Return a modified parse tree for the given suite text."""
return self
.transform(parser
.suite(text
))
def parseexpr(self
, text
):
"""Return a modified parse tree for the given expression text."""
return self
.transform(parser
.expr(text
))
def parsefile(self
, file):
"""Return a modified parse tree for the contents of the given file."""
if type(file) == type(''):
return self
.parsesuite(file.read())
# --------------------------------------------------------------
def compile_node(self
, node
):
### emit a line-number node?
if n
== symbol
.encoding_decl
:
if n
== symbol
.single_input
:
return self
.single_input(node
[1:])
if n
== symbol
.file_input
:
return self
.file_input(node
[1:])
if n
== symbol
.eval_input
:
return self
.eval_input(node
[1:])
return self
.lambdef(node
[1:])
return self
.funcdef(node
[1:])
return self
.classdef(node
[1:])
raise WalkerError
, ('unexpected node type', n
)
def single_input(self
, node
):
### do we want to do anything about being "interactive" ?
# NEWLINE | simple_stmt | compound_stmt NEWLINE
return self
.com_stmt(node
[0])
def file_input(self
, nodelist
):
doc
= self
.get_docstring(nodelist
, symbol
.file_input
)
for node
in nodelist
[i
:]:
if node
[0] != token
.ENDMARKER
and node
[0] != token
.NEWLINE
:
self
.com_append_stmt(stmts
, node
)
return Module(doc
, Stmt(stmts
))
def eval_input(self
, nodelist
):
# from the built-in function input()
return Expression(self
.com_node(nodelist
[0]))
def decorator_name(self
, nodelist
):
assert listlen
>= 1 and listlen
% 2 == 1
item
= self
.atom_name(nodelist
)
assert nodelist
[i
][0] == token
.DOT
assert nodelist
[i
+ 1][0] == token
.NAME
item
= Getattr(item
, nodelist
[i
+ 1][1])
def decorator(self
, nodelist
):
# '@' dotted_name [ '(' [arglist] ')' ]
assert len(nodelist
) in (3, 5, 6)
assert nodelist
[0][0] == token
.AT
assert nodelist
[-1][0] == token
.NEWLINE
assert nodelist
[1][0] == symbol
.dotted_name
funcname
= self
.decorator_name(nodelist
[1][1:])
assert nodelist
[2][0] == token
.LPAR
expr
= self
.com_call_function(funcname
, nodelist
[3])
def decorators(self
, nodelist
):
# decorators: decorator ([NEWLINE] decorator)* NEWLINE
for dec_nodelist
in nodelist
:
assert dec_nodelist
[0] == symbol
.decorator
items
.append(self
.decorator(dec_nodelist
[1:]))
def funcdef(self
, nodelist
):
# funcdef: [decorators] 'def' NAME parameters ':' suite
# parameters: '(' [varargslist] ')'
assert nodelist
[0][0] == symbol
.decorators
decorators
= self
.decorators(nodelist
[0][1:])
assert len(nodelist
) == 5
if args
[0] == symbol
.varargslist
:
names
, defaults
, flags
= self
.com_arglist(args
[1:])
doc
= self
.get_docstring(nodelist
[-1])
code
= self
.com_node(nodelist
[-1])
assert isinstance(code
, Stmt
)
assert isinstance(code
.nodes
[0], Discard
)
return Function(decorators
, name
, names
, defaults
, flags
, doc
, code
,
def lambdef(self
, nodelist
):
# lambdef: 'lambda' [varargslist] ':' test
if nodelist
[2][0] == symbol
.varargslist
:
names
, defaults
, flags
= self
.com_arglist(nodelist
[2][1:])
code
= self
.com_node(nodelist
[-1])
return Lambda(names
, defaults
, flags
, code
, lineno
=nodelist
[1][2])
def classdef(self
, nodelist
):
# classdef: 'class' NAME ['(' testlist ')'] ':' suite
doc
= self
.get_docstring(nodelist
[-1])
if nodelist
[2][0] == token
.COLON
:
bases
= self
.com_bases(nodelist
[3])
code
= self
.com_node(nodelist
[-1])
assert isinstance(code
, Stmt
)
assert isinstance(code
.nodes
[0], Discard
)
return Class(name
, bases
, doc
, code
, lineno
=nodelist
[1][2])
def stmt(self
, nodelist
):
return self
.com_stmt(nodelist
[0])
def simple_stmt(self
, nodelist
):
# small_stmt (';' small_stmt)* [';'] NEWLINE
for i
in range(0, len(nodelist
), 2):
self
.com_append_stmt(stmts
, nodelist
[i
])
def parameters(self
, nodelist
):
def varargslist(self
, nodelist
):
def fpdef(self
, nodelist
):
def fplist(self
, nodelist
):
def dotted_name(self
, nodelist
):
def comp_op(self
, nodelist
):
def trailer(self
, nodelist
):
def sliceop(self
, nodelist
):
def argument(self
, nodelist
):
# --------------------------------------------------------------
# STATEMENT NODES (invoked by com_node())
def expr_stmt(self
, nodelist
):
# augassign testlist | testlist ('=' testlist)*
exprNode
= self
.lookup_node(en
)(en
[1:])
return Discard(exprNode
, lineno
=exprNode
.lineno
)
if nodelist
[1][0] == token
.EQUAL
:
for i
in range(0, len(nodelist
) - 2, 2):
nodesl
.append(self
.com_assign(nodelist
[i
], OP_ASSIGN
))
return Assign(nodesl
, exprNode
, lineno
=nodelist
[1][2])
lval
= self
.com_augassign(nodelist
[0])
op
= self
.com_augassign_op(nodelist
[1])
return AugAssign(lval
, op
[1], exprNode
, lineno
=op
[2])
raise WalkerError
, "can't get here"
def print_stmt(self
, nodelist
):
# print ([ test (',' test)* [','] ] | '>>' test [ (',' test)+ [','] ])
elif nodelist
[1][0] == token
.RIGHTSHIFT
:
assert len(nodelist
) == 3 \
or nodelist
[3][0] == token
.COMMA
dest
= self
.com_node(nodelist
[2])
for i
in range(start
, len(nodelist
), 2):
items
.append(self
.com_node(nodelist
[i
]))
if nodelist
[-1][0] == token
.COMMA
:
return Print(items
, dest
, lineno
=nodelist
[0][2])
return Printnl(items
, dest
, lineno
=nodelist
[0][2])
def del_stmt(self
, nodelist
):
return self
.com_assign(nodelist
[1], OP_DELETE
)
def pass_stmt(self
, nodelist
):
return Pass(lineno
=nodelist
[0][2])
def break_stmt(self
, nodelist
):
return Break(lineno
=nodelist
[0][2])
def continue_stmt(self
, nodelist
):
return Continue(lineno
=nodelist
[0][2])
def return_stmt(self
, nodelist
):
return Return(Const(None), lineno
=nodelist
[0][2])
return Return(self
.com_node(nodelist
[1]), lineno
=nodelist
[0][2])
def yield_stmt(self
, nodelist
):
return Yield(self
.com_node(nodelist
[1]), lineno
=nodelist
[0][2])
def raise_stmt(self
, nodelist
):
# raise: [test [',' test [',' test]]]
expr3
= self
.com_node(nodelist
[5])
expr2
= self
.com_node(nodelist
[3])
expr1
= self
.com_node(nodelist
[1])
return Raise(expr1
, expr2
, expr3
, lineno
=nodelist
[0][2])
def import_stmt(self
, nodelist
):
# import_stmt: import_name | import_from
assert len(nodelist
) == 1
return self
.com_node(nodelist
[0])
def import_name(self
, nodelist
):
# import_name: 'import' dotted_as_names
return Import(self
.com_dotted_as_names(nodelist
[1]),
def import_from(self
, nodelist
):
# import_from: 'from' dotted_name 'import' ('*' |
# '(' import_as_names ')' | import_as_names)
assert nodelist
[0][1] == 'from'
assert nodelist
[1][0] == symbol
.dotted_name
assert nodelist
[2][1] == 'import'
fromname
= self
.com_dotted_name(nodelist
[1])
if nodelist
[3][0] == token
.STAR
:
return From(fromname
, [('*', None)],
node
= nodelist
[3 + (nodelist
[3][0] == token
.LPAR
)]
return From(fromname
, self
.com_import_as_names(node
),
def global_stmt(self
, nodelist
):
# global: NAME (',' NAME)*
for i
in range(1, len(nodelist
), 2):
names
.append(nodelist
[i
][1])
return Global(names
, lineno
=nodelist
[0][2])
def exec_stmt(self
, nodelist
):
# exec_stmt: 'exec' expr ['in' expr [',' expr]]
expr1
= self
.com_node(nodelist
[1])
expr2
= self
.com_node(nodelist
[3])
expr3
= self
.com_node(nodelist
[5])
return Exec(expr1
, expr2
, expr3
, lineno
=nodelist
[0][2])
def assert_stmt(self
, nodelist
):
# 'assert': test, [',' test]
expr1
= self
.com_node(nodelist
[1])
expr2
= self
.com_node(nodelist
[3])
return Assert(expr1
, expr2
, lineno
=nodelist
[0][2])
def if_stmt(self
, nodelist
):
# if: test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
for i
in range(0, len(nodelist
) - 3, 4):
testNode
= self
.com_node(nodelist
[i
+ 1])
suiteNode
= self
.com_node(nodelist
[i
+ 3])
tests
.append((testNode
, suiteNode
))
if len(nodelist
) % 4 == 3:
elseNode
= self
.com_node(nodelist
[-1])
## elseNode.lineno = nodelist[-1][1][2]
return If(tests
, elseNode
, lineno
=nodelist
[0][2])
def while_stmt(self
, nodelist
):
# 'while' test ':' suite ['else' ':' suite]
testNode
= self
.com_node(nodelist
[1])
bodyNode
= self
.com_node(nodelist
[3])
elseNode
= self
.com_node(nodelist
[6])
return While(testNode
, bodyNode
, elseNode
, lineno
=nodelist
[0][2])
def for_stmt(self
, nodelist
):
# 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
assignNode
= self
.com_assign(nodelist
[1], OP_ASSIGN
)
listNode
= self
.com_node(nodelist
[3])
bodyNode
= self
.com_node(nodelist
[5])
elseNode
= self
.com_node(nodelist
[8])
return For(assignNode
, listNode
, bodyNode
, elseNode
,
def try_stmt(self
, nodelist
):
# 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
# | 'try' ':' suite 'finally' ':' suite
if nodelist
[3][0] != symbol
.except_clause
:
return self
.com_try_finally(nodelist
)
return self
.com_try_except(nodelist
)
def suite(self
, nodelist
):
# simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
return self
.com_stmt(nodelist
[0])
if node
[0] == symbol
.stmt
:
self
.com_append_stmt(stmts
, node
)
# --------------------------------------------------------------
# EXPRESSION NODES (invoked by com_node())
def testlist(self
, nodelist
):
# testlist: expr (',' expr)* [',']
# testlist_safe: test [(',' test)+ [',']]
# exprlist: expr (',' expr)* [',']
return self
.com_binary(Tuple
, nodelist
)
testlist_safe
= testlist
# XXX
def testlist_gexp(self
, nodelist
):
if len(nodelist
) == 2 and nodelist
[1][0] == symbol
.gen_for
:
test
= self
.com_node(nodelist
[0])
return self
.com_generator_expression(test
, nodelist
[1])
return self
.testlist(nodelist
)
def test(self
, nodelist
):
# and_test ('or' and_test)* | lambdef
if len(nodelist
) == 1 and nodelist
[0][0] == symbol
.lambdef
:
return self
.lambdef(nodelist
[0])
return self
.com_binary(Or
, nodelist
)
def and_test(self
, nodelist
):
# not_test ('and' not_test)*
return self
.com_binary(And
, nodelist
)
def not_test(self
, nodelist
):
# 'not' not_test | comparison
result
= self
.com_node(nodelist
[-1])
return Not(result
, lineno
=nodelist
[0][2])
def comparison(self
, nodelist
):
# comparison: expr (comp_op expr)*
node
= self
.com_node(nodelist
[0])
for i
in range(2, len(nodelist
), 2):
# comp_op: '<' | '>' | '=' | '>=' | '<=' | '<>' | '!=' | '=='
# | 'in' | 'not' 'in' | 'is' | 'is' 'not'
results
.append((type, self
.com_node(nodelist
[i
])))
# we need a special "compare" node so that we can distinguish
# 3 < x < 5 from (3 < x) < 5
# the two have very different semantics and results (note that the
# latter form is always true)
return Compare(node
, results
, lineno
=lineno
)
def expr(self
, nodelist
):
# xor_expr ('|' xor_expr)*
return self
.com_binary(Bitor
, nodelist
)
def xor_expr(self
, nodelist
):
# xor_expr ('^' xor_expr)*
return self
.com_binary(Bitxor
, nodelist
)
def and_expr(self
, nodelist
):
# xor_expr ('&' xor_expr)*
return self
.com_binary(Bitand
, nodelist
)
def shift_expr(self
, nodelist
):
# shift_expr ('<<'|'>>' shift_expr)*
node
= self
.com_node(nodelist
[0])
for i
in range(2, len(nodelist
), 2):
right
= self
.com_node(nodelist
[i
])
if nodelist
[i
-1][0] == token
.LEFTSHIFT
:
node
= LeftShift([node
, right
], lineno
=nodelist
[1][2])
elif nodelist
[i
-1][0] == token
.RIGHTSHIFT
:
node
= RightShift([node
, right
], lineno
=nodelist
[1][2])
raise ValueError, "unexpected token: %s" % nodelist
[i
-1][0]
def arith_expr(self
, nodelist
):
node
= self
.com_node(nodelist
[0])
for i
in range(2, len(nodelist
), 2):
right
= self
.com_node(nodelist
[i
])
if nodelist
[i
-1][0] == token
.PLUS
:
node
= Add([node
, right
], lineno
=nodelist
[1][2])
elif nodelist
[i
-1][0] == token
.MINUS
:
node
= Sub([node
, right
], lineno
=nodelist
[1][2])
raise ValueError, "unexpected token: %s" % nodelist
[i
-1][0]
def term(self
, nodelist
):
node
= self
.com_node(nodelist
[0])
for i
in range(2, len(nodelist
), 2):
right
= self
.com_node(nodelist
[i
])
node
= Mul([node
, right
])
node
= Div([node
, right
])
node
= Mod([node
, right
])
elif t
== token
.DOUBLESLASH
:
node
= FloorDiv([node
, right
])
raise ValueError, "unexpected token: %s" % t
node
.lineno
= nodelist
[1][2]
def factor(self
, nodelist
):
node
= self
.lookup_node(nodelist
[-1])(nodelist
[-1][1:])
# need to handle (unary op)constant here...
return UnaryAdd(node
, lineno
=elt
[2])
return UnarySub(node
, lineno
=elt
[2])
node
= Invert(node
, lineno
=elt
[2])
def power(self
, nodelist
):
# power: atom trailer* ('**' factor)*
node
= self
.com_node(nodelist
[0])
for i
in range(1, len(nodelist
)):
if elt
[0] == token
.DOUBLESTAR
:
return Power([node
, self
.com_node(nodelist
[i
+1])],
node
= self
.com_apply_trailer(node
, elt
)
def atom(self
, nodelist
):
return self
._atom
_dispatch
[nodelist
[0][0]](nodelist
)
n
.lineno
= nodelist
[0][2]
def atom_lpar(self
, nodelist
):
if nodelist
[1][0] == token
.RPAR
:
return self
.com_node(nodelist
[1])
def atom_lsqb(self
, nodelist
):
if nodelist
[1][0] == token
.RSQB
:
return self
.com_list_constructor(nodelist
[1])
def atom_lbrace(self
, nodelist
):
if nodelist
[1][0] == token
.RBRACE
:
return self
.com_dictmaker(nodelist
[1])
def atom_backquote(self
, nodelist
):
return Backquote(self
.com_node(nodelist
[1]))
def atom_number(self
, nodelist
):
### need to verify this matches compile.c
return Const(k
, lineno
=nodelist
[0][2])
def decode_literal(self
, lit
):
# this is particularly fragile & a bit of a
# hack... changes in compile.c:parsestr and
# tokenizer.c must be reflected here.
if self
.encoding
not in ['utf-8', 'iso-8859-1']:
lit
= unicode(lit
, 'utf-8').encode(self
.encoding
)
return eval("# coding: %s\n%s" % (self
.encoding
, lit
))
def atom_string(self
, nodelist
):
k
+= self
.decode_literal(node
[1])
return Const(k
, lineno
=nodelist
[0][2])
def atom_name(self
, nodelist
):
return Name(nodelist
[0][1], lineno
=nodelist
[0][2])
# --------------------------------------------------------------
# INTERNAL PARSING UTILITIES
# The use of com_node() introduces a lot of extra stack frames,
# enough to cause a stack overflow compiling test.test_parser with
# the standard interpreter recursionlimit. The com_node() is a
# convenience function that hides the dispatch details, but comes
# at a very high cost. It is more efficient to dispatch directly
# in the callers. In these cases, use lookup_node() and call the
# dispatched node directly.
def lookup_node(self
, node
):
return self
._dispatch
[node
[0]]
def com_node(self
, node
):
# Note: compile.c has handling in com_node for del_stmt, pass_stmt,
# break_stmt, stmt, small_stmt, flow_stmt, simple_stmt,
# We'll just dispatch them.
return self
._dispatch
[node
[0]](node
[1:])
def com_NEWLINE(self
, *args
):
# A ';' at the end of a line can make a NEWLINE token appear
# here, Render it harmless. (genc discards ('discard',
# ('const', xxxx)) Nodes)
return Discard(Const(None))
def com_arglist(self
, nodelist
):
# (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] | '**' NAME)
# | fpdef ['=' test] (',' fpdef ['=' test])* [',']
# fpdef: NAME | '(' fplist ')'
# fplist: fpdef (',' fpdef)* [',']
if node
[0] == token
.STAR
or node
[0] == token
.DOUBLESTAR
:
if node
[0] == token
.STAR
:
if node
[0] == token
.NAME
:
flags
= flags | CO_VARARGS
if t
== token
.DOUBLESTAR
:
raise ValueError, "unexpected token: %s" % t
flags
= flags | CO_VARKEYWORDS
# fpdef: NAME | '(' fplist ')'
names
.append(self
.com_fpdef(node
))
if nodelist
[i
][0] == token
.EQUAL
:
defaults
.append(self
.com_node(nodelist
[i
+ 1]))
# XXX This should be a syntax error.
# Treat "(a=1, b)" as "(a=1, b=None)"
defaults
.append(Const(None))
return names
, defaults
, flags
def com_fpdef(self
, node
):
# fpdef: NAME | '(' fplist ')'
if node
[1][0] == token
.LPAR
:
return self
.com_fplist(node
[2])
def com_fplist(self
, node
):
# fplist: fpdef (',' fpdef)* [',']
return self
.com_fpdef(node
[1])
for i
in range(1, len(node
), 2):
list.append(self
.com_fpdef(node
[i
]))
def com_dotted_name(self
, node
):
# String together the dotted names and return the string
if type(n
) == type(()) and n
[0] == 1:
def com_dotted_as_name(self
, node
):
assert node
[0] == symbol
.dotted_as_name
dot
= self
.com_dotted_name(node
[0][1:])
assert node
[1][1] == 'as'
assert node
[2][0] == token
.NAME
def com_dotted_as_names(self
, node
):
assert node
[0] == symbol
.dotted_as_names
names
= [self
.com_dotted_as_name(node
[0])]
for i
in range(2, len(node
), 2):
names
.append(self
.com_dotted_as_name(node
[i
]))
def com_import_as_name(self
, node
):
assert node
[0] == symbol
.import_as_name
assert node
[0][0] == token
.NAME
assert node
[1][1] == 'as', node
assert node
[2][0] == token
.NAME
return node
[0][1], node
[2][1]
def com_import_as_names(self
, node
):
assert node
[0] == symbol
.import_as_names
names
= [self
.com_import_as_name(node
[0])]
for i
in range(2, len(node
), 2):
names
.append(self
.com_import_as_name(node
[i
]))
def com_bases(self
, node
):
for i
in range(1, len(node
), 2):
bases
.append(self
.com_node(node
[i
]))
def com_try_finally(self
, nodelist
):
# try_fin_stmt: "try" ":" suite "finally" ":" suite
return TryFinally(self
.com_node(nodelist
[2]),
self
.com_node(nodelist
[5]),
def com_try_except(self
, nodelist
):
# try_except: 'try' ':' suite (except_clause ':' suite)* ['else' suite]
#tryexcept: [TryNode, [except_clauses], elseNode)]
stmt
= self
.com_node(nodelist
[2])
for i
in range(3, len(nodelist
), 3):
if node
[0] == symbol
.except_clause
:
# except_clause: 'except' [expr [',' expr]] */
expr1
= self
.com_node(node
[2])
expr2
= self
.com_assign(node
[4], OP_ASSIGN
)
clauses
.append((expr1
, expr2
, self
.com_node(nodelist
[i
+2])))
if node
[0] == token
.NAME
:
elseNode
= self
.com_node(nodelist
[i
+2])
return TryExcept(self
.com_node(nodelist
[2]), clauses
, elseNode
,
def com_augassign_op(self
, node
):
assert node
[0] == symbol
.augassign
def com_augassign(self
, node
):
"""Return node suitable for lvalue of augmented assignment
Names, slices, and attributes are the only allowable nodes.
if l
.__class
__ in (Name
, Slice
, Subscript
, Getattr
):
raise SyntaxError, "can't assign to %s" % l
.__class
__.__name
__
def com_assign(self
, node
, assigning
):
# return a node suitable for use as an "lvalue"
# loop to avoid trivial recursion
if t
== symbol
.exprlist
or t
== symbol
.testlist
or t
== symbol
.testlist_gexp
:
return self
.com_assign_tuple(node
, assigning
)
raise SyntaxError, "can't assign to operator"
if node
[1][0] != symbol
.atom
:
raise SyntaxError, "can't assign to operator"
primary
= self
.com_node(node
[1])
for i
in range(2, len(node
)-1):
if ch
[0] == token
.DOUBLESTAR
:
raise SyntaxError, "can't assign to operator"
primary
= self
.com_apply_trailer(primary
, ch
)
return self
.com_assign_trailer(primary
, node
[-1],
if node
[0] == token
.RPAR
:
raise SyntaxError, "can't assign to ()"
if node
[0] == token
.RSQB
:
raise SyntaxError, "can't assign to []"
return self
.com_assign_list(node
, assigning
)
return self
.com_assign_name(node
[1], assigning
)
raise SyntaxError, "can't assign to literal"
raise SyntaxError, "bad assignment"
def com_assign_tuple(self
, node
, assigning
):
for i
in range(1, len(node
), 2):
assigns
.append(self
.com_assign(node
[i
], assigning
))
return AssTuple(assigns
, lineno
=extractLineNo(node
))
def com_assign_list(self
, node
, assigning
):
for i
in range(1, len(node
), 2):
if node
[i
+ 1][0] == symbol
.list_for
:
raise SyntaxError, "can't assign to list comprehension"
assert node
[i
+ 1][0] == token
.COMMA
, node
[i
+ 1]
assigns
.append(self
.com_assign(node
[i
], assigning
))
return AssList(assigns
, lineno
=extractLineNo(node
))
def com_assign_name(self
, node
, assigning
):
return AssName(node
[1], assigning
, lineno
=node
[2])
def com_assign_trailer(self
, primary
, node
, assigning
):
return self
.com_assign_attr(primary
, node
[2], assigning
)
return self
.com_subscriptlist(primary
, node
[2], assigning
)
raise SyntaxError, "can't assign to function call"
raise SyntaxError, "unknown trailer type: %s" % t
def com_assign_attr(self
, primary
, node
, assigning
):
return AssAttr(primary
, node
[1], assigning
, lineno
=node
[-1])
def com_binary(self
, constructor
, nodelist
):
"Compile 'NODE (OP NODE)*' into (type, [ node1, ..., nodeN ])."
return self
.lookup_node(n
)(n
[1:])
items
.append(self
.lookup_node(n
)(n
[1:]))
return constructor(items
, lineno
=extractLineNo(nodelist
))
def com_stmt(self
, node
):
result
= self
.lookup_node(node
)(node
[1:])
assert result
is not None
if isinstance(result
, Stmt
):
def com_append_stmt(self
, stmts
, node
):
result
= self
.lookup_node(node
)(node
[1:])
assert result
is not None
if isinstance(result
, Stmt
):
stmts
.extend(result
.nodes
)
if hasattr(symbol
, 'list_for'):
def com_list_constructor(self
, nodelist
):
# listmaker: test ( list_for | (',' test)* [','] )
for i
in range(1, len(nodelist
)):
if nodelist
[i
][0] == symbol
.list_for
:
assert len(nodelist
[i
:]) == 1
return self
.com_list_comprehension(values
[0],
elif nodelist
[i
][0] == token
.COMMA
:
values
.append(self
.com_node(nodelist
[i
]))
return List(values
, lineno
=values
[0].lineno
)
def com_list_comprehension(self
, expr
, node
):
# list_iter: list_for | list_if
# list_for: 'for' exprlist 'in' testlist [list_iter]
# list_if: 'if' test [list_iter]
# XXX should raise SyntaxError for assignment
assignNode
= self
.com_assign(node
[2], OP_ASSIGN
)
listNode
= self
.com_node(node
[4])
newfor
= ListCompFor(assignNode
, listNode
, [])
newfor
.lineno
= node
[1][2]
node
= self
.com_list_iter(node
[5])
test
= self
.com_node(node
[2])
newif
= ListCompIf(test
, lineno
=node
[1][2])
node
= self
.com_list_iter(node
[3])
("unexpected list comprehension element: %s %d"
return ListComp(expr
, fors
, lineno
=lineno
)
def com_list_iter(self
, node
):
assert node
[0] == symbol
.list_iter
def com_list_constructor(self
, nodelist
):
for i
in range(1, len(nodelist
), 2):
values
.append(self
.com_node(nodelist
[i
]))
if hasattr(symbol
, 'gen_for'):
def com_generator_expression(self
, expr
, node
):
# gen_iter: gen_for | gen_if
# gen_for: 'for' exprlist 'in' test [gen_iter]
# gen_if: 'if' test [gen_iter]
assignNode
= self
.com_assign(node
[2], OP_ASSIGN
)
genNode
= self
.com_node(node
[4])
newfor
= GenExprFor(assignNode
, genNode
, [],
node
= self
.com_gen_iter(node
[5])
test
= self
.com_node(node
[2])
newif
= GenExprIf(test
, lineno
=node
[1][2])
node
= self
.com_gen_iter(node
[3])
("unexpected generator expression element: %s %d"
fors
[0].is_outmost
= True
return GenExpr(GenExprInner(expr
, fors
), lineno
=lineno
)
def com_gen_iter(self
, node
):
assert node
[0] == symbol
.gen_iter
def com_dictmaker(self
, nodelist
):
# dictmaker: test ':' test (',' test ':' value)* [',']
for i
in range(1, len(nodelist
), 4):
items
.append((self
.com_node(nodelist
[i
]),
self
.com_node(nodelist
[i
+2])))
def com_apply_trailer(self
, primaryNode
, nodelist
):
return self
.com_call_function(primaryNode
, nodelist
[2])
return self
.com_select_member(primaryNode
, nodelist
[2])
return self
.com_subscriptlist(primaryNode
, nodelist
[2], OP_APPLY
)
raise SyntaxError, 'unknown node type: %s' % t
def com_select_member(self
, primaryNode
, nodelist
):
if nodelist
[0] != token
.NAME
:
raise SyntaxError, "member must be a name"
return Getattr(primaryNode
, nodelist
[1], lineno
=nodelist
[2])
def com_call_function(self
, primaryNode
, nodelist
):
if nodelist
[0] == token
.RPAR
:
return CallFunc(primaryNode
, [], lineno
=extractLineNo(nodelist
))
len_nodelist
= len(nodelist
)
for i
in range(1, len_nodelist
, 2):
if node
[0] == token
.STAR
or node
[0] == token
.DOUBLESTAR
:
kw
, result
= self
.com_argument(node
, kw
)
if len_nodelist
!= 2 and isinstance(result
, GenExpr
) \
and len(node
) == 3 and node
[2][0] == symbol
.gen_for
:
# allow f(x for x in y), but reject f(x for x in y, 1)
# should use f((x for x in y), 1) instead of f(x for x in y, 1)
raise SyntaxError, 'generator expression needs parenthesis'
# No broken by star arg, so skip the last one we processed.
if i
< len_nodelist
and nodelist
[i
][0] == token
.COMMA
:
# need to accept an application that looks like "f(a, b,)"
star_node
= dstar_node
= None
if star_node
is not None:
raise SyntaxError, 'already have the varargs indentifier'
star_node
= self
.com_node(ch
)
elif tok
[0]==token
.DOUBLESTAR
:
if dstar_node
is not None:
raise SyntaxError, 'already have the kwargs indentifier'
dstar_node
= self
.com_node(ch
)
raise SyntaxError, 'unknown node type: %s' % tok
return CallFunc(primaryNode
, args
, star_node
, dstar_node
,
lineno
=extractLineNo(nodelist
))
def com_argument(self
, nodelist
, kw
):
if len(nodelist
) == 3 and nodelist
[2][0] == symbol
.gen_for
:
test
= self
.com_node(nodelist
[1])
return 0, self
.com_generator_expression(test
, nodelist
[2])
raise SyntaxError, "non-keyword arg after keyword arg"
return 0, self
.com_node(nodelist
[1])
result
= self
.com_node(nodelist
[3])
while len(n
) == 2 and n
[0] != token
.NAME
:
raise SyntaxError, "keyword can't be an expression (%s)"%n
[0]
node
= Keyword(n
[1], result
, lineno
=n
[2])
def com_subscriptlist(self
, primary
, nodelist
, assigning
):
# slicing: simple_slicing | extended_slicing
# simple_slicing: primary "[" short_slice "]"
# extended_slicing: primary "[" slice_list "]"
# slice_list: slice_item ("," slice_item)* [","]
# backwards compat slice for '[i:j]'
if (sub
[1][0] == token
.COLON
or \
(len(sub
) > 2 and sub
[2][0] == token
.COLON
)) and \
sub
[-1][0] != symbol
.sliceop
:
return self
.com_slice(primary
, sub
, assigning
)
for i
in range(1, len(nodelist
), 2):
subscripts
.append(self
.com_subscript(nodelist
[i
]))
return Subscript(primary
, assigning
, subscripts
,
lineno
=extractLineNo(nodelist
))
def com_subscript(self
, node
):
# slice_item: expression | proper_slice | ellipsis
if t
== token
.DOT
and node
[2][0] == token
.DOT
:
if t
== token
.COLON
or len(node
) > 2:
return self
.com_sliceobj(node
)
def com_sliceobj(self
, node
):
# proper_slice: short_slice | long_slice
# short_slice: [lower_bound] ":" [upper_bound]
# long_slice: short_slice ":" [stride]
# lower_bound: expression
# upper_bound: expression
# Note: a stride may be further slicing...
if node
[1][0] == token
.COLON
:
items
.append(Const(None))
items
.append(self
.com_node(node
[1]))
if i
< len(node
) and node
[i
][0] == symbol
.test
:
items
.append(self
.com_node(node
[i
]))
items
.append(Const(None))
# a short_slice has been built. look for long_slice now by looking
for j
in range(i
, len(node
)):
items
.append(Const(None))
items
.append(self
.com_node(ch
[2]))
return Sliceobj(items
, lineno
=extractLineNo(node
))
def com_slice(self
, primary
, node
, assigning
):
# short_slice: [lower_bound] ":" [upper_bound]
if node
[1][0] == token
.COLON
:
upper
= self
.com_node(node
[2])
lower
= self
.com_node(node
[1])
lower
= self
.com_node(node
[1])
upper
= self
.com_node(node
[3])
return Slice(primary
, assigning
, lower
, upper
,
lineno
=extractLineNo(node
))
def get_docstring(self
, node
, n
=None):
return self
.get_docstring(node
[0])
if sub
[0] == symbol
.stmt
:
return self
.get_docstring(sub
)
if n
== symbol
.file_input
:
if sub
[0] == symbol
.stmt
:
return self
.get_docstring(sub
)
if node
[0][0] == token
.STRING
:
if n
== symbol
.stmt
or n
== symbol
.simple_stmt \
or n
== symbol
.small_stmt
:
return self
.get_docstring(node
[0])
if n
in _doc_nodes
and len(node
) == 1:
return self
.get_docstring(node
[0])
# comp_op: '<' | '>' | '=' | '>=' | '<=' | '<>' | '!=' | '=='
# | 'in' | 'not' 'in' | 'is' | 'is' 'not'
token
.GREATEREQUAL
: '>=',
if hasattr(symbol
, 'yield_stmt'):
_legal_node_types
.append(symbol
.yield_stmt
)
for k
, v
in symbol
.sym_name
.items():
for k
, v
in token
.tok_name
.items():
if type(elt
) == types
.IntType
:
l
.append(_names
.get(elt
, elt
))
elif type(elt
) == types
.StringType
:
l
.append(debug_tree(elt
))