178caa9ca3494c41d7536969962c640c9c956440
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
15 from soc
.decoder
.power_decoder
import create_pdecode
16 from soc
.decoder
.pseudo
.lexer
import IndentLexer
17 from soc
.decoder
.orderedset
import OrderedSet
19 # I use the Python AST
20 #from compiler import ast
26 def Assign(autoassign
, assignname
, left
, right
, iea_mode
):
28 print("Assign", assignname
, left
, right
)
29 if isinstance(left
, ast
.Name
):
30 # Single assignment on left
31 # XXX when doing IntClass, which will have an "eq" function,
32 # this is how to access it
33 # eq = ast.Attribute(left, "eq") # get eq fn
34 # return ast.Call(eq, [right], []) # now call left.eq(right)
35 return ast
.Assign([ast
.Name(left
.id, ast
.Store())], right
)
36 elif isinstance(left
, ast
.Tuple
):
37 # List of things - make sure they are Name nodes
39 for child
in left
.getChildren():
40 if not isinstance(child
, ast
.Name
):
41 raise SyntaxError("that assignment not supported")
42 names
.append(child
.name
)
43 ass_list
= [ast
.AssName(name
, 'OP_ASSIGN') for name
in names
]
44 return ast
.Assign([ast
.AssTuple(ass_list
)], right
)
45 elif isinstance(left
, ast
.Subscript
):
47 if (isinstance(ls
, ast
.Slice
) and isinstance(right
, ast
.Name
) and
48 right
.id == 'undefined'):
49 # undefined needs to be copied the exact same slice
50 right
= ast
.Subscript(right
, ls
, ast
.Load())
51 return ast
.Assign([left
], right
)
52 res
= ast
.Assign([left
], right
)
53 if autoassign
and isinstance(ls
, ast
.Slice
):
54 # hack to create a variable pre-declared based on a slice.
55 # dividend[0:32] = (RA)[0:32] will create
57 # dividend[0:32] = (RA)[0:32]
58 # the declaration makes the slice-assignment "work"
59 lower
, upper
, step
= ls
.lower
, ls
.upper
, ls
.step
60 print("lower, upper, step", repr(lower
), repr(upper
), step
)
61 if not isinstance(lower
, ast
.Constant
) or \
62 not isinstance(upper
, ast
.Constant
):
64 qty
= ast
.Num(upper
.value
-lower
.value
)
65 keywords
= [ast
.keyword(arg
='repeat', value
=qty
)]
67 right
= ast
.Call(ast
.Name("concat", ast
.Load()), l
, keywords
)
68 declare
= ast
.Assign([ast
.Name(assignname
, ast
.Store())], right
)
71 # XXX HMMM probably not needed...
73 if isinstance(ls
, ast
.Slice
):
74 lower
, upper
, step
= ls
.lower
, ls
.upper
, ls
.step
75 print("slice assign", lower
, upper
, step
)
77 ls
= (lower
, upper
, None)
79 ls
= (lower
, upper
, step
)
81 return ast
.Call(ast
.Name("selectassign", ast
.Load()),
82 [left
.value
, ls
, right
], [])
85 raise SyntaxError("Can't do that yet")
88 # I implemented INDENT / DEDENT generation as a post-processing filter
90 # The original lex token stream contains WS and NEWLINE characters.
91 # WS will only occur before any other tokens on a line.
93 # I have three filters. One tags tokens by adding two attributes.
94 # "must_indent" is True if the token must be indented from the
95 # previous code. The other is "at_line_start" which is True for WS
96 # and the first non-WS/non-NEWLINE on a line. It flags the check so
97 # see if the new line has changed indication level.
100 # No using Python's approach because Ply supports precedence
102 # comparison: expr (comp_op expr)*
103 # arith_expr: term (('+'|'-') term)*
104 # term: factor (('*'|'/'|'%'|'//') factor)*
105 # factor: ('+'|'-'|'~') factor | power
106 # comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
108 def make_le_compare(arg
):
110 return ast
.Call(ast
.Name("le", ast
.Load()), (left
, right
), [])
113 def make_ge_compare(arg
):
115 return ast
.Call(ast
.Name("ge", ast
.Load()), (left
, right
), [])
118 def make_lt_compare(arg
):
120 return ast
.Call(ast
.Name("lt", ast
.Load()), (left
, right
), [])
123 def make_gt_compare(arg
):
125 return ast
.Call(ast
.Name("gt", ast
.Load()), (left
, right
), [])
128 def make_eq_compare(arg
):
130 return ast
.Call(ast
.Name("eq", ast
.Load()), (left
, right
), [])
133 def make_ne_compare(arg
):
135 return ast
.Call(ast
.Name("ne", ast
.Load()), (left
, right
), [])
147 "<=": make_le_compare
,
148 ">=": make_ge_compare
,
149 "<": make_lt_compare
,
150 ">": make_gt_compare
,
151 "=": make_eq_compare
,
152 "!=": make_ne_compare
,
161 def check_concat(node
): # checks if the comparison is already a concat
162 print("check concat", node
)
163 if not isinstance(node
, ast
.Call
):
165 print("func", node
.func
.id)
166 if node
.func
.id != 'concat':
168 if node
.keywords
: # a repeated list-constant, don't optimise
173 # identify SelectableInt pattern [something] * N
174 # must return concat(something, repeat=N)
175 def identify_sint_mul_pattern(p
):
176 if p
[2] != '*': # multiply
178 if not isinstance(p
[3], ast
.Constant
): # rhs = Num
180 if not isinstance(p
[1], ast
.List
): # lhs is a list
183 if len(l
) != 1: # lhs is a list of length 1
185 return True # yippee!
188 def apply_trailer(atom
, trailer
):
189 if trailer
[0] == "TLIST":
190 # assume depth of one
191 atom
= apply_trailer(atom
, trailer
[1])
193 if trailer
[0] == "CALL":
194 #p[0] = ast.Expr(ast.Call(p[1], p[2][1], []))
195 return ast
.Call(atom
, trailer
[1], [])
196 # if p[1].id == 'print':
197 # p[0] = ast.Printnl(ast.Tuple(p[2][1]), None, None)
199 # p[0] = ast.CallFunc(p[1], p[2][1], None, None)
201 print("subscript atom", trailer
[1])
202 #raise AssertionError("not implemented %s" % p[2][0])
207 idx
= ast
.Slice(subs
[0], subs
[1], None)
208 # if isinstance(atom, ast.Name) and atom.id == 'CR':
209 # atom.id = 'CR' # bad hack
210 #print ("apply_trailer Subscript", atom.id, idx)
211 return ast
.Subscript(atom
, idx
, ast
.Load())
213 ########## Parser (tokens -> AST) ######
218 # https://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_precedence.html
219 # python operator precedence
220 # Highest precedence at top, lowest at bottom.
221 # Operators in the same box evaluate left to right.
223 # Operator Description
224 # () Parentheses (grouping)
225 # f(args...) Function call
226 # x[index:index] Slicing
227 # x[index] Subscription
228 # x.attribute Attribute reference
231 # +x, -x Positive, negative
232 # *, /, % mul, div, remainder
233 # +, - Addition, subtraction
234 # <<, >> Bitwise shifts
238 # in, not in, is, is not, <, <=, >, >=, <>, !=, == comp, membership, ident
242 # lambda Lambda expression
248 ("left", "EQ", "NE", "GT", "LT", "LE", "GE", "LTU", "GTU"),
252 ("left", "PLUS", "MINUS"),
253 ("left", "MULT", "DIV", "MOD"),
257 def __init__(self
, form
, include_carry_in_write
=False):
258 self
.include_ca_in_write
= include_carry_in_write
260 form
= self
.sd
.sigforms
[form
]
262 formkeys
= form
._asdict
().keys()
263 self
.declared_vars
= set()
264 for rname
in ['RA', 'RB', 'RC', 'RT', 'RS']:
265 self
.gprs
[rname
] = None
266 self
.declared_vars
.add(rname
)
267 self
.available_op_fields
= set()
269 if k
not in self
.gprs
:
270 if k
== 'SPR': # sigh, lower-case to not conflict
272 self
.available_op_fields
.add(k
)
273 self
.op_fields
= OrderedSet()
274 self
.read_regs
= OrderedSet()
275 self
.uninit_regs
= OrderedSet()
276 self
.write_regs
= OrderedSet()
277 self
.special_regs
= OrderedSet() # see p_atom_name
279 # The grammar comments come from Python's Grammar/Grammar file
281 # NB: compound_stmt in single_input is followed by extra NEWLINE!
282 # file_input: (NEWLINE | stmt)* ENDMARKER
284 def p_file_input_end(self
, p
):
285 """file_input_end : file_input ENDMARKER"""
289 def p_file_input(self
, p
):
290 """file_input : file_input NEWLINE
294 if isinstance(p
[len(p
)-1], str):
298 p
[0] = [] # p == 2 --> only a blank line
305 # funcdef: [decorators] 'def' NAME parameters ':' suite
306 # ignoring decorators
308 def p_funcdef(self
, p
):
309 "funcdef : DEF NAME parameters COLON suite"
310 p
[0] = ast
.FunctionDef(p
[2], p
[3], p
[5], ())
312 # parameters: '(' [varargslist] ')'
313 def p_parameters(self
, p
):
314 """parameters : LPAR RPAR
315 | LPAR varargslist RPAR"""
320 p
[0] = ast
.arguments(args
=args
, vararg
=None, kwarg
=None, defaults
=[])
322 # varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] |
326 def p_varargslist(self
, p
):
327 """varargslist : varargslist COMMA NAME
334 # stmt: simple_stmt | compound_stmt
335 def p_stmt_simple(self
, p
):
336 """stmt : simple_stmt"""
337 # simple_stmt is a list
340 def p_stmt_compound(self
, p
):
341 """stmt : compound_stmt"""
344 # simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
345 def p_simple_stmt(self
, p
):
346 """simple_stmt : small_stmts NEWLINE
347 | small_stmts SEMICOLON NEWLINE"""
350 def p_small_stmts(self
, p
):
351 """small_stmts : small_stmts SEMICOLON small_stmt
355 elif isinstance(p
[1], list):
360 # small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
361 # import_stmt | global_stmt | exec_stmt | assert_stmt
362 def p_small_stmt(self
, p
):
363 """small_stmt : flow_stmt
366 if isinstance(p
[1], ast
.Call
):
367 p
[0] = ast
.Expr(p
[1])
368 elif isinstance(p
[1], ast
.Name
) and p
[1].id == 'TRAP':
369 # TRAP needs to actually be a function
370 name
= ast
.Name("self", ast
.Load())
371 name
= ast
.Attribute(name
, "TRAP", ast
.Load())
372 p
[0] = ast
.Call(name
, [], [])
376 # expr_stmt: testlist (augassign (yield_expr|testlist) |
377 # ('=' (yield_expr|testlist))*)
378 # augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
379 # '<<=' | '>>=' | '**=' | '//=')
380 def p_expr_stmt(self
, p
):
381 """expr_stmt : testlist ASSIGNEA testlist
382 | testlist ASSIGN testlist
384 print("expr_stmt", p
)
386 # a list of expressions
387 #p[0] = ast.Discard(p[1])
390 iea_mode
= p
[2] == '<-iea'
393 if isinstance(p
[1], ast
.Name
):
395 elif isinstance(p
[1], ast
.Subscript
):
396 if isinstance(p
[1].value
, ast
.Name
):
398 if name
in self
.gprs
:
399 # add to list of uninitialised
400 self
.uninit_regs
.add(name
)
401 autoassign
= (name
not in self
.declared_vars
and
402 name
not in self
.special_regs
)
403 elif isinstance(p
[1], ast
.Call
) and p
[1].func
.id in ['GPR', 'SPR']:
404 print(astor
.dump_tree(p
[1]))
405 # replace GPR(x) with GPR[x]
407 p
[1] = ast
.Subscript(p
[1].func
, idx
, ast
.Load())
408 elif isinstance(p
[1], ast
.Call
) and p
[1].func
.id == 'MEM':
410 print(astor
.dump_tree(p
[1]))
411 p
[1].func
.id = "memassign" # change function name to set
412 p
[1].args
.append(p
[3])
415 print(astor
.dump_tree(p
[0]))
419 print(astor
.dump_tree(p
[1]))
420 print("expr assign", name
, p
[1])
421 if name
and name
in self
.gprs
:
422 self
.write_regs
.add(name
) # add to list of regs to write
423 p
[0] = Assign(autoassign
, name
, p
[1], p
[3], iea_mode
)
425 self
.declared_vars
.add(name
)
427 def p_flow_stmt(self
, p
):
428 "flow_stmt : return_stmt"
431 # return_stmt: 'return' [testlist]
432 def p_return_stmt(self
, p
):
433 "return_stmt : RETURN testlist"
434 p
[0] = ast
.Return(p
[2])
436 def p_compound_stmt(self
, p
):
437 """compound_stmt : if_stmt
445 def p_break_stmt(self
, p
):
446 """break_stmt : BREAK
450 def p_for_stmt(self
, p
):
451 """for_stmt : FOR atom EQ test TO test COLON suite
452 | DO atom EQ test TO test COLON suite
456 if start
.value
> end
.value
: # start greater than end, must go -ve
457 # auto-subtract-one (sigh) due to python range
458 end
= ast
.BinOp(p
[6], ast
.Add(), ast
.Constant(-1))
459 arange
= [start
, end
, ast
.Constant(-1)]
461 # auto-add-one (sigh) due to python range
462 end
= ast
.BinOp(p
[6], ast
.Add(), ast
.Constant(1))
463 arange
= [start
, end
]
464 it
= ast
.Call(ast
.Name("range", ast
.Load()), arange
, [])
465 p
[0] = ast
.For(p
[2], it
, p
[8], [])
467 def p_while_stmt(self
, p
):
468 """while_stmt : DO WHILE test COLON suite ELSE COLON suite
469 | DO WHILE test COLON suite
472 p
[0] = ast
.While(p
[3], p
[5], [])
474 p
[0] = ast
.While(p
[3], p
[5], p
[8])
476 def p_switch_smt(self
, p
):
477 """switch_stmt : SWITCH LPAR atom RPAR COLON NEWLINE INDENT switches DEDENT
481 print(astor
.dump_tree(p
[1]))
484 current_cases
= [] # for deferral
485 for (case
, suite
) in p
[8]:
486 print("for", case
, suite
)
489 current_cases
.append(ast
.Num(c
))
491 if case
== 'default': # last
494 current_cases
.append(ast
.Num(c
))
495 print("cases", current_cases
)
496 compare
= ast
.Compare(switchon
, [ast
.In()],
497 [ast
.List(current_cases
, ast
.Load())])
499 cases
.append((compare
, suite
))
501 print("ended", case
, current_cases
)
502 if case
== 'default':
504 compare
= ast
.Compare(switchon
, [ast
.In()],
505 [ast
.List(current_cases
, ast
.Load())])
506 cases
.append((compare
, suite
))
507 cases
.append((None, suite
))
511 for compare
, suite
in cases
:
512 print("after rev", compare
, suite
)
514 assert len(res
) == 0, "last case should be default"
517 if not isinstance(res
, list):
519 res
= ast
.If(compare
, suite
, res
)
522 def p_switches(self
, p
):
523 """switches : switch_list switch_default
531 def p_switch_list(self
, p
):
532 """switch_list : switch_case switch_list
540 def p_switch_case(self
, p
):
541 """switch_case : CASE LPAR atomlist RPAR COLON suite
544 if isinstance(p
[6][0], ast
.Name
) and p
[6][0].id == 'fallthrough':
548 def p_switch_default(self
, p
):
549 """switch_default : DEFAULT COLON suite
551 p
[0] = ('default', p
[3])
553 def p_atomlist(self
, p
):
554 """atomlist : atom COMMA atomlist
557 assert isinstance(p
[1], ast
.Constant
), "case must be numbers"
559 p
[0] = [p
[1].value
] + p
[3]
563 def p_if_stmt(self
, p
):
564 """if_stmt : IF test COLON suite ELSE COLON if_stmt
565 | IF test COLON suite ELSE COLON suite
566 | IF test COLON suite
568 if len(p
) == 8 and isinstance(p
[7], ast
.If
):
569 p
[0] = ast
.If(p
[2], p
[4], [p
[7]])
571 p
[0] = ast
.If(p
[2], p
[4], [])
573 p
[0] = ast
.If(p
[2], p
[4], p
[7])
575 def p_suite(self
, p
):
576 """suite : simple_stmt
577 | NEWLINE INDENT stmts DEDENT"""
583 def p_stmts(self
, p
):
584 """stmts : stmts stmt
591 def p_comparison(self
, p
):
592 """comparison : comparison PLUS comparison
593 | comparison MINUS comparison
594 | comparison MULT comparison
595 | comparison DIV comparison
596 | comparison MOD comparison
597 | comparison EQ comparison
598 | comparison NE comparison
599 | comparison LE comparison
600 | comparison GE comparison
601 | comparison LTU comparison
602 | comparison GTU comparison
603 | comparison LT comparison
604 | comparison GT comparison
605 | comparison BITOR comparison
606 | comparison BITXOR comparison
607 | comparison BITAND comparison
611 | comparison APPEND comparison
616 p
[0] = ast
.Call(ast
.Name("ltu", ast
.Load()), (p
[1], p
[3]), [])
618 p
[0] = ast
.Call(ast
.Name("gtu", ast
.Load()), (p
[1], p
[3]), [])
620 l
= check_concat(p
[1]) + check_concat(p
[3])
621 p
[0] = ast
.Call(ast
.Name("concat", ast
.Load()), l
, [])
622 elif p
[2] in ['/', '%']:
623 # bad hack: if % or / used anywhere other than div/mod ops,
624 # do % or /. however if the argument names are "dividend"
625 # we must call the special trunc_divs and trunc_rems functions
627 # actual call will be "dividend / divisor" - just check
629 # XXX DISABLE BAD HACK (False)
630 if False and isinstance(l
, ast
.Name
) and l
.id == 'dividend':
635 # return "function trunc_xxx(l, r)"
636 p
[0] = ast
.Call(ast
.Name(fn
, ast
.Load()), (l
, r
), [])
638 # return "l {binop} r"
639 p
[0] = ast
.BinOp(p
[1], binary_ops
[p
[2]], p
[3])
640 elif p
[2] in ['<', '>', '=', '<=', '>=', '!=']:
641 p
[0] = binary_ops
[p
[2]]((p
[1], p
[3]))
642 elif identify_sint_mul_pattern(p
):
643 keywords
= [ast
.keyword(arg
='repeat', value
=p
[3])]
645 p
[0] = ast
.Call(ast
.Name("concat", ast
.Load()), l
, keywords
)
647 p
[0] = ast
.BinOp(p
[1], binary_ops
[p
[2]], p
[3])
649 if isinstance(p
[2], str) and p
[2] == '-':
650 p
[0] = ast
.UnaryOp(unary_ops
[p
[2]], p
[1])
652 p
[0] = ast
.UnaryOp(unary_ops
[p
[1]], p
[2])
656 # power: atom trailer* ['**' factor]
657 # trailers enables function calls (and subscripts).
658 # so this is 'trailerlist'
659 def p_power(self
, p
):
661 | atom trailerlist"""
665 print("power dump atom")
666 print(astor
.dump_tree(p
[1]))
667 print("power dump trailerlist")
668 print(astor
.dump_tree(p
[2]))
669 p
[0] = apply_trailer(p
[1], p
[2])
670 if isinstance(p
[1], ast
.Name
):
672 if name
in ['RA', 'RS', 'RB', 'RC']:
673 self
.read_regs
.add(name
)
675 def p_atom_name(self
, p
):
678 if name
in self
.available_op_fields
:
679 self
.op_fields
.add(name
)
680 if name
== 'overflow':
681 self
.write_regs
.add(name
)
682 if self
.include_ca_in_write
:
683 if name
in ['CA', 'CA32']:
684 self
.write_regs
.add(name
)
685 if name
in ['CR', 'LR', 'CTR', 'TAR', 'FPSCR', 'MSR']:
686 self
.special_regs
.add(name
)
687 self
.write_regs
.add(name
) # and add to list to write
688 p
[0] = ast
.Name(id=name
, ctx
=ast
.Load())
690 def p_atom_number(self
, p
):
695 p
[0] = ast
.Constant(p
[1])
697 # '[' [listmaker] ']' |
699 def p_atom_listmaker(self
, p
):
700 """atom : LBRACK listmaker RBRACK"""
703 def p_listmaker(self
, p
):
704 """listmaker : test COMMA listmaker
708 p
[0] = ast
.List([p
[1]], ast
.Load())
710 p
[0] = ast
.List([p
[1]] + p
[3].nodes
, ast
.Load())
712 def p_atom_tuple(self
, p
):
713 """atom : LPAR testlist RPAR"""
716 print(astor
.dump_tree(p
[2]))
718 if isinstance(p
[2], ast
.Name
):
720 print("tuple name", name
)
721 if name
in self
.gprs
:
722 self
.read_regs
.add(name
) # add to list of regs to read
723 #p[0] = ast.Subscript(ast.Name("GPR", ast.Load()), ast.Str(p[2].id))
726 elif isinstance(p
[2], ast
.BinOp
):
727 if isinstance(p
[2].left
, ast
.Name
) and \
728 isinstance(p
[2].right
, ast
.Constant
) and \
729 p
[2].right
.value
== 0 and \
730 p
[2].left
.id in self
.gprs
:
732 self
.read_regs
.add(rid
) # add to list of regs to read
733 # create special call to GPR.getz
734 gprz
= ast
.Name("GPR", ast
.Load())
735 # get testzero function
736 gprz
= ast
.Attribute(gprz
, "getz", ast
.Load())
737 # *sigh* see class GPR. we need index itself not reg value
738 ridx
= ast
.Name("_%s" % rid
, ast
.Load())
739 p
[0] = ast
.Call(gprz
, [ridx
], [])
740 print("tree", astor
.dump_tree(p
[0]))
746 def p_trailerlist(self
, p
):
747 """trailerlist : trailer trailerlist
753 p
[0] = ("TLIST", p
[1], p
[2])
755 # trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
756 def p_trailer(self
, p
):
757 """trailer : trailer_arglist
762 def p_trailer_arglist(self
, p
):
763 "trailer_arglist : LPAR arglist RPAR"
764 p
[0] = ("CALL", p
[2])
766 def p_trailer_subscript(self
, p
):
767 "trailer_subscript : LBRACK subscript RBRACK"
768 p
[0] = ("SUBS", p
[2])
770 # subscript: '.' '.' '.' | test | [test] ':' [test]
772 def p_subscript(self
, p
):
773 """subscript : test COLON test
778 if isinstance(p
[3], ast
.Constant
):
779 end
= ast
.Constant(p
[3].value
+1)
781 end
= ast
.BinOp(p
[3], ast
.Add(), ast
.Constant(1))
786 # testlist: test (',' test)* [',']
787 # Contains shift/reduce error
789 def p_testlist(self
, p
):
790 """testlist : testlist_multi COMMA
795 # May need to promote singleton to tuple
796 if isinstance(p
[1], list):
800 # Convert into a tuple?
801 if isinstance(p
[0], list):
802 p
[0] = ast
.Tuple(p
[0])
804 def p_testlist_multi(self
, p
):
805 """testlist_multi : testlist_multi COMMA test
811 if isinstance(p
[1], list):
817 # test: or_test ['if' or_test 'else' test] | lambdef
818 # as I don't support 'and', 'or', and 'not' this works down to 'comparison'
824 # arglist: (argument ',')* (argument [',']| '*' test [',' '**' test]
826 # XXX INCOMPLETE: this doesn't allow the trailing comma
828 def p_arglist(self
, p
):
829 """arglist : arglist COMMA argument
836 # argument: test [gen_for] | test '=' test # Really [keyword '='] test
837 def p_argument(self
, p
):
841 def p_error(self
, p
):
842 # print "Error!", repr(p)
846 class GardenSnakeParser(PowerParser
):
847 def __init__(self
, lexer
=None, debug
=False, form
=None, incl_carry
=False):
848 self
.sd
= create_pdecode()
849 PowerParser
.__init
__(self
, form
, incl_carry
)
852 lexer
= IndentLexer(debug
=0)
854 self
.tokens
= lexer
.tokens
855 self
.parser
= yacc
.yacc(module
=self
, start
="file_input_end",
856 debug
=debug
, write_tables
=False)
858 def parse(self
, code
):
859 # self.lexer.input(code)
860 result
= self
.parser
.parse(code
, lexer
=self
.lexer
, debug
=self
.debug
)
861 return ast
.Module(result
)
864 ###### Code generation ######
866 #from compiler import misc, syntax, pycodegen
868 class GardenSnakeCompiler(object):
869 def __init__(self
, debug
=False, form
=None, incl_carry
=False):
870 self
.parser
= GardenSnakeParser(debug
=debug
, form
=form
,
871 incl_carry
=incl_carry
)
873 def compile(self
, code
, mode
="exec", filename
="<string>"):
874 tree
= self
.parser
.parse(code
)
878 #misc.set_filename(filename, tree)
879 return compile(tree
, mode
="exec", filename
="<string>")
881 gen
= pycodegen
.ModuleCodeGenerator(tree
)