4fb7bba95a6b22f02456c86d21a192a0c75142da
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(left
, right
, iea_mode
):
28 print("Assign", 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
):
46 return ast
.Assign([left
], right
)
47 # XXX HMMM probably not needed...
49 if isinstance(ls
, ast
.Slice
):
50 lower
, upper
, step
= ls
.lower
, ls
.upper
, ls
.step
51 print("slice assign", lower
, upper
, step
)
53 ls
= (lower
, upper
, None)
55 ls
= (lower
, upper
, step
)
57 return ast
.Call(ast
.Name("selectassign"),
58 [left
.value
, ls
, right
], [])
61 raise SyntaxError("Can't do that yet")
64 # I implemented INDENT / DEDENT generation as a post-processing filter
66 # The original lex token stream contains WS and NEWLINE characters.
67 # WS will only occur before any other tokens on a line.
69 # I have three filters. One tags tokens by adding two attributes.
70 # "must_indent" is True if the token must be indented from the
71 # previous code. The other is "at_line_start" which is True for WS
72 # and the first non-WS/non-NEWLINE on a line. It flags the check so
73 # see if the new line has changed indication level.
76 # No using Python's approach because Ply supports precedence
78 # comparison: expr (comp_op expr)*
79 # arith_expr: term (('+'|'-') term)*
80 # term: factor (('*'|'/'|'%'|'//') factor)*
81 # factor: ('+'|'-'|'~') factor | power
82 # comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
84 def make_le_compare(arg
):
86 return ast
.Compare(left
, [ast
.LtE()], [right
])
89 def make_ge_compare(arg
):
91 return ast
.Compare(left
, [ast
.GtE()], [right
])
94 def make_lt_compare(arg
):
96 return ast
.Compare(left
, [ast
.Lt()], [right
])
99 def make_gt_compare(arg
):
101 return ast
.Compare(left
, [ast
.Gt()], [right
])
104 def make_eq_compare(arg
):
106 return ast
.Compare(left
, [ast
.Eq()], [right
])
109 def make_ne_compare(arg
):
111 return ast
.Compare(left
, [ast
.NotEq()], [right
])
123 "<=": make_le_compare
,
124 ">=": make_ge_compare
,
125 "<": make_lt_compare
,
126 ">": make_gt_compare
,
127 "=": make_eq_compare
,
128 "!=": make_ne_compare
,
137 def check_concat(node
): # checks if the comparison is already a concat
138 print("check concat", node
)
139 if not isinstance(node
, ast
.Call
):
141 print("func", node
.func
.id)
142 if node
.func
.id != 'concat':
144 if node
.keywords
: # a repeated list-constant, don't optimise
149 # identify SelectableInt pattern [something] * N
150 # must return concat(something, repeat=N)
151 def identify_sint_mul_pattern(p
):
152 if p
[2] != '*': # multiply
154 if not isinstance(p
[3], ast
.Constant
): # rhs = Num
156 if not isinstance(p
[1], ast
.List
): # lhs is a list
159 if len(l
) != 1: # lhs is a list of length 1
161 return True # yippee!
164 def apply_trailer(atom
, trailer
):
165 if trailer
[0] == "TLIST":
166 # assume depth of one
167 atom
= apply_trailer(atom
, trailer
[1])
169 if trailer
[0] == "CALL":
170 #p[0] = ast.Expr(ast.Call(p[1], p[2][1], []))
171 return ast
.Call(atom
, trailer
[1], [])
172 # if p[1].id == 'print':
173 # p[0] = ast.Printnl(ast.Tuple(p[2][1]), None, None)
175 # p[0] = ast.CallFunc(p[1], p[2][1], None, None)
177 print("subscript atom", trailer
[1])
178 #raise AssertionError("not implemented %s" % p[2][0])
183 idx
= ast
.Slice(subs
[0], subs
[1], None)
184 return ast
.Subscript(atom
, idx
, ast
.Load())
186 ########## Parser (tokens -> AST) ######
191 # https://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_precedence.html
192 # python operator precedence
193 # Highest precedence at top, lowest at bottom.
194 # Operators in the same box evaluate left to right.
196 # Operator Description
197 # () Parentheses (grouping)
198 # f(args...) Function call
199 # x[index:index] Slicing
200 # x[index] Subscription
201 # x.attribute Attribute reference
204 # +x, -x Positive, negative
205 # *, /, % mul, div, remainder
206 # +, - Addition, subtraction
207 # <<, >> Bitwise shifts
211 # in, not in, is, is not, <, <=, >, >=, <>, !=, == comp, membership, ident
215 # lambda Lambda expression
220 ("left", "EQ", "NE", "GT", "LT", "LE", "GE", "LTU", "GTU"),
224 ("left", "PLUS", "MINUS"),
225 ("left", "MULT", "DIV", "MOD"),
231 for rname
in ['RA', 'RB', 'RC', 'RT', 'RS']:
232 self
.gprs
[rname
] = None
233 self
.read_regs
= OrderedSet()
234 self
.uninit_regs
= OrderedSet()
235 self
.write_regs
= OrderedSet()
237 # The grammar comments come from Python's Grammar/Grammar file
239 # NB: compound_stmt in single_input is followed by extra NEWLINE!
240 # file_input: (NEWLINE | stmt)* ENDMARKER
242 def p_file_input_end(self
, p
):
243 """file_input_end : file_input ENDMARKER"""
247 def p_file_input(self
, p
):
248 """file_input : file_input NEWLINE
252 if isinstance(p
[len(p
)-1], str):
256 p
[0] = [] # p == 2 --> only a blank line
263 # funcdef: [decorators] 'def' NAME parameters ':' suite
264 # ignoring decorators
266 def p_funcdef(self
, p
):
267 "funcdef : DEF NAME parameters COLON suite"
268 p
[0] = ast
.FunctionDef(p
[2], p
[3], p
[5], ())
270 # parameters: '(' [varargslist] ')'
271 def p_parameters(self
, p
):
272 """parameters : LPAR RPAR
273 | LPAR varargslist RPAR"""
278 p
[0] = ast
.arguments(args
=args
, vararg
=None, kwarg
=None, defaults
=[])
280 # varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] |
284 def p_varargslist(self
, p
):
285 """varargslist : varargslist COMMA NAME
292 # stmt: simple_stmt | compound_stmt
293 def p_stmt_simple(self
, p
):
294 """stmt : simple_stmt"""
295 # simple_stmt is a list
298 def p_stmt_compound(self
, p
):
299 """stmt : compound_stmt"""
302 # simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
303 def p_simple_stmt(self
, p
):
304 """simple_stmt : small_stmts NEWLINE
305 | small_stmts SEMICOLON NEWLINE"""
308 def p_small_stmts(self
, p
):
309 """small_stmts : small_stmts SEMICOLON small_stmt
316 # small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
317 # import_stmt | global_stmt | exec_stmt | assert_stmt
318 def p_small_stmt(self
, p
):
319 """small_stmt : flow_stmt
322 if isinstance(p
[1], ast
.Call
):
323 p
[0] = ast
.Expr(p
[1])
327 # expr_stmt: testlist (augassign (yield_expr|testlist) |
328 # ('=' (yield_expr|testlist))*)
329 # augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
330 # '<<=' | '>>=' | '**=' | '//=')
331 def p_expr_stmt(self
, p
):
332 """expr_stmt : testlist ASSIGNEA testlist
333 | testlist ASSIGN testlist
335 print("expr_stmt", p
)
337 # a list of expressions
338 #p[0] = ast.Discard(p[1])
341 iea_mode
= p
[2] == '<-iea'
343 if isinstance(p
[1], ast
.Name
):
345 elif isinstance(p
[1], ast
.Subscript
):
347 if name
in self
.gprs
:
348 # add to list of uninitialised
349 self
.uninit_regs
.add(name
)
350 elif isinstance(p
[1], ast
.Call
) and p
[1].func
.id == 'GPR':
351 print(astor
.dump_tree(p
[1]))
352 # replace GPR(x) with GPR[x]
354 p
[1] = ast
.Subscript(p
[1].func
, idx
)
355 elif isinstance(p
[1], ast
.Call
) and p
[1].func
.id == 'MEM':
357 print(astor
.dump_tree(p
[1]))
358 p
[1].func
.id = "memassign" # change function name to set
359 p
[1].args
.append(p
[3])
361 print ("mem rewrite")
362 print(astor
.dump_tree(p
[0]))
366 print(astor
.dump_tree(p
[1]))
367 print("expr assign", name
, p
[1])
368 if name
and name
in self
.gprs
:
369 self
.write_regs
.add(name
) # add to list of regs to write
370 p
[0] = Assign(p
[1], p
[3], iea_mode
)
372 def p_flow_stmt(self
, p
):
373 "flow_stmt : return_stmt"
376 # return_stmt: 'return' [testlist]
377 def p_return_stmt(self
, p
):
378 "return_stmt : RETURN testlist"
379 p
[0] = ast
.Return(p
[2])
381 def p_compound_stmt(self
, p
):
382 """compound_stmt : if_stmt
389 def p_break_stmt(self
, p
):
390 """break_stmt : BREAK
394 def p_for_stmt(self
, p
):
395 """for_stmt : FOR atom EQ test TO test COLON suite
396 | DO atom EQ test TO test COLON suite
398 # auto-add-one (sigh) due to python range
400 end
= ast
.BinOp(p
[6], ast
.Add(), ast
.Constant(1))
401 it
= ast
.Call(ast
.Name("range"), [start
, end
], [])
402 p
[0] = ast
.For(p
[2], it
, p
[8], [])
404 def p_while_stmt(self
, p
):
405 """while_stmt : DO WHILE test COLON suite ELSE COLON suite
406 | DO WHILE test COLON suite
409 p
[0] = ast
.While(p
[3], p
[5], [])
411 p
[0] = ast
.While(p
[3], p
[5], p
[8])
413 def p_if_stmt(self
, p
):
414 """if_stmt : IF test COLON suite ELSE COLON if_stmt
415 | IF test COLON suite ELSE COLON suite
416 | IF test COLON suite
418 if len(p
) == 8 and isinstance(p
[7], ast
.If
):
419 p
[0] = ast
.If(p
[2], p
[4], [p
[7]])
421 p
[0] = ast
.If(p
[2], p
[4], [])
423 p
[0] = ast
.If(p
[2], p
[4], p
[7])
425 def p_suite(self
, p
):
426 """suite : simple_stmt
427 | NEWLINE INDENT stmts DEDENT"""
433 def p_stmts(self
, p
):
434 """stmts : stmts stmt
441 def p_comparison(self
, p
):
442 """comparison : comparison PLUS comparison
443 | comparison MINUS comparison
444 | comparison MULT comparison
445 | comparison DIV comparison
446 | comparison MOD comparison
447 | comparison EQ comparison
448 | comparison NE comparison
449 | comparison LE comparison
450 | comparison GE comparison
451 | comparison LTU comparison
452 | comparison GTU comparison
453 | comparison LT comparison
454 | comparison GT comparison
455 | comparison BITOR comparison
456 | comparison BITXOR comparison
457 | comparison BITAND comparison
461 | comparison APPEND comparison
466 p
[0] = ast
.Call(ast
.Name("ltu"), (p
[1], p
[3]), [])
468 p
[0] = ast
.Call(ast
.Name("gtu"), (p
[1], p
[3]), [])
470 l
= check_concat(p
[1]) + check_concat(p
[3])
471 p
[0] = ast
.Call(ast
.Name("concat"), l
, [])
472 elif p
[2] in ['<', '>', '=', '<=', '>=', '!=']:
473 p
[0] = binary_ops
[p
[2]]((p
[1], p
[3]))
474 elif identify_sint_mul_pattern(p
):
475 keywords
=[ast
.keyword(arg
='repeat', value
=p
[3])]
477 p
[0] = ast
.Call(ast
.Name("concat"), l
, keywords
)
479 p
[0] = ast
.BinOp(p
[1], binary_ops
[p
[2]], p
[3])
481 if isinstance(p
[2], str) and p
[2] == '-':
482 p
[0] = ast
.UnaryOp(unary_ops
[p
[2]], p
[1])
484 p
[0] = ast
.UnaryOp(unary_ops
[p
[1]], p
[2])
488 # power: atom trailer* ['**' factor]
489 # trailers enables function calls (and subscripts).
490 # so this is 'trailerlist'
491 def p_power(self
, p
):
493 | atom trailerlist"""
497 print("power dump atom")
498 print(astor
.dump_tree(p
[1]))
499 print("power dump trailerlist")
500 print(astor
.dump_tree(p
[2]))
501 p
[0] = apply_trailer(p
[1], p
[2])
503 def p_atom_name(self
, p
):
505 p
[0] = ast
.Name(id=p
[1], ctx
=ast
.Load())
507 def p_atom_number(self
, p
):
511 p
[0] = ast
.Constant(p
[1])
513 # '[' [listmaker] ']' |
515 def p_atom_listmaker(self
, p
):
516 """atom : LBRACK listmaker RBRACK"""
519 def p_listmaker(self
, p
):
520 """listmaker : test COMMA listmaker
524 p
[0] = ast
.List([p
[1]])
526 p
[0] = ast
.List([p
[1]] + p
[3].nodes
)
528 def p_atom_tuple(self
, p
):
529 """atom : LPAR testlist RPAR"""
532 print(astor
.dump_tree(p
[2]))
534 if isinstance(p
[2], ast
.Name
):
535 print("tuple name", p
[2].id)
536 if p
[2].id in self
.gprs
:
537 self
.read_regs
.add(p
[2].id) # add to list of regs to read
538 #p[0] = ast.Subscript(ast.Name("GPR"), ast.Str(p[2].id))
541 elif isinstance(p
[2], ast
.BinOp
):
542 if isinstance(p
[2].left
, ast
.Name
) and \
543 isinstance(p
[2].right
, ast
.Constant
) and \
544 p
[2].right
.value
== 0 and \
545 p
[2].left
.id in self
.gprs
:
547 self
.read_regs
.add(rid
) # add to list of regs to read
548 # create special call to GPR.getz
549 gprz
= ast
.Name("GPR")
550 gprz
= ast
.Attribute(gprz
, "getz") # get testzero function
551 # *sigh* see class GPR. we need index itself not reg value
552 ridx
= ast
.Name("_%s" % rid
)
553 p
[0] = ast
.Call(gprz
, [ridx
], [])
554 print("tree", astor
.dump_tree(p
[0]))
560 def p_trailerlist(self
, p
):
561 """trailerlist : trailer trailerlist
567 p
[0] = ("TLIST", p
[1], p
[2])
569 # trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
570 def p_trailer(self
, p
):
571 """trailer : trailer_arglist
576 def p_trailer_arglist(self
, p
):
577 "trailer_arglist : LPAR arglist RPAR"
578 p
[0] = ("CALL", p
[2])
580 def p_trailer_subscript(self
, p
):
581 "trailer_subscript : LBRACK subscript RBRACK"
582 p
[0] = ("SUBS", p
[2])
584 # subscript: '.' '.' '.' | test | [test] ':' [test]
586 def p_subscript(self
, p
):
587 """subscript : test COLON test
592 if isinstance(p
[3], ast
.Constant
):
593 end
= ast
.Constant(p
[3].value
+1)
595 end
= ast
.BinOp(p
[3], ast
.Add(), ast
.Constant(1))
600 # testlist: test (',' test)* [',']
601 # Contains shift/reduce error
603 def p_testlist(self
, p
):
604 """testlist : testlist_multi COMMA
609 # May need to promote singleton to tuple
610 if isinstance(p
[1], list):
614 # Convert into a tuple?
615 if isinstance(p
[0], list):
616 p
[0] = ast
.Tuple(p
[0])
618 def p_testlist_multi(self
, p
):
619 """testlist_multi : testlist_multi COMMA test
625 if isinstance(p
[1], list):
631 # test: or_test ['if' or_test 'else' test] | lambdef
632 # as I don't support 'and', 'or', and 'not' this works down to 'comparison'
638 # arglist: (argument ',')* (argument [',']| '*' test [',' '**' test]
640 # XXX INCOMPLETE: this doesn't allow the trailing comma
642 def p_arglist(self
, p
):
643 """arglist : arglist COMMA argument
650 # argument: test [gen_for] | test '=' test # Really [keyword '='] test
651 def p_argument(self
, p
):
655 def p_error(self
, p
):
656 # print "Error!", repr(p)
660 class GardenSnakeParser(PowerParser
):
661 def __init__(self
, lexer
=None, debug
=False):
662 PowerParser
.__init
__(self
)
665 lexer
= IndentLexer(debug
=0)
667 self
.tokens
= lexer
.tokens
668 self
.parser
= yacc
.yacc(module
=self
, start
="file_input_end",
669 debug
=debug
, write_tables
=False)
671 self
.sd
= create_pdecode()
673 def parse(self
, code
):
674 # self.lexer.input(code)
675 result
= self
.parser
.parse(code
, lexer
=self
.lexer
, debug
=self
.debug
)
676 return ast
.Module(result
)
679 ###### Code generation ######
681 #from compiler import misc, syntax, pycodegen
683 class GardenSnakeCompiler(object):
684 def __init__(self
, debug
=False):
685 self
.parser
= GardenSnakeParser(debug
=debug
)
687 def compile(self
, code
, mode
="exec", filename
="<string>"):
688 tree
= self
.parser
.parse(code
)
692 #misc.set_filename(filename, tree)
693 return compile(tree
, mode
="exec", filename
="<string>")
695 gen
= pycodegen
.ModuleCodeGenerator(tree
)