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])
211 idx
= ast
.Slice(subs
[0], subs
[1], None)
212 # if isinstance(atom, ast.Name) and atom.id == 'CR':
213 # atom.id = 'CR' # bad hack
214 #print ("apply_trailer Subscript", atom.id, idx)
215 return ast
.Subscript(atom
, idx
, ast
.Load())
217 ########## Parser (tokens -> AST) ######
222 # https://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_precedence.html
223 # python operator precedence
224 # Highest precedence at top, lowest at bottom.
225 # Operators in the same box evaluate left to right.
227 # Operator Description
228 # () Parentheses (grouping)
229 # f(args...) Function call
230 # x[index:index] Slicing
231 # x[index] Subscription
232 # x.attribute Attribute reference
235 # +x, -x Positive, negative
236 # *, /, % mul, div, remainder
237 # +, - Addition, subtraction
238 # <<, >> Bitwise shifts
242 # in, not in, is, is not, <, <=, >, >=, <>, !=, == comp, membership, ident
246 # lambda Lambda expression
252 ("left", "EQ", "NE", "GT", "LT", "LE", "GE", "LTU", "GTU"),
256 ("left", "PLUS", "MINUS"),
257 ("left", "MULT", "DIV", "MOD"),
261 def __init__(self
, form
, include_carry_in_write
=False):
262 self
.include_ca_in_write
= include_carry_in_write
264 form
= self
.sd
.sigforms
[form
]
266 formkeys
= form
._asdict
().keys()
267 self
.declared_vars
= set()
268 for rname
in regs
+ fregs
:
269 self
.gprs
[rname
] = None
270 self
.declared_vars
.add(rname
)
271 self
.available_op_fields
= set()
273 if k
not in self
.gprs
:
274 if k
== 'SPR': # sigh, lower-case to not conflict
276 self
.available_op_fields
.add(k
)
277 self
.op_fields
= OrderedSet()
278 self
.read_regs
= OrderedSet()
279 self
.uninit_regs
= OrderedSet()
280 self
.write_regs
= OrderedSet()
281 self
.special_regs
= OrderedSet() # see p_atom_name
283 # The grammar comments come from Python's Grammar/Grammar file
285 # NB: compound_stmt in single_input is followed by extra NEWLINE!
286 # file_input: (NEWLINE | stmt)* ENDMARKER
288 def p_file_input_end(self
, p
):
289 """file_input_end : file_input ENDMARKER"""
293 def p_file_input(self
, p
):
294 """file_input : file_input NEWLINE
298 if isinstance(p
[len(p
)-1], str):
302 p
[0] = [] # p == 2 --> only a blank line
309 # funcdef: [decorators] 'def' NAME parameters ':' suite
310 # ignoring decorators
312 def p_funcdef(self
, p
):
313 "funcdef : DEF NAME parameters COLON suite"
314 p
[0] = ast
.FunctionDef(p
[2], p
[3], p
[5], ())
316 # parameters: '(' [varargslist] ')'
317 def p_parameters(self
, p
):
318 """parameters : LPAR RPAR
319 | LPAR varargslist RPAR"""
324 p
[0] = ast
.arguments(args
=args
, vararg
=None, kwarg
=None, defaults
=[])
326 # varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] |
330 def p_varargslist(self
, p
):
331 """varargslist : varargslist COMMA NAME
338 # stmt: simple_stmt | compound_stmt
339 def p_stmt_simple(self
, p
):
340 """stmt : simple_stmt"""
341 # simple_stmt is a list
344 def p_stmt_compound(self
, p
):
345 """stmt : compound_stmt"""
348 # simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
349 def p_simple_stmt(self
, p
):
350 """simple_stmt : small_stmts NEWLINE
351 | small_stmts SEMICOLON NEWLINE"""
354 def p_small_stmts(self
, p
):
355 """small_stmts : small_stmts SEMICOLON small_stmt
359 elif isinstance(p
[1], list):
364 # small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
365 # import_stmt | global_stmt | exec_stmt | assert_stmt
366 def p_small_stmt(self
, p
):
367 """small_stmt : flow_stmt
370 if isinstance(p
[1], ast
.Call
):
371 p
[0] = ast
.Expr(p
[1])
372 elif isinstance(p
[1], ast
.Name
) and p
[1].id == 'TRAP':
373 # TRAP needs to actually be a function
374 name
= ast
.Name("self", ast
.Load())
375 name
= ast
.Attribute(name
, "TRAP", ast
.Load())
376 p
[0] = ast
.Call(name
, [], [])
380 # expr_stmt: testlist (augassign (yield_expr|testlist) |
381 # ('=' (yield_expr|testlist))*)
382 # augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
383 # '<<=' | '>>=' | '**=' | '//=')
384 def p_expr_stmt(self
, p
):
385 """expr_stmt : testlist ASSIGNEA testlist
386 | testlist ASSIGN testlist
388 print("expr_stmt", p
)
390 # a list of expressions
391 #p[0] = ast.Discard(p[1])
394 iea_mode
= p
[2] == '<-iea'
397 if isinstance(p
[1], ast
.Name
):
399 elif isinstance(p
[1], ast
.Subscript
):
400 if isinstance(p
[1].value
, ast
.Name
):
402 if name
in self
.gprs
:
403 # add to list of uninitialised
404 self
.uninit_regs
.add(name
)
405 autoassign
= (name
not in self
.declared_vars
and
406 name
not in self
.special_regs
)
407 elif isinstance(p
[1], ast
.Call
) and p
[1].func
.id in \
408 ['GPR', 'FPR', 'SPR']:
409 print(astor
.dump_tree(p
[1]))
410 # replace GPR(x) with GPR[x]
412 p
[1] = ast
.Subscript(p
[1].func
, idx
, ast
.Load())
413 elif isinstance(p
[1], ast
.Call
) and p
[1].func
.id == 'MEM':
415 print(astor
.dump_tree(p
[1]))
416 p
[1].func
.id = "memassign" # change function name to set
417 p
[1].args
.append(p
[3])
420 print(astor
.dump_tree(p
[0]))
424 print(astor
.dump_tree(p
[1]))
425 print("expr assign", name
, p
[1])
426 if name
and name
in self
.gprs
:
427 self
.write_regs
.add(name
) # add to list of regs to write
428 p
[0] = Assign(autoassign
, name
, p
[1], p
[3], iea_mode
)
430 self
.declared_vars
.add(name
)
432 def p_flow_stmt(self
, p
):
433 "flow_stmt : return_stmt"
436 # return_stmt: 'return' [testlist]
437 def p_return_stmt(self
, p
):
438 "return_stmt : RETURN testlist"
439 p
[0] = ast
.Return(p
[2])
441 def p_compound_stmt(self
, p
):
442 """compound_stmt : if_stmt
450 def p_break_stmt(self
, p
):
451 """break_stmt : BREAK
455 def p_for_stmt(self
, p
):
456 """for_stmt : FOR atom EQ test TO test COLON suite
457 | DO atom EQ test TO test COLON suite
461 if start
.value
> end
.value
: # start greater than end, must go -ve
462 # auto-subtract-one (sigh) due to python range
463 end
= ast
.BinOp(p
[6], ast
.Add(), ast
.Constant(-1))
464 arange
= [start
, end
, ast
.Constant(-1)]
466 # auto-add-one (sigh) due to python range
467 end
= ast
.BinOp(p
[6], ast
.Add(), ast
.Constant(1))
468 arange
= [start
, end
]
469 it
= ast
.Call(ast
.Name("range", ast
.Load()), arange
, [])
470 p
[0] = ast
.For(p
[2], it
, p
[8], [])
472 def p_while_stmt(self
, p
):
473 """while_stmt : DO WHILE test COLON suite ELSE COLON suite
474 | DO WHILE test COLON suite
477 p
[0] = ast
.While(p
[3], p
[5], [])
479 p
[0] = ast
.While(p
[3], p
[5], p
[8])
481 def p_switch_smt(self
, p
):
482 """switch_stmt : SWITCH LPAR atom RPAR COLON NEWLINE INDENT switches DEDENT
486 print(astor
.dump_tree(p
[1]))
489 current_cases
= [] # for deferral
490 for (case
, suite
) in p
[8]:
491 print("for", case
, suite
)
494 current_cases
.append(ast
.Num(c
))
496 if case
== 'default': # last
499 current_cases
.append(ast
.Num(c
))
500 print("cases", current_cases
)
501 compare
= ast
.Compare(switchon
, [ast
.In()],
502 [ast
.List(current_cases
, ast
.Load())])
504 cases
.append((compare
, suite
))
506 print("ended", case
, current_cases
)
507 if case
== 'default':
509 compare
= ast
.Compare(switchon
, [ast
.In()],
510 [ast
.List(current_cases
, ast
.Load())])
511 cases
.append((compare
, suite
))
512 cases
.append((None, suite
))
516 for compare
, suite
in cases
:
517 print("after rev", compare
, suite
)
519 assert len(res
) == 0, "last case should be default"
522 if not isinstance(res
, list):
524 res
= ast
.If(compare
, suite
, res
)
527 def p_switches(self
, p
):
528 """switches : switch_list switch_default
536 def p_switch_list(self
, p
):
537 """switch_list : switch_case switch_list
545 def p_switch_case(self
, p
):
546 """switch_case : CASE LPAR atomlist RPAR COLON suite
549 if isinstance(p
[6][0], ast
.Name
) and p
[6][0].id == 'fallthrough':
553 def p_switch_default(self
, p
):
554 """switch_default : DEFAULT COLON suite
556 p
[0] = ('default', p
[3])
558 def p_atomlist(self
, p
):
559 """atomlist : atom COMMA atomlist
562 assert isinstance(p
[1], ast
.Constant
), "case must be numbers"
564 p
[0] = [p
[1].value
] + p
[3]
568 def p_if_stmt(self
, p
):
569 """if_stmt : IF test COLON suite ELSE COLON if_stmt
570 | IF test COLON suite ELSE COLON suite
571 | IF test COLON suite
573 if len(p
) == 8 and isinstance(p
[7], ast
.If
):
574 p
[0] = ast
.If(p
[2], p
[4], [p
[7]])
576 p
[0] = ast
.If(p
[2], p
[4], [])
578 p
[0] = ast
.If(p
[2], p
[4], p
[7])
580 def p_suite(self
, p
):
581 """suite : simple_stmt
582 | NEWLINE INDENT stmts DEDENT"""
588 def p_stmts(self
, p
):
589 """stmts : stmts stmt
596 def p_comparison(self
, p
):
597 """comparison : comparison PLUS comparison
598 | comparison MINUS comparison
599 | comparison MULT comparison
600 | comparison DIV comparison
601 | comparison MOD comparison
602 | comparison EQ comparison
603 | comparison NE comparison
604 | comparison LE comparison
605 | comparison GE comparison
606 | comparison LTU comparison
607 | comparison GTU comparison
608 | comparison LT comparison
609 | comparison GT comparison
610 | comparison BITOR comparison
611 | comparison BITXOR comparison
612 | comparison BITAND comparison
616 | comparison APPEND comparison
621 p
[0] = ast
.Call(ast
.Name("ltu", ast
.Load()), (p
[1], p
[3]), [])
623 p
[0] = ast
.Call(ast
.Name("gtu", ast
.Load()), (p
[1], p
[3]), [])
625 l
= check_concat(p
[1]) + check_concat(p
[3])
626 p
[0] = ast
.Call(ast
.Name("concat", ast
.Load()), l
, [])
627 elif p
[2] in ['/', '%']:
628 # bad hack: if % or / used anywhere other than div/mod ops,
629 # do % or /. however if the argument names are "dividend"
630 # we must call the special trunc_divs and trunc_rems functions
632 # actual call will be "dividend / divisor" - just check
634 # XXX DISABLE BAD HACK (False)
635 if False and isinstance(l
, ast
.Name
) and l
.id == 'dividend':
640 # return "function trunc_xxx(l, r)"
641 p
[0] = ast
.Call(ast
.Name(fn
, ast
.Load()), (l
, r
), [])
643 # return "l {binop} r"
644 p
[0] = ast
.BinOp(p
[1], binary_ops
[p
[2]], p
[3])
645 elif p
[2] in ['<', '>', '=', '<=', '>=', '!=']:
646 p
[0] = binary_ops
[p
[2]]((p
[1], p
[3]))
647 elif identify_sint_mul_pattern(p
):
648 keywords
= [ast
.keyword(arg
='repeat', value
=p
[3])]
650 p
[0] = ast
.Call(ast
.Name("concat", ast
.Load()), l
, keywords
)
652 p
[0] = ast
.BinOp(p
[1], binary_ops
[p
[2]], p
[3])
654 if isinstance(p
[2], str) and p
[2] == '-':
655 p
[0] = ast
.UnaryOp(unary_ops
[p
[2]], p
[1])
657 p
[0] = ast
.UnaryOp(unary_ops
[p
[1]], p
[2])
661 # power: atom trailer* ['**' factor]
662 # trailers enables function calls (and subscripts).
663 # so this is 'trailerlist'
664 def p_power(self
, p
):
666 | atom trailerlist"""
668 print("power dump atom notrailer")
669 print(astor
.dump_tree(p
[1]))
672 print("power dump atom")
673 print(astor
.dump_tree(p
[1]))
674 print("power dump trailerlist")
675 print(astor
.dump_tree(p
[2]))
676 p
[0] = apply_trailer(p
[1], p
[2])
677 if isinstance(p
[1], ast
.Name
):
679 if name
in regs
+ fregs
:
680 self
.read_regs
.add(name
)
682 def p_atom_name(self
, p
):
685 if name
in self
.available_op_fields
:
686 self
.op_fields
.add(name
)
687 if name
== 'overflow':
688 self
.write_regs
.add(name
)
689 if self
.include_ca_in_write
:
690 if name
in ['CA', 'CA32']:
691 self
.write_regs
.add(name
)
692 if name
in ['CR', 'LR', 'CTR', 'TAR', 'FPSCR', 'MSR', 'SVSTATE']:
693 self
.special_regs
.add(name
)
694 self
.write_regs
.add(name
) # and add to list to write
695 p
[0] = ast
.Name(id=name
, ctx
=ast
.Load())
697 def p_atom_number(self
, p
):
702 p
[0] = ast
.Constant(p
[1])
704 # '[' [listmaker] ']' |
706 def p_atom_listmaker(self
, p
):
707 """atom : LBRACK listmaker RBRACK"""
710 def p_listmaker(self
, p
):
711 """listmaker : test COMMA listmaker
715 p
[0] = ast
.List([p
[1]], ast
.Load())
717 p
[0] = ast
.List([p
[1]] + p
[3].nodes
, ast
.Load())
719 def p_atom_tuple(self
, p
):
720 """atom : LPAR testlist RPAR"""
723 print(astor
.dump_tree(p
[2]))
725 if isinstance(p
[2], ast
.Name
):
727 print("tuple name", name
)
728 if name
in self
.gprs
:
729 self
.read_regs
.add(name
) # add to list of regs to read
730 #p[0] = ast.Subscript(ast.Name("GPR", ast.Load()), ast.Str(p[2].id))
733 elif isinstance(p
[2], ast
.BinOp
):
734 if isinstance(p
[2].left
, ast
.Name
) and \
735 isinstance(p
[2].right
, ast
.Constant
) and \
736 p
[2].right
.value
== 0 and \
737 p
[2].left
.id in self
.gprs
:
739 self
.read_regs
.add(rid
) # add to list of regs to read
740 # create special call to GPR.getz or FPR.getz
742 gprz
= ast
.Name("FPR", ast
.Load())
744 gprz
= ast
.Name("GPR", ast
.Load())
745 # get testzero function
746 gprz
= ast
.Attribute(gprz
, "getz", ast
.Load())
747 # *sigh* see class GPR. we need index itself not reg value
748 ridx
= ast
.Name("_%s" % rid
, ast
.Load())
749 p
[0] = ast
.Call(gprz
, [ridx
], [])
750 print("tree", astor
.dump_tree(p
[0]))
756 def p_trailerlist(self
, p
):
757 """trailerlist : trailer trailerlist
763 p
[0] = ("TLIST", p
[1], p
[2])
765 # trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
766 def p_trailer(self
, p
):
767 """trailer : trailer_arglist
772 def p_trailer_arglist(self
, p
):
773 "trailer_arglist : LPAR arglist RPAR"
774 p
[0] = ("CALL", p
[2])
776 def p_trailer_subscript(self
, p
):
777 "trailer_subscript : LBRACK subscript RBRACK"
778 p
[0] = ("SUBS", p
[2])
780 # subscript: '.' '.' '.' | test | [test] ':' [test]
782 def p_subscript(self
, p
):
783 """subscript : test COLON test
788 if isinstance(p
[3], ast
.Constant
):
789 end
= ast
.Constant(p
[3].value
+1)
791 end
= ast
.BinOp(p
[3], ast
.Add(), ast
.Constant(1))
796 # testlist: test (',' test)* [',']
797 # Contains shift/reduce error
799 def p_testlist(self
, p
):
800 """testlist : testlist_multi COMMA
805 # May need to promote singleton to tuple
806 if isinstance(p
[1], list):
810 # Convert into a tuple?
811 if isinstance(p
[0], list):
812 p
[0] = ast
.Tuple(p
[0])
814 def p_testlist_multi(self
, p
):
815 """testlist_multi : testlist_multi COMMA test
821 if isinstance(p
[1], list):
827 # test: or_test ['if' or_test 'else' test] | lambdef
828 # as I don't support 'and', 'or', and 'not' this works down to 'comparison'
834 # arglist: (argument ',')* (argument [',']| '*' test [',' '**' test]
836 # XXX INCOMPLETE: this doesn't allow the trailing comma
838 def p_arglist(self
, p
):
839 """arglist : arglist COMMA argument
846 # argument: test [gen_for] | test '=' test # Really [keyword '='] test
847 def p_argument(self
, p
):
851 def p_error(self
, p
):
852 # print "Error!", repr(p)
856 class GardenSnakeParser(PowerParser
):
857 def __init__(self
, lexer
=None, debug
=False, form
=None, incl_carry
=False):
858 self
.sd
= create_pdecode()
859 PowerParser
.__init
__(self
, form
, incl_carry
)
862 lexer
= IndentLexer(debug
=0)
864 self
.tokens
= lexer
.tokens
865 self
.parser
= yacc
.yacc(module
=self
, start
="file_input_end",
866 debug
=debug
, write_tables
=False)
868 def parse(self
, code
):
869 # self.lexer.input(code)
870 result
= self
.parser
.parse(code
, lexer
=self
.lexer
, debug
=self
.debug
)
871 return ast
.Module(result
)
874 ###### Code generation ######
876 #from compiler import misc, syntax, pycodegen
879 _CACHE_PARSERS
= True
882 class GardenSnakeCompiler(object):
883 def __init__(self
, debug
=False, form
=None, incl_carry
=False):
886 parser
= _CACHED_PARSERS
[debug
, form
, incl_carry
]
888 parser
= GardenSnakeParser(debug
=debug
, form
=form
,
889 incl_carry
=incl_carry
)
890 _CACHED_PARSERS
[debug
, form
, incl_carry
] = parser
892 self
.parser
= deepcopy(parser
)
894 self
.parser
= GardenSnakeParser(debug
=debug
, form
=form
,
895 incl_carry
=incl_carry
)
897 def compile(self
, code
, mode
="exec", filename
="<string>"):
898 tree
= self
.parser
.parse(code
)
902 #misc.set_filename(filename, tree)
903 return compile(tree
, mode
="exec", filename
="<string>")
905 gen
= pycodegen
.ModuleCodeGenerator(tree
)