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