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
18 # I use the Python AST
19 #from compiler import ast
25 def Assign(left
, right
):
27 print("Assign", left
, right
)
28 if isinstance(left
, ast
.Name
):
29 # Single assignment on left
30 # XXX when doing IntClass, which will have an "eq" function,
31 # this is how to access it
32 # eq = ast.Attribute(left, "eq") # get eq fn
33 # return ast.Call(eq, [right], []) # now call left.eq(right)
34 return ast
.Assign([ast
.Name(left
.id, ast
.Store())], right
)
35 elif isinstance(left
, ast
.Tuple
):
36 # List of things - make sure they are Name nodes
38 for child
in left
.getChildren():
39 if not isinstance(child
, ast
.Name
):
40 raise SyntaxError("that assignment not supported")
41 names
.append(child
.name
)
42 ass_list
= [ast
.AssName(name
, 'OP_ASSIGN') for name
in names
]
43 return ast
.Assign([ast
.AssTuple(ass_list
)], right
)
44 elif isinstance(left
, ast
.Subscript
):
45 return ast
.Assign([left
], right
)
46 # XXX HMMM probably not needed...
48 if isinstance(ls
, ast
.Slice
):
49 lower
, upper
, step
= ls
.lower
, ls
.upper
, ls
.step
50 print("slice assign", lower
, upper
, step
)
52 ls
= (lower
, upper
, None)
54 ls
= (lower
, upper
, step
)
56 return ast
.Call(ast
.Name("selectassign"),
57 [left
.value
, ls
, right
], [])
60 raise SyntaxError("Can't do that yet")
63 # I implemented INDENT / DEDENT generation as a post-processing filter
65 # The original lex token stream contains WS and NEWLINE characters.
66 # WS will only occur before any other tokens on a line.
68 # I have three filters. One tags tokens by adding two attributes.
69 # "must_indent" is True if the token must be indented from the
70 # previous code. The other is "at_line_start" which is True for WS
71 # and the first non-WS/non-NEWLINE on a line. It flags the check so
72 # see if the new line has changed indication level.
75 # No using Python's approach because Ply supports precedence
77 # comparison: expr (comp_op expr)*
78 # arith_expr: term (('+'|'-') term)*
79 # term: factor (('*'|'/'|'%'|'//') factor)*
80 # factor: ('+'|'-'|'~') factor | power
81 # comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
83 def make_le_compare(arg
):
85 return ast
.Compare(left
, [ast
.LtE()], [right
])
88 def make_ge_compare(arg
):
90 return ast
.Compare(left
, [ast
.GtE()], [right
])
93 def make_lt_compare(arg
):
95 return ast
.Compare(left
, [ast
.Lt()], [right
])
98 def make_gt_compare(arg
):
100 return ast
.Compare(left
, [ast
.Gt()], [right
])
103 def make_eq_compare(arg
):
105 return ast
.Compare(left
, [ast
.Eq()], [right
])
116 "<=": make_le_compare
,
117 ">=": make_ge_compare
,
118 "<": make_lt_compare
,
119 ">": make_gt_compare
,
120 "=": make_eq_compare
,
129 def check_concat(node
): # checks if the comparison is already a concat
130 print("check concat", node
)
131 if not isinstance(node
, ast
.Call
):
133 print("func", node
.func
.id)
134 if node
.func
.id != 'concat':
136 if node
.keywords
: # a repeated list-constant, don't optimise
141 # identify SelectableInt pattern
142 def identify_sint_mul_pattern(p
):
143 if not isinstance(p
[3], ast
.Constant
):
145 if not isinstance(p
[1], ast
.List
):
151 return isinstance(elt
, ast
.Constant
)
154 ########## Parser (tokens -> AST) ######
159 # https://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_precedence.html
160 # python operator precedence
161 # Highest precedence at top, lowest at bottom.
162 # Operators in the same box evaluate left to right.
164 # Operator Description
165 # () Parentheses (grouping)
166 # f(args...) Function call
167 # x[index:index] Slicing
168 # x[index] Subscription
169 # x.attribute Attribute reference
172 # +x, -x Positive, negative
173 # *, /, % mul, div, remainder
174 # +, - Addition, subtraction
175 # <<, >> Bitwise shifts
179 # in, not in, is, is not, <, <=, >, >=, <>, !=, == comp, membership, ident
183 # lambda Lambda expression
188 ("left", "EQ", "GT", "LT", "LE", "GE", "LTU", "GTU"),
191 ("left", "PLUS", "MINUS"),
192 ("left", "MULT", "DIV", "MOD"),
198 for rname
in ['RA', 'RB', 'RC', 'RT', 'RS']:
199 self
.gprs
[rname
] = None
201 self
.uninit_regs
= []
204 # The grammar comments come from Python's Grammar/Grammar file
206 # NB: compound_stmt in single_input is followed by extra NEWLINE!
207 # file_input: (NEWLINE | stmt)* ENDMARKER
209 def p_file_input_end(self
, p
):
210 """file_input_end : file_input ENDMARKER"""
214 def p_file_input(self
, p
):
215 """file_input : file_input NEWLINE
219 if isinstance(p
[len(p
)-1], str):
223 p
[0] = [] # p == 2 --> only a blank line
230 # funcdef: [decorators] 'def' NAME parameters ':' suite
231 # ignoring decorators
233 def p_funcdef(self
, p
):
234 "funcdef : DEF NAME parameters COLON suite"
235 p
[0] = ast
.FunctionDef(p
[2], p
[3], p
[5], ())
237 # parameters: '(' [varargslist] ')'
238 def p_parameters(self
, p
):
239 """parameters : LPAR RPAR
240 | LPAR varargslist RPAR"""
245 p
[0] = ast
.arguments(args
=args
, vararg
=None, kwarg
=None, defaults
=[])
247 # varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] |
251 def p_varargslist(self
, p
):
252 """varargslist : varargslist COMMA NAME
259 # stmt: simple_stmt | compound_stmt
260 def p_stmt_simple(self
, p
):
261 """stmt : simple_stmt"""
262 # simple_stmt is a list
265 def p_stmt_compound(self
, p
):
266 """stmt : compound_stmt"""
269 # simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
270 def p_simple_stmt(self
, p
):
271 """simple_stmt : small_stmts NEWLINE
272 | small_stmts SEMICOLON NEWLINE"""
275 def p_small_stmts(self
, p
):
276 """small_stmts : small_stmts SEMICOLON small_stmt
283 # small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
284 # import_stmt | global_stmt | exec_stmt | assert_stmt
285 def p_small_stmt(self
, p
):
286 """small_stmt : flow_stmt
289 if isinstance(p
[1], ast
.Call
):
290 p
[0] = ast
.Expr(p
[1])
294 # expr_stmt: testlist (augassign (yield_expr|testlist) |
295 # ('=' (yield_expr|testlist))*)
296 # augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
297 # '<<=' | '>>=' | '**=' | '//=')
298 def p_expr_stmt(self
, p
):
299 """expr_stmt : testlist ASSIGN testlist
301 print("expr_stmt", p
)
303 # a list of expressions
304 #p[0] = ast.Discard(p[1])
307 if isinstance(p
[1], ast
.Name
):
309 elif isinstance(p
[1], ast
.Subscript
):
311 if name
in self
.gprs
:
312 # add to list of uninitialised
313 self
.uninit_regs
.append(name
)
314 print("expr assign", name
, p
[1])
315 if name
in self
.gprs
:
316 self
.write_regs
.append(name
) # add to list of regs to write
317 p
[0] = Assign(p
[1], p
[3])
319 def p_flow_stmt(self
, p
):
320 "flow_stmt : return_stmt"
323 # return_stmt: 'return' [testlist]
324 def p_return_stmt(self
, p
):
325 "return_stmt : RETURN testlist"
326 p
[0] = ast
.Return(p
[2])
328 def p_compound_stmt(self
, p
):
329 """compound_stmt : if_stmt
336 def p_break_stmt(self
, p
):
337 """break_stmt : BREAK
341 def p_for_stmt(self
, p
):
342 """for_stmt : FOR test EQ test TO test COLON suite
344 p
[0] = ast
.While(p
[2], p
[4], [])
345 # auto-add-one (sigh) due to python range
347 end
= ast
.BinOp(p
[6], ast
.Add(), ast
.Constant(1))
348 it
= ast
.Call(ast
.Name("range"), [start
, end
], [])
349 p
[0] = ast
.For(p
[2], it
, p
[8], [])
351 def p_while_stmt(self
, p
):
352 """while_stmt : DO WHILE test COLON suite ELSE COLON suite
353 | DO WHILE test COLON suite
356 p
[0] = ast
.While(p
[3], p
[5], [])
358 p
[0] = ast
.While(p
[3], p
[5], p
[8])
360 def p_if_stmt(self
, p
):
361 """if_stmt : IF test COLON suite ELSE COLON if_stmt
362 | IF test COLON suite ELSE COLON suite
363 | IF test COLON suite
365 if len(p
) == 8 and isinstance(p
[7], ast
.If
):
366 p
[0] = ast
.If(p
[2], p
[4], [p
[7]])
368 p
[0] = ast
.If(p
[2], p
[4], [])
370 p
[0] = ast
.If(p
[2], p
[4], p
[7])
372 def p_suite(self
, p
):
373 """suite : simple_stmt
374 | NEWLINE INDENT stmts DEDENT"""
380 def p_stmts(self
, p
):
381 """stmts : stmts stmt
388 def p_comparison(self
, p
):
389 """comparison : comparison PLUS comparison
390 | comparison MINUS comparison
391 | comparison MULT comparison
392 | comparison DIV comparison
393 | comparison MOD comparison
394 | comparison EQ comparison
395 | comparison LE comparison
396 | comparison GE comparison
397 | comparison LTU comparison
398 | comparison GTU comparison
399 | comparison LT comparison
400 | comparison GT comparison
401 | comparison BITOR comparison
402 | comparison BITAND comparison
406 | comparison APPEND comparison
411 p
[0] = ast
.Call(ast
.Name("ltu"), (p
[1], p
[3]), [])
413 p
[0] = ast
.Call(ast
.Name("gtu"), (p
[1], p
[3]), [])
415 l
= check_concat(p
[1]) + check_concat(p
[3])
416 p
[0] = ast
.Call(ast
.Name("concat"), l
, [])
417 elif p
[2] in ['<', '>', '=', '<=', '>=']:
418 p
[0] = binary_ops
[p
[2]]((p
[1], p
[3]))
419 elif identify_sint_mul_pattern(p
):
420 keywords
=[ast
.keyword(arg
='repeat', value
=p
[3])]
422 p
[0] = ast
.Call(ast
.Name("concat"), l
, keywords
)
424 p
[0] = ast
.BinOp(p
[1], binary_ops
[p
[2]], p
[3])
426 if isinstance(p
[2], str) and p
[2] == '-':
427 p
[0] = ast
.UnaryOp(unary_ops
[p
[2]], p
[1])
429 p
[0] = ast
.UnaryOp(unary_ops
[p
[1]], p
[2])
433 # power: atom trailer* ['**' factor]
434 # trailers enables function calls (and subscripts).
435 # I only allow one level of calls
436 # so this is 'trailer'
437 def p_power(self
, p
):
443 if p
[2][0] == "CALL":
444 #p[0] = ast.Expr(ast.Call(p[1], p[2][1], []))
445 p
[0] = ast
.Call(p
[1], p
[2][1], [])
446 # if p[1].id == 'print':
447 # p[0] = ast.Printnl(ast.Tuple(p[2][1]), None, None)
449 # p[0] = ast.CallFunc(p[1], p[2][1], None, None)
451 print("subscript atom", p
[2][1])
452 #raise AssertionError("not implemented %s" % p[2][0])
457 idx
= ast
.Slice(subs
[0], subs
[1], None)
458 p
[0] = ast
.Subscript(p
[1], idx
, ast
.Load())
460 def p_atom_name(self
, p
):
462 p
[0] = ast
.Name(id=p
[1], ctx
=ast
.Load())
464 def p_atom_number(self
, p
):
468 p
[0] = ast
.Constant(p
[1])
470 # '[' [listmaker] ']' |
472 def p_atom_listmaker(self
, p
):
473 """atom : LBRACK listmaker RBRACK"""
476 def p_listmaker(self
, p
):
477 """listmaker : test COMMA listmaker
481 p
[0] = ast
.List([p
[1]])
483 p
[0] = ast
.List([p
[1]] + p
[3].nodes
)
485 def p_atom_tuple(self
, p
):
486 """atom : LPAR testlist RPAR"""
488 if isinstance(p
[2], ast
.Name
):
489 print("tuple name", p
[2].id)
490 if p
[2].id in self
.gprs
:
491 self
.read_regs
.append(p
[2].id) # add to list of regs to read
492 #p[0] = ast.Subscript(ast.Name("GPR"), ast.Str(p[2].id))
496 # trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
497 def p_trailer(self
, p
):
498 """trailer : trailer_arglist
503 def p_trailer_arglist(self
, p
):
504 "trailer_arglist : LPAR arglist RPAR"
505 p
[0] = ("CALL", p
[2])
507 def p_trailer_subscript(self
, p
):
508 "trailer_subscript : LBRACK subscript RBRACK"
509 p
[0] = ("SUBS", p
[2])
511 # subscript: '.' '.' '.' | test | [test] ':' [test]
513 def p_subscript(self
, p
):
514 """subscript : test COLON test
519 if isinstance(p
[3], ast
.Constant
):
520 end
= ast
.Constant(p
[3].value
+1)
522 end
= ast
.BinOp(p
[3], ast
.Add(), ast
.Constant(1))
527 # testlist: test (',' test)* [',']
528 # Contains shift/reduce error
530 def p_testlist(self
, p
):
531 """testlist : testlist_multi COMMA
536 # May need to promote singleton to tuple
537 if isinstance(p
[1], list):
541 # Convert into a tuple?
542 if isinstance(p
[0], list):
543 p
[0] = ast
.Tuple(p
[0])
545 def p_testlist_multi(self
, p
):
546 """testlist_multi : testlist_multi COMMA test
552 if isinstance(p
[1], list):
558 # test: or_test ['if' or_test 'else' test] | lambdef
559 # as I don't support 'and', 'or', and 'not' this works down to 'comparison'
565 # arglist: (argument ',')* (argument [',']| '*' test [',' '**' test]
567 # XXX INCOMPLETE: this doesn't allow the trailing comma
569 def p_arglist(self
, p
):
570 """arglist : arglist COMMA argument
577 # argument: test [gen_for] | test '=' test # Really [keyword '='] test
578 def p_argument(self
, p
):
582 def p_error(self
, p
):
583 # print "Error!", repr(p)
587 class GardenSnakeParser(PowerParser
):
588 def __init__(self
, lexer
=None):
589 PowerParser
.__init
__(self
)
591 lexer
= IndentLexer(debug
=0)
593 self
.tokens
= lexer
.tokens
594 self
.parser
= yacc
.yacc(module
=self
, start
="file_input_end",
595 debug
=False, write_tables
=False)
597 self
.sd
= create_pdecode()
599 def parse(self
, code
):
600 # self.lexer.input(code)
601 result
= self
.parser
.parse(code
, lexer
=self
.lexer
, debug
=False)
602 return ast
.Module(result
)
605 ###### Code generation ######
607 #from compiler import misc, syntax, pycodegen
609 class GardenSnakeCompiler(object):
611 self
.parser
= GardenSnakeParser()
613 def compile(self
, code
, mode
="exec", filename
="<string>"):
614 tree
= self
.parser
.parse(code
)
618 #misc.set_filename(filename, tree)
619 return compile(tree
, mode
="exec", filename
="<string>")
621 gen
= pycodegen
.ModuleCodeGenerator(tree
)