1 # Based on GardenSnake - a parser generator demonstration program
2 # GardenSnake was released into the Public Domain by Andrew Dalke.
4 # Portions of this work are derived from Python's Grammar definition
5 # and may be covered under the Python copyright and license
7 # Andrew Dalke / Dalke Scientific Software, LLC
8 # 30 August 2006 / Cape Town, South Africa
10 # Modifications for inclusion in PLY distribution
11 from pprint
import pprint
12 from ply
import lex
, yacc
14 from copy
import deepcopy
16 from openpower
.decoder
.power_decoder
import create_pdecode
17 from openpower
.decoder
.pseudo
.lexer
import IndentLexer
18 from openpower
.decoder
.orderedset
import OrderedSet
20 # I use the Python AST
21 #from compiler import ast
26 regs
= ['RA', 'RS', 'RB', 'RC', 'RT']
27 fregs
= ['FRA', 'FRS', 'FRB', 'FRC', 'FRT']
29 def Assign(autoassign
, assignname
, left
, right
, iea_mode
):
31 print("Assign", assignname
, left
, right
)
32 if isinstance(left
, ast
.Name
):
33 # Single assignment on left
34 # XXX when doing IntClass, which will have an "eq" function,
35 # this is how to access it
36 # eq = ast.Attribute(left, "eq") # get eq fn
37 # return ast.Call(eq, [right], []) # now call left.eq(right)
38 return ast
.Assign([ast
.Name(left
.id, ast
.Store())], right
)
39 elif isinstance(left
, ast
.Tuple
):
40 # List of things - make sure they are Name nodes
42 for child
in left
.getChildren():
43 if not isinstance(child
, ast
.Name
):
44 raise SyntaxError("that assignment not supported")
45 names
.append(child
.name
)
46 ass_list
= [ast
.AssName(name
, 'OP_ASSIGN') for name
in names
]
47 return ast
.Assign([ast
.AssTuple(ass_list
)], right
)
48 elif isinstance(left
, ast
.Subscript
):
50 # XXX changing meaning of "undefined" to a function
51 #if (isinstance(ls, ast.Slice) and isinstance(right, ast.Name) and
52 # right.id == 'undefined'):
53 # # undefined needs to be copied the exact same slice
54 # right = ast.Subscript(right, ls, ast.Load())
55 # return ast.Assign([left], right)
56 res
= ast
.Assign([left
], right
)
57 if autoassign
and isinstance(ls
, ast
.Slice
):
58 # hack to create a variable pre-declared based on a slice.
59 # dividend[0:32] = (RA)[0:32] will create
61 # dividend[0:32] = (RA)[0:32]
62 # the declaration makes the slice-assignment "work"
63 lower
, upper
, step
= ls
.lower
, ls
.upper
, ls
.step
64 print("lower, upper, step", repr(lower
), repr(upper
), step
)
65 if not isinstance(lower
, ast
.Constant
) or \
66 not isinstance(upper
, ast
.Constant
):
68 qty
= ast
.Num(upper
.value
-lower
.value
)
69 keywords
= [ast
.keyword(arg
='repeat', value
=qty
)]
71 right
= ast
.Call(ast
.Name("concat", ast
.Load()), l
, keywords
)
72 declare
= ast
.Assign([ast
.Name(assignname
, ast
.Store())], right
)
75 # XXX HMMM probably not needed...
77 if isinstance(ls
, ast
.Slice
):
78 lower
, upper
, step
= ls
.lower
, ls
.upper
, ls
.step
79 print("slice assign", lower
, upper
, step
)
81 ls
= (lower
, upper
, None)
83 ls
= (lower
, upper
, step
)
85 return ast
.Call(ast
.Name("selectassign", ast
.Load()),
86 [left
.value
, ls
, right
], [])
89 raise SyntaxError("Can't do that yet")
92 # I implemented INDENT / DEDENT generation as a post-processing filter
94 # The original lex token stream contains WS and NEWLINE characters.
95 # WS will only occur before any other tokens on a line.
97 # I have three filters. One tags tokens by adding two attributes.
98 # "must_indent" is True if the token must be indented from the
99 # previous code. The other is "at_line_start" which is True for WS
100 # and the first non-WS/non-NEWLINE on a line. It flags the check so
101 # see if the new line has changed indication level.
104 # No using Python's approach because Ply supports precedence
106 # comparison: expr (comp_op expr)*
107 # arith_expr: term (('+'|'-') term)*
108 # term: factor (('*'|'/'|'%'|'//') factor)*
109 # factor: ('+'|'-'|'~') factor | power
110 # comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
112 def make_le_compare(arg
):
114 return ast
.Call(ast
.Name("le", ast
.Load()), (left
, right
), [])
117 def make_ge_compare(arg
):
119 return ast
.Call(ast
.Name("ge", ast
.Load()), (left
, right
), [])
122 def make_lt_compare(arg
):
124 return ast
.Call(ast
.Name("lt", ast
.Load()), (left
, right
), [])
127 def make_gt_compare(arg
):
129 return ast
.Call(ast
.Name("gt", ast
.Load()), (left
, right
), [])
132 def make_eq_compare(arg
):
134 return ast
.Call(ast
.Name("eq", ast
.Load()), (left
, right
), [])
137 def make_ne_compare(arg
):
139 return ast
.Call(ast
.Name("ne", ast
.Load()), (left
, right
), [])
151 "<=": make_le_compare
,
152 ">=": make_ge_compare
,
153 "<": make_lt_compare
,
154 ">": make_gt_compare
,
155 "=": make_eq_compare
,
156 "!=": make_ne_compare
,
165 def check_concat(node
): # checks if the comparison is already a concat
166 print("check concat", node
)
167 if not isinstance(node
, ast
.Call
):
169 print("func", node
.func
.id)
170 if node
.func
.id != 'concat':
172 if node
.keywords
: # a repeated list-constant, don't optimise
177 # identify SelectableInt pattern [something] * N
178 # must return concat(something, repeat=N)
179 def identify_sint_mul_pattern(p
):
180 if p
[2] != '*': # multiply
182 if not isinstance(p
[3], ast
.Constant
): # rhs = Num
184 if not isinstance(p
[1], ast
.List
): # lhs is a list
187 if len(l
) != 1: # lhs is a list of length 1
189 return True # yippee!
192 def apply_trailer(atom
, trailer
):
193 if trailer
[0] == "TLIST":
194 # assume depth of one
195 atom
= apply_trailer(atom
, trailer
[1])
197 if trailer
[0] == "CALL":
198 #p[0] = ast.Expr(ast.Call(p[1], p[2][1], []))
199 return ast
.Call(atom
, trailer
[1], [])
200 # if p[1].id == 'print':
201 # p[0] = ast.Printnl(ast.Tuple(p[2][1]), None, None)
203 # p[0] = ast.CallFunc(p[1], p[2][1], None, None)
205 print("subscript atom", trailer
[1])
206 #raise AssertionError("not implemented %s" % p[2][0])
210 if isinstance(idx
, ast
.Name
) and idx
.id in regs
:
211 print ("single atom subscript, underscored", idx
.id)
212 idx
= ast
.Name("_%s" % idx
.id, ast
.Load())
214 idx
= ast
.Slice(subs
[0], subs
[1], None)
215 # if isinstance(atom, ast.Name) and atom.id == 'CR':
216 # atom.id = 'CR' # bad hack
217 #print ("apply_trailer Subscript", atom.id, idx)
218 return ast
.Subscript(atom
, idx
, ast
.Load())
220 ########## Parser (tokens -> AST) ######
225 # https://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_precedence.html
226 # python operator precedence
227 # Highest precedence at top, lowest at bottom.
228 # Operators in the same box evaluate left to right.
230 # Operator Description
231 # () Parentheses (grouping)
232 # f(args...) Function call
233 # x[index:index] Slicing
234 # x[index] Subscription
235 # x.attribute Attribute reference
238 # +x, -x Positive, negative
239 # *, /, % mul, div, remainder
240 # +, - Addition, subtraction
241 # <<, >> Bitwise shifts
245 # in, not in, is, is not, <, <=, >, >=, <>, !=, == comp, membership, ident
249 # lambda Lambda expression
255 ("left", "EQ", "NE", "GT", "LT", "LE", "GE", "LTU", "GTU"),
259 ("left", "PLUS", "MINUS"),
260 ("left", "MULT", "DIV", "MOD"),
264 def __init__(self
, form
, include_carry_in_write
=False):
265 self
.include_ca_in_write
= include_carry_in_write
267 form
= self
.sd
.sigforms
[form
]
269 formkeys
= form
._asdict
().keys()
270 self
.declared_vars
= set()
271 for rname
in regs
+ fregs
:
272 self
.gprs
[rname
] = None
273 self
.declared_vars
.add(rname
)
274 self
.available_op_fields
= set()
276 if k
not in self
.gprs
:
277 if k
== 'SPR': # sigh, lower-case to not conflict
279 self
.available_op_fields
.add(k
)
280 self
.op_fields
= OrderedSet()
281 self
.read_regs
= OrderedSet()
282 self
.uninit_regs
= OrderedSet()
283 self
.write_regs
= OrderedSet()
284 self
.special_regs
= OrderedSet() # see p_atom_name
286 # The grammar comments come from Python's Grammar/Grammar file
288 # NB: compound_stmt in single_input is followed by extra NEWLINE!
289 # file_input: (NEWLINE | stmt)* ENDMARKER
291 def p_file_input_end(self
, p
):
292 """file_input_end : file_input ENDMARKER"""
296 def p_file_input(self
, p
):
297 """file_input : file_input NEWLINE
301 if isinstance(p
[len(p
)-1], str):
305 p
[0] = [] # p == 2 --> only a blank line
312 # funcdef: [decorators] 'def' NAME parameters ':' suite
313 # ignoring decorators
315 def p_funcdef(self
, p
):
316 "funcdef : DEF NAME parameters COLON suite"
317 p
[0] = ast
.FunctionDef(p
[2], p
[3], p
[5], ())
319 # parameters: '(' [varargslist] ')'
320 def p_parameters(self
, p
):
321 """parameters : LPAR RPAR
322 | LPAR varargslist RPAR"""
327 p
[0] = ast
.arguments(args
=args
, vararg
=None, kwarg
=None, defaults
=[])
329 # varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] |
333 def p_varargslist(self
, p
):
334 """varargslist : varargslist COMMA NAME
341 # stmt: simple_stmt | compound_stmt
342 def p_stmt_simple(self
, p
):
343 """stmt : simple_stmt"""
344 # simple_stmt is a list
347 def p_stmt_compound(self
, p
):
348 """stmt : compound_stmt"""
351 # simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
352 def p_simple_stmt(self
, p
):
353 """simple_stmt : small_stmts NEWLINE
354 | small_stmts SEMICOLON NEWLINE"""
357 def p_small_stmts(self
, p
):
358 """small_stmts : small_stmts SEMICOLON small_stmt
362 elif isinstance(p
[1], list):
367 # small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
368 # import_stmt | global_stmt | exec_stmt | assert_stmt
369 def p_small_stmt(self
, p
):
370 """small_stmt : flow_stmt
373 if isinstance(p
[1], ast
.Call
):
374 p
[0] = ast
.Expr(p
[1])
375 elif isinstance(p
[1], ast
.Name
) and p
[1].id == 'TRAP':
376 # TRAP needs to actually be a function
377 name
= ast
.Name("self", ast
.Load())
378 name
= ast
.Attribute(name
, "TRAP", ast
.Load())
379 p
[0] = ast
.Call(name
, [], [])
383 # expr_stmt: testlist (augassign (yield_expr|testlist) |
384 # ('=' (yield_expr|testlist))*)
385 # augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
386 # '<<=' | '>>=' | '**=' | '//=')
387 def p_expr_stmt(self
, p
):
388 """expr_stmt : testlist ASSIGNEA testlist
389 | testlist ASSIGN testlist
391 print("expr_stmt", p
)
393 # a list of expressions
394 #p[0] = ast.Discard(p[1])
397 iea_mode
= p
[2] == '<-iea'
400 if isinstance(p
[1], ast
.Name
):
402 elif isinstance(p
[1], ast
.Subscript
):
403 if isinstance(p
[1].value
, ast
.Name
):
405 if name
in self
.gprs
:
406 # add to list of uninitialised
407 self
.uninit_regs
.add(name
)
408 autoassign
= (name
not in self
.declared_vars
and
409 name
not in self
.special_regs
)
410 elif isinstance(p
[1], ast
.Call
) and p
[1].func
.id in \
411 ['GPR', 'FPR', 'SPR']:
412 print(astor
.dump_tree(p
[1]))
413 # replace GPR(x) with GPR[x]
414 idx
= p
[1].args
[0].id
415 ridx
= ast
.Name("_%s" % idx
, ast
.Load())
416 p
[1] = ast
.Subscript(p
[1].func
, ridx
, ast
.Load())
417 self
.read_regs
.add(idx
) # add to list of regs to read
418 elif isinstance(p
[1], ast
.Call
) and p
[1].func
.id == 'MEM':
420 print(astor
.dump_tree(p
[1]))
421 p
[1].func
.id = "memassign" # change function name to set
422 p
[1].args
.append(p
[3])
425 print(astor
.dump_tree(p
[0]))
429 print(astor
.dump_tree(p
[1]))
430 print("expr assign", name
, p
[1])
431 if name
and name
in self
.gprs
:
432 self
.write_regs
.add(name
) # add to list of regs to write
433 p
[0] = Assign(autoassign
, name
, p
[1], p
[3], iea_mode
)
435 self
.declared_vars
.add(name
)
437 def p_flow_stmt(self
, p
):
438 "flow_stmt : return_stmt"
441 # return_stmt: 'return' [testlist]
442 def p_return_stmt(self
, p
):
443 "return_stmt : RETURN testlist"
444 p
[0] = ast
.Return(p
[2])
446 def p_compound_stmt(self
, p
):
447 """compound_stmt : if_stmt
455 def p_break_stmt(self
, p
):
456 """break_stmt : BREAK
460 def p_for_stmt(self
, p
):
461 """for_stmt : FOR atom EQ test TO test COLON suite
462 | DO atom EQ test TO test COLON suite
466 if start
.value
> end
.value
: # start greater than end, must go -ve
467 # auto-subtract-one (sigh) due to python range
468 end
= ast
.BinOp(p
[6], ast
.Add(), ast
.Constant(-1))
469 arange
= [start
, end
, ast
.Constant(-1)]
471 # auto-add-one (sigh) due to python range
472 end
= ast
.BinOp(p
[6], ast
.Add(), ast
.Constant(1))
473 arange
= [start
, end
]
474 it
= ast
.Call(ast
.Name("range", ast
.Load()), arange
, [])
475 p
[0] = ast
.For(p
[2], it
, p
[8], [])
477 def p_while_stmt(self
, p
):
478 """while_stmt : DO WHILE test COLON suite ELSE COLON suite
479 | DO WHILE test COLON suite
482 p
[0] = ast
.While(p
[3], p
[5], [])
484 p
[0] = ast
.While(p
[3], p
[5], p
[8])
486 def p_switch_smt(self
, p
):
487 """switch_stmt : SWITCH LPAR atom RPAR COLON NEWLINE INDENT switches DEDENT
491 print(astor
.dump_tree(p
[1]))
494 current_cases
= [] # for deferral
495 for (case
, suite
) in p
[8]:
496 print("for", case
, suite
)
499 current_cases
.append(ast
.Num(c
))
501 if case
== 'default': # last
504 current_cases
.append(ast
.Num(c
))
505 print("cases", current_cases
)
506 compare
= ast
.Compare(switchon
, [ast
.In()],
507 [ast
.List(current_cases
, ast
.Load())])
509 cases
.append((compare
, suite
))
511 print("ended", case
, current_cases
)
512 if case
== 'default':
514 compare
= ast
.Compare(switchon
, [ast
.In()],
515 [ast
.List(current_cases
, ast
.Load())])
516 cases
.append((compare
, suite
))
517 cases
.append((None, suite
))
521 for compare
, suite
in cases
:
522 print("after rev", compare
, suite
)
524 assert len(res
) == 0, "last case should be default"
527 if not isinstance(res
, list):
529 res
= ast
.If(compare
, suite
, res
)
532 def p_switches(self
, p
):
533 """switches : switch_list switch_default
541 def p_switch_list(self
, p
):
542 """switch_list : switch_case switch_list
550 def p_switch_case(self
, p
):
551 """switch_case : CASE LPAR atomlist RPAR COLON suite
554 if isinstance(p
[6][0], ast
.Name
) and p
[6][0].id == 'fallthrough':
558 def p_switch_default(self
, p
):
559 """switch_default : DEFAULT COLON suite
561 p
[0] = ('default', p
[3])
563 def p_atomlist(self
, p
):
564 """atomlist : atom COMMA atomlist
567 assert isinstance(p
[1], ast
.Constant
), "case must be numbers"
569 p
[0] = [p
[1].value
] + p
[3]
573 def p_if_stmt(self
, p
):
574 """if_stmt : IF test COLON suite ELSE COLON if_stmt
575 | IF test COLON suite ELSE COLON suite
576 | IF test COLON suite
578 if len(p
) == 8 and isinstance(p
[7], ast
.If
):
579 p
[0] = ast
.If(p
[2], p
[4], [p
[7]])
581 p
[0] = ast
.If(p
[2], p
[4], [])
583 p
[0] = ast
.If(p
[2], p
[4], p
[7])
585 def p_suite(self
, p
):
586 """suite : simple_stmt
587 | NEWLINE INDENT stmts DEDENT"""
593 def p_stmts(self
, p
):
594 """stmts : stmts stmt
601 def p_comparison(self
, p
):
602 """comparison : comparison PLUS comparison
603 | comparison MINUS comparison
604 | comparison MULT comparison
605 | comparison DIV comparison
606 | comparison MOD comparison
607 | comparison EQ comparison
608 | comparison NE comparison
609 | comparison LE comparison
610 | comparison GE comparison
611 | comparison LTU comparison
612 | comparison GTU comparison
613 | comparison LT comparison
614 | comparison GT comparison
615 | comparison BITOR comparison
616 | comparison BITXOR comparison
617 | comparison BITAND comparison
621 | comparison APPEND comparison
626 p
[0] = ast
.Call(ast
.Name("ltu", ast
.Load()), (p
[1], p
[3]), [])
628 p
[0] = ast
.Call(ast
.Name("gtu", ast
.Load()), (p
[1], p
[3]), [])
630 l
= check_concat(p
[1]) + check_concat(p
[3])
631 p
[0] = ast
.Call(ast
.Name("concat", ast
.Load()), l
, [])
632 elif p
[2] in ['/', '%']:
633 # bad hack: if % or / used anywhere other than div/mod ops,
634 # do % or /. however if the argument names are "dividend"
635 # we must call the special trunc_divs and trunc_rems functions
637 # actual call will be "dividend / divisor" - just check
639 # XXX DISABLE BAD HACK (False)
640 if False and isinstance(l
, ast
.Name
) and l
.id == 'dividend':
645 # return "function trunc_xxx(l, r)"
646 p
[0] = ast
.Call(ast
.Name(fn
, ast
.Load()), (l
, r
), [])
648 # return "l {binop} r"
649 p
[0] = ast
.BinOp(p
[1], binary_ops
[p
[2]], p
[3])
650 elif p
[2] in ['<', '>', '=', '<=', '>=', '!=']:
651 p
[0] = binary_ops
[p
[2]]((p
[1], p
[3]))
652 elif identify_sint_mul_pattern(p
):
653 keywords
= [ast
.keyword(arg
='repeat', value
=p
[3])]
655 p
[0] = ast
.Call(ast
.Name("concat", ast
.Load()), l
, keywords
)
657 p
[0] = ast
.BinOp(p
[1], binary_ops
[p
[2]], p
[3])
659 if isinstance(p
[2], str) and p
[2] == '-':
660 p
[0] = ast
.UnaryOp(unary_ops
[p
[2]], p
[1])
662 p
[0] = ast
.UnaryOp(unary_ops
[p
[1]], p
[2])
666 # power: atom trailer* ['**' factor]
667 # trailers enables function calls (and subscripts).
668 # so this is 'trailerlist'
669 def p_power(self
, p
):
671 | atom trailerlist"""
673 print("power dump atom notrailer")
674 print(astor
.dump_tree(p
[1]))
677 print("power dump atom")
678 print(astor
.dump_tree(p
[1]))
679 print("power dump trailerlist")
680 print(astor
.dump_tree(p
[2]))
681 p
[0] = apply_trailer(p
[1], p
[2])
682 if isinstance(p
[1], ast
.Name
):
684 if name
in regs
+ fregs
:
685 self
.read_regs
.add(name
)
687 def p_atom_name(self
, p
):
690 if name
in self
.available_op_fields
:
691 self
.op_fields
.add(name
)
692 if name
== 'overflow':
693 self
.write_regs
.add(name
)
694 if self
.include_ca_in_write
:
695 if name
in ['CA', 'CA32']:
696 self
.write_regs
.add(name
)
697 if name
in ['CR', 'LR', 'CTR', 'TAR', 'FPSCR', 'MSR', 'SVSTATE']:
698 self
.special_regs
.add(name
)
699 self
.write_regs
.add(name
) # and add to list to write
700 p
[0] = ast
.Name(id=name
, ctx
=ast
.Load())
702 def p_atom_number(self
, p
):
707 p
[0] = ast
.Constant(p
[1])
709 # '[' [listmaker] ']' |
711 def p_atom_listmaker(self
, p
):
712 """atom : LBRACK listmaker RBRACK"""
715 def p_listmaker(self
, p
):
716 """listmaker : test COMMA listmaker
720 p
[0] = ast
.List([p
[1]], ast
.Load())
722 p
[0] = ast
.List([p
[1]] + p
[3].nodes
, ast
.Load())
724 def p_atom_tuple(self
, p
):
725 """atom : LPAR testlist RPAR"""
728 print(astor
.dump_tree(p
[2]))
730 if isinstance(p
[2], ast
.Name
):
732 print("tuple name", name
)
733 if name
in self
.gprs
:
734 self
.read_regs
.add(name
) # add to list of regs to read
735 #p[0] = ast.Subscript(ast.Name("GPR", ast.Load()), ast.Str(p[2].id))
738 elif isinstance(p
[2], ast
.BinOp
):
739 if isinstance(p
[2].left
, ast
.Name
) and \
740 isinstance(p
[2].right
, ast
.Constant
) and \
741 p
[2].right
.value
== 0 and \
742 p
[2].left
.id in self
.gprs
:
744 self
.read_regs
.add(rid
) # add to list of regs to read
745 # create special call to GPR.getz or FPR.getz
747 gprz
= ast
.Name("FPR", ast
.Load())
749 gprz
= ast
.Name("GPR", ast
.Load())
750 # get testzero function
751 gprz
= ast
.Attribute(gprz
, "getz", ast
.Load())
752 # *sigh* see class GPR. we need index itself not reg value
753 ridx
= ast
.Name("_%s" % rid
, ast
.Load())
754 p
[0] = ast
.Call(gprz
, [ridx
], [])
755 print("tree", astor
.dump_tree(p
[0]))
761 def p_trailerlist(self
, p
):
762 """trailerlist : trailer trailerlist
768 p
[0] = ("TLIST", p
[1], p
[2])
770 # trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
771 def p_trailer(self
, p
):
772 """trailer : trailer_arglist
777 def p_trailer_arglist(self
, p
):
778 "trailer_arglist : LPAR arglist RPAR"
779 p
[0] = ("CALL", p
[2])
781 def p_trailer_subscript(self
, p
):
782 "trailer_subscript : LBRACK subscript RBRACK"
783 p
[0] = ("SUBS", p
[2])
785 # subscript: '.' '.' '.' | test | [test] ':' [test]
787 def p_subscript(self
, p
):
788 """subscript : test COLON test
793 if isinstance(p
[3], ast
.Constant
):
794 end
= ast
.Constant(p
[3].value
+1)
796 end
= ast
.BinOp(p
[3], ast
.Add(), ast
.Constant(1))
801 # testlist: test (',' test)* [',']
802 # Contains shift/reduce error
804 def p_testlist(self
, p
):
805 """testlist : testlist_multi COMMA
810 # May need to promote singleton to tuple
811 if isinstance(p
[1], list):
815 # Convert into a tuple?
816 if isinstance(p
[0], list):
817 p
[0] = ast
.Tuple(p
[0])
819 def p_testlist_multi(self
, p
):
820 """testlist_multi : testlist_multi COMMA test
826 if isinstance(p
[1], list):
832 # test: or_test ['if' or_test 'else' test] | lambdef
833 # as I don't support 'and', 'or', and 'not' this works down to 'comparison'
839 # arglist: (argument ',')* (argument [',']| '*' test [',' '**' test]
841 # XXX INCOMPLETE: this doesn't allow the trailing comma
843 def p_arglist(self
, p
):
844 """arglist : arglist COMMA argument
851 # argument: test [gen_for] | test '=' test # Really [keyword '='] test
852 def p_argument(self
, p
):
856 def p_error(self
, p
):
857 # print "Error!", repr(p)
861 class GardenSnakeParser(PowerParser
):
862 def __init__(self
, lexer
=None, debug
=False, form
=None, incl_carry
=False):
863 self
.sd
= create_pdecode()
864 PowerParser
.__init
__(self
, form
, incl_carry
)
867 lexer
= IndentLexer(debug
=0)
869 self
.tokens
= lexer
.tokens
870 self
.parser
= yacc
.yacc(module
=self
, start
="file_input_end",
871 debug
=debug
, write_tables
=False)
873 def parse(self
, code
):
874 # self.lexer.input(code)
875 result
= self
.parser
.parse(code
, lexer
=self
.lexer
, debug
=self
.debug
)
876 return ast
.Module(result
)
879 ###### Code generation ######
881 #from compiler import misc, syntax, pycodegen
884 _CACHE_PARSERS
= True
887 class GardenSnakeCompiler(object):
888 def __init__(self
, debug
=False, form
=None, incl_carry
=False):
891 parser
= _CACHED_PARSERS
[debug
, form
, incl_carry
]
893 parser
= GardenSnakeParser(debug
=debug
, form
=form
,
894 incl_carry
=incl_carry
)
895 _CACHED_PARSERS
[debug
, form
, incl_carry
] = parser
897 self
.parser
= deepcopy(parser
)
899 self
.parser
= GardenSnakeParser(debug
=debug
, form
=form
,
900 incl_carry
=incl_carry
)
902 def compile(self
, code
, mode
="exec", filename
="<string>"):
903 tree
= self
.parser
.parse(code
)
907 #misc.set_filename(filename, tree)
908 return compile(tree
, mode
="exec", filename
="<string>")
910 gen
= pycodegen
.ModuleCodeGenerator(tree
)