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', 'FRS']
55 def Assign(autoassign
, assignname
, left
, right
, iea_mode
):
57 print("Assign", autoassign
, assignname
, left
, right
)
58 if isinstance(left
, ast
.Name
):
59 # Single assignment on left
60 # XXX when doing IntClass, which will have an "eq" function,
61 # this is how to access it
62 # eq = ast.Attribute(left, "eq") # get eq fn
63 # return ast.Call(eq, [right], []) # now call left.eq(right)
64 return ast
.Assign([ast
.Name(left
.id, ast
.Store())], right
)
65 elif isinstance(left
, ast
.Tuple
):
66 # List of things - make sure they are Name nodes
68 for child
in left
.getChildren():
69 if not isinstance(child
, ast
.Name
):
70 raise SyntaxError("that assignment not supported")
71 names
.append(child
.name
)
72 ass_list
= [ast
.AssName(name
, 'OP_ASSIGN') for name
in names
]
73 return ast
.Assign([ast
.AssTuple(ass_list
)], right
)
74 elif isinstance(left
, ast
.Subscript
):
76 # XXX changing meaning of "undefined" to a function
77 #if (isinstance(ls, ast.Slice) and isinstance(right, ast.Name) and
78 # right.id == 'undefined'):
79 # # undefined needs to be copied the exact same slice
80 # right = ast.Subscript(right, ls, ast.Load())
81 # return ast.Assign([left], right)
82 res
= ast
.Assign([left
], right
)
83 if autoassign
and isinstance(ls
, ast
.Slice
):
84 # hack to create a variable pre-declared based on a slice.
85 # dividend[0:32] = (RA)[0:32] will create
87 # dividend[0:32] = (RA)[0:32]
88 # the declaration makes the slice-assignment "work"
89 lower
, upper
, step
= ls
.lower
, ls
.upper
, ls
.step
90 print("lower, upper, step", repr(lower
), repr(upper
), step
)
91 # XXX relax constraint that indices on auto-assign have
92 # to be constants x[0:32]
93 #if not isinstance(lower, ast.Constant) or \
94 # not isinstance(upper, ast.Constant):
96 qty
= ast
.BinOp(upper
, binary_ops
['-'], lower
)
97 keywords
= [ast
.keyword(arg
='repeat', value
=qty
)]
99 right
= ast
.Call(ast
.Name("concat", ast
.Load()), l
, keywords
)
100 declare
= ast
.Assign([ast
.Name(assignname
, ast
.Store())], right
)
101 return [declare
, res
]
103 # XXX HMMM probably not needed...
105 if isinstance(ls
, ast
.Slice
):
106 lower
, upper
, step
= ls
.lower
, ls
.upper
, ls
.step
107 print("slice assign", lower
, upper
, step
)
109 ls
= (lower
, upper
, None)
111 ls
= (lower
, upper
, step
)
113 return ast
.Call(ast
.Name("selectassign", ast
.Load()),
114 [left
.value
, ls
, right
], [])
117 raise SyntaxError("Can't do that yet")
120 # I implemented INDENT / DEDENT generation as a post-processing filter
122 # The original lex token stream contains WS and NEWLINE characters.
123 # WS will only occur before any other tokens on a line.
125 # I have three filters. One tags tokens by adding two attributes.
126 # "must_indent" is True if the token must be indented from the
127 # previous code. The other is "at_line_start" which is True for WS
128 # and the first non-WS/non-NEWLINE on a line. It flags the check so
129 # see if the new line has changed indication level.
132 # No using Python's approach because Ply supports precedence
134 # comparison: expr (comp_op expr)*
135 # arith_expr: term (('+'|'-') term)*
136 # term: factor (('*'|'/'|'%'|'//') factor)*
137 # factor: ('+'|'-'|'~') factor | power
138 # comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
140 def make_le_compare(arg
):
142 return ast
.Call(ast
.Name("le", ast
.Load()), (left
, right
), [])
145 def make_ge_compare(arg
):
147 return ast
.Call(ast
.Name("ge", ast
.Load()), (left
, right
), [])
150 def make_lt_compare(arg
):
152 return ast
.Call(ast
.Name("lt", ast
.Load()), (left
, right
), [])
155 def make_gt_compare(arg
):
157 return ast
.Call(ast
.Name("gt", ast
.Load()), (left
, right
), [])
160 def make_eq_compare(arg
):
162 return ast
.Call(ast
.Name("eq", ast
.Load()), (left
, right
), [])
165 def make_ne_compare(arg
):
167 return ast
.Call(ast
.Name("ne", ast
.Load()), (left
, right
), [])
179 "<=": make_le_compare
,
180 ">=": make_ge_compare
,
181 "<": make_lt_compare
,
182 ">": make_gt_compare
,
183 "=": make_eq_compare
,
184 "!=": make_ne_compare
,
193 def check_concat(node
): # checks if the comparison is already a concat
194 print("check concat", node
)
195 if not isinstance(node
, ast
.Call
):
197 print("func", node
.func
.id)
198 if node
.func
.id != 'concat':
200 if node
.keywords
: # a repeated list-constant, don't optimise
205 # identify SelectableInt pattern [something] * N
206 # must return concat(something, repeat=N)
207 # here is a TEMPORARY hack to support minimal expressions
208 # such as (XLEN-16), looking for ast.BinOp
209 # have to keep an eye on this
210 def identify_sint_mul_pattern(p
):
211 """here we are looking for patterns of this type:
213 these must specifically be returned as concat(item, repeat=something)
215 #print ("identify_sint_mul_pattern")
217 # print(" ", astor.dump_tree(pat))
218 if p
[2] != '*': # multiply
220 if (not isinstance(p
[3], ast
.Constant
) and # rhs = Num
221 not isinstance(p
[3], ast
.BinOp
) and # rhs = (XLEN-something)
222 not isinstance(p
[3], ast
.Name
)): # rhs = XLEN
224 if not isinstance(p
[1], ast
.List
): # lhs is a list
227 if len(l
) != 1: # lhs is a list of length 1
229 return True # yippee!
232 def apply_trailer(atom
, trailer
, read_regs
):
233 if trailer
[0] == "TLIST":
234 # assume depth of one
235 atom
= apply_trailer(atom
, trailer
[1], read_regs
)
237 if trailer
[0] == "CALL":
238 #p[0] = ast.Expr(ast.Call(p[1], p[2][1], []))
239 for arg
in trailer
[1]:
240 if isinstance(arg
, ast
.Name
):
242 if name
in regs
+ fregs
:
244 # special-case, these functions must be made "self.xxxx"
245 if atom
.id in HELPERS
:
246 name
= ast
.Name("self", ast
.Load())
247 atom
= ast
.Attribute(name
, atom
, ast
.Load())
248 return ast
.Call(atom
, trailer
[1], [])
249 # if p[1].id == 'print':
250 # p[0] = ast.Printnl(ast.Tuple(p[2][1]), None, None)
252 # p[0] = ast.CallFunc(p[1], p[2][1], None, None)
254 print("subscript atom", trailer
[1])
255 #raise AssertionError("not implemented %s" % p[2][0])
259 if isinstance(idx
, ast
.Name
) and idx
.id in regs
+ fregs
:
260 read_regs
.add(idx
.id)
261 if isinstance(idx
, ast
.Name
) and idx
.id in regs
:
262 print ("single atom subscript, underscored", idx
.id)
263 idx
= ast
.Name("_%s" % idx
.id, ast
.Load())
265 idx
= ast
.Slice(subs
[0], subs
[1], None)
266 # if isinstance(atom, ast.Name) and atom.id == 'CR':
267 # atom.id = 'CR' # bad hack
268 #print ("apply_trailer Subscript", atom.id, idx)
269 return ast
.Subscript(atom
, idx
, ast
.Load())
271 ########## Parser (tokens -> AST) ######
276 # https://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_precedence.html
277 # python operator precedence
278 # Highest precedence at top, lowest at bottom.
279 # Operators in the same box evaluate left to right.
281 # Operator Description
282 # () Parentheses (grouping)
283 # f(args...) Function call
284 # x[index:index] Slicing
285 # x[index] Subscription
286 # x.attribute Attribute reference
289 # +x, -x Positive, negative
290 # *, /, % mul, div, remainder
291 # +, - Addition, subtraction
292 # <<, >> Bitwise shifts
296 # in, not in, is, is not, <, <=, >, >=, <>, !=, == comp, membership, ident
300 # lambda Lambda expression
306 ("left", "EQ", "NE", "GT", "LT", "LE", "GE", "LTU", "GTU"),
310 ("left", "PLUS", "MINUS"),
311 ("left", "MULT", "DIV", "MOD"),
315 def __init__(self
, form
, include_carry_in_write
=False):
316 self
.include_ca_in_write
= include_carry_in_write
319 form
= self
.sd
.sigforms
[form
]
321 formkeys
= form
._asdict
().keys()
324 self
.declared_vars
= set()
325 self
.fnparm_vars
= set()
326 for rname
in regs
+ fregs
:
327 self
.gprs
[rname
] = None
328 self
.declared_vars
.add(rname
)
329 self
.available_op_fields
= set()
331 if k
not in self
.gprs
:
332 if k
== 'SPR': # sigh, lower-case to not conflict
334 self
.available_op_fields
.add(k
)
335 self
.op_fields
= OrderedSet()
336 self
.read_regs
= OrderedSet()
337 self
.uninit_regs
= OrderedSet()
338 self
.write_regs
= OrderedSet()
339 self
.special_regs
= OrderedSet() # see p_atom_name
341 # The grammar comments come from Python's Grammar/Grammar file
343 # NB: compound_stmt in single_input is followed by extra NEWLINE!
344 # file_input: (NEWLINE | stmt)* ENDMARKER
346 def p_file_input_end(self
, p
):
347 """file_input_end : file_input ENDMARKER"""
351 def p_file_input(self
, p
):
352 """file_input : file_input NEWLINE
356 if isinstance(p
[len(p
)-1], str):
360 p
[0] = [] # p == 2 --> only a blank line
367 # funcdef: [decorators] 'def' NAME parameters ':' suite
368 # ignoring decorators
370 def p_funcdef(self
, p
):
371 "funcdef : DEF NAME parameters COLON suite"
372 p
[0] = ast
.FunctionDef(p
[2], p
[3], p
[5], ())
373 # reset function parameters after suite is identified
374 self
.fnparm_vars
= set()
376 # parameters: '(' [varargslist] ')'
377 def p_parameters(self
, p
):
378 """parameters : LPAR RPAR
379 | LPAR varargslist RPAR"""
384 p
[0] = ast
.arguments(args
=args
, vararg
=None, kwarg
=None, defaults
=[])
385 # during the time between parameters identified and suite is not
386 # there is a window of opportunity to declare the function parameters
387 # in-scope, for use to not overwrite them with auto-assign
388 self
.fnparm_vars
= set()
390 print ("adding fn parm", arg
)
391 self
.fnparm_vars
.add(arg
)
393 # varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] |
397 def p_varargslist(self
, p
):
398 """varargslist : varargslist COMMA NAME
406 # stmt: simple_stmt | compound_stmt
407 def p_stmt_simple(self
, p
):
408 """stmt : simple_stmt"""
409 # simple_stmt is a list
412 def p_stmt_compound(self
, p
):
413 """stmt : compound_stmt"""
416 # simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
417 def p_simple_stmt(self
, p
):
418 """simple_stmt : small_stmts NEWLINE
419 | small_stmts SEMICOLON NEWLINE"""
422 def p_small_stmts(self
, p
):
423 """small_stmts : small_stmts SEMICOLON small_stmt
427 elif isinstance(p
[1], list):
432 # small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
433 # import_stmt | global_stmt | exec_stmt | assert_stmt
434 def p_small_stmt(self
, p
):
435 """small_stmt : flow_stmt
438 if isinstance(p
[1], ast
.Call
):
439 p
[0] = ast
.Expr(p
[1])
440 elif isinstance(p
[1], ast
.Name
) and p
[1].id in HELPERS
:
442 name
= ast
.Name("self", ast
.Load())
443 name
= ast
.Attribute(name
, fname
, ast
.Load())
444 p
[0] = ast
.Call(name
, [], [])
448 # expr_stmt: testlist (augassign (yield_expr|testlist) |
449 # ('=' (yield_expr|testlist))*)
450 # augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
451 # '<<=' | '>>=' | '**=' | '//=')
452 def p_expr_stmt(self
, p
):
453 """expr_stmt : testlist ASSIGNEA testlist
454 | testlist ASSIGN testlist
456 print("expr_stmt", p
)
458 # a list of expressions
459 #p[0] = ast.Discard(p[1])
462 iea_mode
= p
[2] == '<-iea'
465 if isinstance(p
[1], ast
.Name
):
467 elif isinstance(p
[1], ast
.Subscript
):
468 print ("assign subscript", p
[1].value
,
472 print(astor
.dump_tree(p
[1]))
473 if isinstance(p
[1].value
, ast
.Name
):
475 print ("assign subscript value to name", name
)
476 if name
in self
.gprs
:
477 # add to list of uninitialised
478 self
.uninit_regs
.add(name
)
479 # work out if this is an ininitialised variable
480 # that should be auto-assigned simply by being "sliced"
481 autoassign
= (name
not in self
.declared_vars
and
482 name
not in self
.fnparm_vars
and
483 name
not in self
.special_regs
)
484 elif isinstance(p
[1], ast
.Call
) and p
[1].func
.id in \
485 ['GPR', 'FPR', 'SPR']:
486 print(astor
.dump_tree(p
[1]))
487 # replace GPR(x) with GPR[x]
488 idx
= p
[1].args
[0].id
489 if idx
in regs
+ fregs
:
490 ridx
= ast
.Name("_%s" % idx
, ast
.Load())
492 ridx
= ast
.Name(idx
, ast
.Load())
493 p
[1] = ast
.Subscript(p
[1].func
, ridx
, ast
.Load())
495 self
.read_regs
.add(idx
) # add to list of regs to read
496 elif isinstance(p
[1], ast
.Call
) and p
[1].func
.id == 'MEM':
498 print(astor
.dump_tree(p
[1]))
499 p
[1].func
.id = "memassign" # change function name to set
500 p
[1].args
.append(p
[3])
503 print(astor
.dump_tree(p
[0]))
507 print(astor
.dump_tree(p
[1]))
508 print("expr assign", name
, p
[1], "to", p
[3])
509 if isinstance(p
[3], ast
.Name
):
511 if toname
in self
.gprs
:
512 self
.read_regs
.add(toname
)
513 if name
and name
in self
.gprs
:
514 self
.write_regs
.add(name
) # add to list of regs to write
515 p
[0] = Assign(autoassign
, name
, p
[1], p
[3], iea_mode
)
517 self
.declared_vars
.add(name
)
519 def p_flow_stmt(self
, p
):
520 "flow_stmt : return_stmt"
523 # return_stmt: 'return' [testlist]
524 def p_return_stmt(self
, p
):
525 "return_stmt : RETURN testlist"
526 p
[0] = ast
.Return(p
[2])
528 def p_compound_stmt(self
, p
):
529 """compound_stmt : if_stmt
537 def p_break_stmt(self
, p
):
538 """break_stmt : BREAK
542 def p_for_stmt(self
, p
):
543 """for_stmt : FOR atom EQ comparison TO comparison COLON suite
544 | DO atom EQ comparison TO comparison COLON suite
548 it
= ast
.Call(ast
.Name("RANGE", ast
.Load()), (start
, end
), [])
549 p
[0] = ast
.For(p
[2], it
, p
[8], [])
551 def p_while_stmt(self
, p
):
552 """while_stmt : DO WHILE test COLON suite ELSE COLON suite
553 | DO WHILE test COLON suite
556 p
[0] = ast
.While(p
[3], p
[5], [])
558 p
[0] = ast
.While(p
[3], p
[5], p
[8])
560 def p_switch_smt(self
, p
):
561 """switch_stmt : SWITCH LPAR atom RPAR COLON NEWLINE INDENT switches DEDENT
565 print(astor
.dump_tree(p
[1]))
568 current_cases
= [] # for deferral
569 for (case
, suite
) in p
[8]:
570 print("for", case
, suite
)
573 current_cases
.append(ast
.Num(c
))
575 if case
== 'default': # last
578 current_cases
.append(ast
.Num(c
))
579 print("cases", current_cases
)
580 compare
= ast
.Compare(switchon
, [ast
.In()],
581 [ast
.List(current_cases
, ast
.Load())])
583 cases
.append((compare
, suite
))
585 print("ended", case
, current_cases
)
586 if case
== 'default':
588 compare
= ast
.Compare(switchon
, [ast
.In()],
589 [ast
.List(current_cases
, ast
.Load())])
590 cases
.append((compare
, suite
))
591 cases
.append((None, suite
))
595 for compare
, suite
in cases
:
596 print("after rev", compare
, suite
)
598 assert len(res
) == 0, "last case should be default"
601 if not isinstance(res
, list):
603 res
= ast
.If(compare
, suite
, res
)
606 def p_switches(self
, p
):
607 """switches : switch_list switch_default
615 def p_switch_list(self
, p
):
616 """switch_list : switch_case switch_list
624 def p_switch_case(self
, p
):
625 """switch_case : CASE LPAR atomlist RPAR COLON suite
628 if isinstance(p
[6][0], ast
.Name
) and p
[6][0].id == 'fallthrough':
632 def p_switch_default(self
, p
):
633 """switch_default : DEFAULT COLON suite
635 p
[0] = ('default', p
[3])
637 def p_atomlist(self
, p
):
638 """atomlist : atom COMMA atomlist
641 assert isinstance(p
[1], ast
.Constant
), "case must be numbers"
643 p
[0] = [p
[1].value
] + p
[3]
647 def p_if_stmt(self
, p
):
648 """if_stmt : IF test COLON suite ELSE COLON if_stmt
649 | IF test COLON suite ELSE COLON suite
650 | IF test COLON suite
652 if len(p
) == 8 and isinstance(p
[7], ast
.If
):
653 p
[0] = ast
.If(p
[2], p
[4], [p
[7]])
655 p
[0] = ast
.If(p
[2], p
[4], [])
657 p
[0] = ast
.If(p
[2], p
[4], p
[7])
659 def p_suite(self
, p
):
660 """suite : simple_stmt
661 | NEWLINE INDENT stmts DEDENT"""
667 def p_stmts(self
, p
):
668 """stmts : stmts stmt
675 def p_comparison(self
, p
):
676 """comparison : comparison PLUS comparison
677 | comparison MINUS comparison
678 | comparison MULT comparison
679 | comparison DIV comparison
680 | comparison MOD comparison
681 | comparison EQ comparison
682 | comparison NE comparison
683 | comparison LE comparison
684 | comparison GE comparison
685 | comparison LTU comparison
686 | comparison GTU comparison
687 | comparison LT comparison
688 | comparison GT comparison
689 | comparison BITOR comparison
690 | comparison BITXOR comparison
691 | comparison BITAND comparison
695 | comparison APPEND comparison
700 p
[0] = ast
.Call(ast
.Name("ltu", ast
.Load()), (p
[1], p
[3]), [])
702 p
[0] = ast
.Call(ast
.Name("gtu", ast
.Load()), (p
[1], p
[3]), [])
704 l
= check_concat(p
[1]) + check_concat(p
[3])
705 p
[0] = ast
.Call(ast
.Name("concat", ast
.Load()), l
, [])
706 elif p
[2] in ['/', '%']:
707 # bad hack: if % or / used anywhere other than div/mod ops,
708 # do % or /. however if the argument names are "dividend"
709 # we must call the special trunc_divs and trunc_rems functions
711 # actual call will be "dividend / divisor" - just check
713 # XXX DISABLE BAD HACK (False)
714 if False and isinstance(l
, ast
.Name
) and l
.id == 'dividend':
719 # return "function trunc_xxx(l, r)"
720 p
[0] = ast
.Call(ast
.Name(fn
, ast
.Load()), (l
, r
), [])
722 # return "l {binop} r"
723 p
[0] = ast
.BinOp(p
[1], binary_ops
[p
[2]], p
[3])
724 elif p
[2] in ['<', '>', '=', '<=', '>=', '!=']:
725 p
[0] = binary_ops
[p
[2]]((p
[1], p
[3]))
726 elif identify_sint_mul_pattern(p
):
727 keywords
= [ast
.keyword(arg
='repeat', value
=p
[3])]
729 p
[0] = ast
.Call(ast
.Name("concat", ast
.Load()), l
, keywords
)
731 p
[0] = ast
.BinOp(p
[1], binary_ops
[p
[2]], p
[3])
733 if isinstance(p
[2], str) and p
[2] == '-':
734 p
[0] = ast
.UnaryOp(unary_ops
[p
[2]], p
[1])
736 p
[0] = ast
.UnaryOp(unary_ops
[p
[1]], p
[2])
740 # power: atom trailer* ['**' factor]
741 # trailers enables function calls (and subscripts).
742 # so this is 'trailerlist'
743 def p_power(self
, p
):
745 | atom trailerlist"""
747 print("power dump atom notrailer")
748 print(astor
.dump_tree(p
[1]))
751 print("power dump atom")
752 print(astor
.dump_tree(p
[1]))
753 print("power dump trailerlist")
754 print(astor
.dump_tree(p
[2]))
755 p
[0] = apply_trailer(p
[1], p
[2], self
.read_regs
)
756 if isinstance(p
[1], ast
.Name
):
758 if name
in regs
+ fregs
:
759 self
.read_regs
.add(name
)
761 def p_atom_name(self
, p
):
764 if name
in self
.available_op_fields
:
765 self
.op_fields
.add(name
)
766 if name
== 'overflow':
767 self
.write_regs
.add(name
)
768 if self
.include_ca_in_write
:
769 if name
in ['CA', 'CA32']:
770 self
.write_regs
.add(name
)
771 if name
in ['CR', 'LR', 'CTR', 'TAR', 'FPSCR', 'MSR',
772 'SVSTATE', 'SVREMAP',
773 'SVSHAPE0', 'SVSHAPE1', 'SVSHAPE2', 'SVSHAPE3']:
774 self
.special_regs
.add(name
)
775 self
.write_regs
.add(name
) # and add to list to write
776 p
[0] = ast
.Name(id=name
, ctx
=ast
.Load())
778 def p_atom_number(self
, p
):
783 p
[0] = ast
.Constant(p
[1])
785 # '[' [listmaker] ']' |
787 def p_atom_listmaker(self
, p
):
788 """atom : LBRACK listmaker RBRACK"""
791 def p_listmaker(self
, p
):
792 """listmaker : test COMMA listmaker
796 p
[0] = ast
.List([p
[1]], ast
.Load())
798 p
[0] = ast
.List([p
[1]] + p
[3].nodes
, ast
.Load())
800 def p_atom_tuple(self
, p
):
801 """atom : LPAR testlist RPAR"""
804 print(astor
.dump_tree(p
[2]))
806 if isinstance(p
[2], ast
.Name
):
808 print("tuple name", name
)
809 if name
in self
.gprs
:
810 self
.read_regs
.add(name
) # add to list of regs to read
811 #p[0] = ast.Subscript(ast.Name("GPR", ast.Load()), ast.Str(p[2].id))
814 elif isinstance(p
[2], ast
.BinOp
):
815 if isinstance(p
[2].left
, ast
.Name
) and \
816 isinstance(p
[2].right
, ast
.Constant
) and \
817 p
[2].right
.value
== 0 and \
818 p
[2].left
.id in self
.gprs
:
820 self
.read_regs
.add(rid
) # add to list of regs to read
821 # create special call to GPR.getz or FPR.getz
823 gprz
= ast
.Name("FPR", ast
.Load())
825 gprz
= ast
.Name("GPR", ast
.Load())
826 # get testzero function
827 gprz
= ast
.Attribute(gprz
, "getz", ast
.Load())
828 # *sigh* see class GPR. we need index itself not reg value
829 ridx
= ast
.Name("_%s" % rid
, ast
.Load())
830 p
[0] = ast
.Call(gprz
, [ridx
], [])
831 print("tree", astor
.dump_tree(p
[0]))
837 def p_trailerlist(self
, p
):
838 """trailerlist : trailer trailerlist
844 p
[0] = ("TLIST", p
[1], p
[2])
846 # trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
847 def p_trailer(self
, p
):
848 """trailer : trailer_arglist
853 def p_trailer_arglist(self
, p
):
854 "trailer_arglist : LPAR arglist RPAR"
855 p
[0] = ("CALL", p
[2])
857 def p_trailer_subscript(self
, p
):
858 "trailer_subscript : LBRACK subscript RBRACK"
859 p
[0] = ("SUBS", p
[2])
861 # subscript: '.' '.' '.' | test | [test] ':' [test]
863 def p_subscript(self
, p
):
864 """subscript : test COLON test
869 if isinstance(p
[3], ast
.Constant
):
870 end
= ast
.Constant(p
[3].value
+1)
872 end
= ast
.BinOp(p
[3], ast
.Add(), ast
.Constant(1))
877 # testlist: test (',' test)* [',']
878 # Contains shift/reduce error
880 def p_testlist(self
, p
):
881 """testlist : testlist_multi COMMA
886 # May need to promote singleton to tuple
887 if isinstance(p
[1], list):
891 # Convert into a tuple?
892 if isinstance(p
[0], list):
893 p
[0] = ast
.Tuple(p
[0])
895 def p_testlist_multi(self
, p
):
896 """testlist_multi : testlist_multi COMMA test
902 if isinstance(p
[1], list):
908 # test: or_test ['if' or_test 'else' test] | lambdef
909 # as I don't support 'and', 'or', and 'not' this works down to 'comparison'
915 # arglist: (argument ',')* (argument [',']| '*' test [',' '**' test]
917 # XXX INCOMPLETE: this doesn't allow the trailing comma
919 def p_arglist(self
, p
):
920 """arglist : arglist COMMA argument
927 # argument: test [gen_for] | test '=' test # Really [keyword '='] test
928 def p_argument(self
, p
):
932 def p_error(self
, p
):
933 # print "Error!", repr(p)
937 class GardenSnakeParser(PowerParser
):
938 def __init__(self
, lexer
=None, debug
=False, form
=None, incl_carry
=False, helper
=False):
940 self
.sd
= create_pdecode()
941 PowerParser
.__init
__(self
, form
, incl_carry
)
944 lexer
= IndentLexer(debug
=0)
946 self
.tokens
= lexer
.tokens
948 self
.parser
= yacc
.yacc(module
=self
, start
="file_input_end",
949 debug
=debug
, write_tables
=False)
951 def parse(self
, code
):
952 # self.lexer.input(code)
953 result
= self
.parser
.parse(code
, lexer
=self
.lexer
, debug
=self
.debug
)
954 return ast
.Module(result
)
957 ###### Code generation ######
959 #from compiler import misc, syntax, pycodegen
962 _CACHE_PARSERS
= True
965 class GardenSnakeCompiler(object):
966 def __init__(self
, debug
=False, form
=None, incl_carry
=False, helper
=False):
969 parser
= _CACHED_PARSERS
[debug
, form
, incl_carry
, helper
]
971 parser
= GardenSnakeParser(debug
=debug
, form
=form
,
972 incl_carry
=incl_carry
, helper
=helper
)
973 _CACHED_PARSERS
[debug
, form
, incl_carry
, helper
] = parser
975 self
.parser
= deepcopy(parser
)
977 self
.parser
= GardenSnakeParser(debug
=debug
, form
=form
,
978 incl_carry
=incl_carry
, helper
=helper
)
980 def compile(self
, code
, mode
="exec", filename
="<string>"):
981 tree
= self
.parser
.parse(code
)
985 #misc.set_filename(filename, tree)
986 return compile(tree
, mode
="exec", filename
="<string>")
988 gen
= pycodegen
.ModuleCodeGenerator(tree
)