6abe1913a204d3bf7b6683e28fda08ae94fc4840
[soc.git] / src / soc / decoder / pseudo / parser.py
1 # Based on GardenSnake - a parser generator demonstration program
2 # GardenSnake was released into the Public Domain by Andrew Dalke.
3
4 # Portions of this work are derived from Python's Grammar definition
5 # and may be covered under the Python copyright and license
6 #
7 # Andrew Dalke / Dalke Scientific Software, LLC
8 # 30 August 2006 / Cape Town, South Africa
9
10 # Modifications for inclusion in PLY distribution
11 from pprint import pprint
12 from ply import lex, yacc
13 import astor
14
15 from soc.decoder.power_decoder import create_pdecode
16 from soc.decoder.pseudo.lexer import IndentLexer
17 from soc.decoder.orderedset import OrderedSet
18
19 # I use the Python AST
20 #from compiler import ast
21 import ast
22
23 # Helper function
24
25
26 def Assign(left, right):
27 names = []
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
38 names = []
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...
48 ls = left.slice
49 if isinstance(ls, ast.Slice):
50 lower, upper, step = ls.lower, ls.upper, ls.step
51 print("slice assign", lower, upper, step)
52 if step is None:
53 ls = (lower, upper, None)
54 else:
55 ls = (lower, upper, step)
56 ls = ast.Tuple(ls)
57 return ast.Call(ast.Name("selectassign"),
58 [left.value, ls, right], [])
59 else:
60 print("Assign fail")
61 raise SyntaxError("Can't do that yet")
62
63
64 # I implemented INDENT / DEDENT generation as a post-processing filter
65
66 # The original lex token stream contains WS and NEWLINE characters.
67 # WS will only occur before any other tokens on a line.
68
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.
74
75
76 # No using Python's approach because Ply supports precedence
77
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'
83
84 def make_le_compare(arg):
85 (left, right) = arg
86 return ast.Compare(left, [ast.LtE()], [right])
87
88
89 def make_ge_compare(arg):
90 (left, right) = arg
91 return ast.Compare(left, [ast.GtE()], [right])
92
93
94 def make_lt_compare(arg):
95 (left, right) = arg
96 return ast.Compare(left, [ast.Lt()], [right])
97
98
99 def make_gt_compare(arg):
100 (left, right) = arg
101 return ast.Compare(left, [ast.Gt()], [right])
102
103
104 def make_eq_compare(arg):
105 (left, right) = arg
106 return ast.Compare(left, [ast.Eq()], [right])
107
108
109 binary_ops = {
110 "&": ast.BitAnd(),
111 "|": ast.BitOr(),
112 "+": ast.Add(),
113 "-": ast.Sub(),
114 "*": ast.Mult(),
115 "/": ast.Div(),
116 "%": ast.Mod(),
117 "<=": make_le_compare,
118 ">=": make_ge_compare,
119 "<": make_lt_compare,
120 ">": make_gt_compare,
121 "=": make_eq_compare,
122 }
123 unary_ops = {
124 "+": ast.UAdd(),
125 "-": ast.USub(),
126 "¬": ast.Invert(),
127 }
128
129
130 def check_concat(node): # checks if the comparison is already a concat
131 print("check concat", node)
132 if not isinstance(node, ast.Call):
133 return [node]
134 print("func", node.func.id)
135 if node.func.id != 'concat':
136 return [node]
137 if node.keywords: # a repeated list-constant, don't optimise
138 return [node]
139 return node.args
140
141
142 # identify SelectableInt pattern
143 def identify_sint_mul_pattern(p):
144 if not isinstance(p[3], ast.Constant):
145 return False
146 if not isinstance(p[1], ast.List):
147 return False
148 l = p[1].elts
149 if len(l) != 1:
150 return False
151 elt = l[0]
152 return isinstance(elt, ast.Constant)
153
154 def apply_trailer(atom, trailer):
155 if trailer[0] == "TLIST":
156 # assume depth of one
157 atom = apply_trailer(atom, trailer[1])
158 trailer = trailer[2]
159 if trailer[0] == "CALL":
160 #p[0] = ast.Expr(ast.Call(p[1], p[2][1], []))
161 return ast.Call(atom, trailer[1], [])
162 # if p[1].id == 'print':
163 # p[0] = ast.Printnl(ast.Tuple(p[2][1]), None, None)
164 # else:
165 # p[0] = ast.CallFunc(p[1], p[2][1], None, None)
166 else:
167 print("subscript atom", trailer[1])
168 #raise AssertionError("not implemented %s" % p[2][0])
169 subs = trailer[1]
170 if len(subs) == 1:
171 idx = subs[0]
172 else:
173 idx = ast.Slice(subs[0], subs[1], None)
174 return ast.Subscript(atom, idx, ast.Load())
175
176 ########## Parser (tokens -> AST) ######
177
178 # also part of Ply
179 #import yacc
180
181 # https://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_precedence.html
182 # python operator precedence
183 # Highest precedence at top, lowest at bottom.
184 # Operators in the same box evaluate left to right.
185 #
186 # Operator Description
187 # () Parentheses (grouping)
188 # f(args...) Function call
189 # x[index:index] Slicing
190 # x[index] Subscription
191 # x.attribute Attribute reference
192 # ** Exponentiation
193 # ~x Bitwise not
194 # +x, -x Positive, negative
195 # *, /, % mul, div, remainder
196 # +, - Addition, subtraction
197 # <<, >> Bitwise shifts
198 # & Bitwise AND
199 # ^ Bitwise XOR
200 # | Bitwise OR
201 # in, not in, is, is not, <, <=, >, >=, <>, !=, == comp, membership, ident
202 # not x Boolean NOT
203 # and Boolean AND
204 # or Boolean OR
205 # lambda Lambda expression
206
207 class PowerParser:
208
209 precedence = (
210 ("left", "EQ", "GT", "LT", "LE", "GE", "LTU", "GTU"),
211 ("left", "BITOR"),
212 ("left", "BITAND"),
213 ("left", "PLUS", "MINUS"),
214 ("left", "MULT", "DIV", "MOD"),
215 ("left", "INVERT"),
216 )
217
218 def __init__(self):
219 self.gprs = {}
220 for rname in ['RA', 'RB', 'RC', 'RT', 'RS']:
221 self.gprs[rname] = None
222 self.read_regs = OrderedSet()
223 self.uninit_regs = OrderedSet()
224 self.write_regs = OrderedSet()
225
226 # The grammar comments come from Python's Grammar/Grammar file
227
228 # NB: compound_stmt in single_input is followed by extra NEWLINE!
229 # file_input: (NEWLINE | stmt)* ENDMARKER
230
231 def p_file_input_end(self, p):
232 """file_input_end : file_input ENDMARKER"""
233 print("end", p[1])
234 p[0] = p[1]
235
236 def p_file_input(self, p):
237 """file_input : file_input NEWLINE
238 | file_input stmt
239 | NEWLINE
240 | stmt"""
241 if isinstance(p[len(p)-1], str):
242 if len(p) == 3:
243 p[0] = p[1]
244 else:
245 p[0] = [] # p == 2 --> only a blank line
246 else:
247 if len(p) == 3:
248 p[0] = p[1] + p[2]
249 else:
250 p[0] = p[1]
251
252 # funcdef: [decorators] 'def' NAME parameters ':' suite
253 # ignoring decorators
254
255 def p_funcdef(self, p):
256 "funcdef : DEF NAME parameters COLON suite"
257 p[0] = ast.FunctionDef(p[2], p[3], p[5], ())
258
259 # parameters: '(' [varargslist] ')'
260 def p_parameters(self, p):
261 """parameters : LPAR RPAR
262 | LPAR varargslist RPAR"""
263 if len(p) == 3:
264 args = []
265 else:
266 args = p[2]
267 p[0] = ast.arguments(args=args, vararg=None, kwarg=None, defaults=[])
268
269 # varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] |
270 # '**' NAME) |
271 # highly simplified
272
273 def p_varargslist(self, p):
274 """varargslist : varargslist COMMA NAME
275 | NAME"""
276 if len(p) == 4:
277 p[0] = p[1] + p[3]
278 else:
279 p[0] = [p[1]]
280
281 # stmt: simple_stmt | compound_stmt
282 def p_stmt_simple(self, p):
283 """stmt : simple_stmt"""
284 # simple_stmt is a list
285 p[0] = p[1]
286
287 def p_stmt_compound(self, p):
288 """stmt : compound_stmt"""
289 p[0] = [p[1]]
290
291 # simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
292 def p_simple_stmt(self, p):
293 """simple_stmt : small_stmts NEWLINE
294 | small_stmts SEMICOLON NEWLINE"""
295 p[0] = p[1]
296
297 def p_small_stmts(self, p):
298 """small_stmts : small_stmts SEMICOLON small_stmt
299 | small_stmt"""
300 if len(p) == 4:
301 p[0] = p[1] + [p[3]]
302 else:
303 p[0] = [p[1]]
304
305 # small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
306 # import_stmt | global_stmt | exec_stmt | assert_stmt
307 def p_small_stmt(self, p):
308 """small_stmt : flow_stmt
309 | break_stmt
310 | expr_stmt"""
311 if isinstance(p[1], ast.Call):
312 p[0] = ast.Expr(p[1])
313 else:
314 p[0] = p[1]
315
316 # expr_stmt: testlist (augassign (yield_expr|testlist) |
317 # ('=' (yield_expr|testlist))*)
318 # augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
319 # '<<=' | '>>=' | '**=' | '//=')
320 def p_expr_stmt(self, p):
321 """expr_stmt : testlist ASSIGN testlist
322 | testlist """
323 print("expr_stmt", p)
324 if len(p) == 2:
325 # a list of expressions
326 #p[0] = ast.Discard(p[1])
327 p[0] = p[1]
328 else:
329 name = None
330 if isinstance(p[1], ast.Name):
331 name = p[1].id
332 elif isinstance(p[1], ast.Subscript):
333 name = p[1].value.id
334 if name in self.gprs:
335 # add to list of uninitialised
336 self.uninit_regs.add(name)
337 elif isinstance(p[1], ast.Call) and p[1].func.id == 'GPR':
338 print(astor.dump_tree(p[1]))
339 # replace GPR(x) with GPR[x]
340 idx = p[1].args[0]
341 p[1] = ast.Subscript(p[1].func, idx)
342 elif isinstance(p[1], ast.Call) and p[1].func.id == 'MEM':
343 print ("mem assign")
344 print(astor.dump_tree(p[1]))
345 p[1].func.id = "memassign" # change function name to set
346 p[1].args.append(p[3])
347 p[0] = p[1]
348 print ("mem rewrite")
349 print(astor.dump_tree(p[0]))
350 return
351 else:
352 print ("help, help")
353 print(astor.dump_tree(p[1]))
354 print("expr assign", name, p[1])
355 if name and name in self.gprs:
356 self.write_regs.add(name) # add to list of regs to write
357 p[0] = Assign(p[1], p[3])
358
359 def p_flow_stmt(self, p):
360 "flow_stmt : return_stmt"
361 p[0] = p[1]
362
363 # return_stmt: 'return' [testlist]
364 def p_return_stmt(self, p):
365 "return_stmt : RETURN testlist"
366 p[0] = ast.Return(p[2])
367
368 def p_compound_stmt(self, p):
369 """compound_stmt : if_stmt
370 | while_stmt
371 | for_stmt
372 | funcdef
373 """
374 p[0] = p[1]
375
376 def p_break_stmt(self, p):
377 """break_stmt : BREAK
378 """
379 p[0] = ast.Break()
380
381 def p_for_stmt(self, p):
382 """for_stmt : FOR test EQ test TO test COLON suite
383 """
384 p[0] = ast.While(p[2], p[4], [])
385 # auto-add-one (sigh) due to python range
386 start = p[4]
387 end = ast.BinOp(p[6], ast.Add(), ast.Constant(1))
388 it = ast.Call(ast.Name("range"), [start, end], [])
389 p[0] = ast.For(p[2], it, p[8], [])
390
391 def p_while_stmt(self, p):
392 """while_stmt : DO WHILE test COLON suite ELSE COLON suite
393 | DO WHILE test COLON suite
394 """
395 if len(p) == 6:
396 p[0] = ast.While(p[3], p[5], [])
397 else:
398 p[0] = ast.While(p[3], p[5], p[8])
399
400 def p_if_stmt(self, p):
401 """if_stmt : IF test COLON suite ELSE COLON if_stmt
402 | IF test COLON suite ELSE COLON suite
403 | IF test COLON suite
404 """
405 if len(p) == 8 and isinstance(p[7], ast.If):
406 p[0] = ast.If(p[2], p[4], [p[7]])
407 elif len(p) == 5:
408 p[0] = ast.If(p[2], p[4], [])
409 else:
410 p[0] = ast.If(p[2], p[4], p[7])
411
412 def p_suite(self, p):
413 """suite : simple_stmt
414 | NEWLINE INDENT stmts DEDENT"""
415 if len(p) == 2:
416 p[0] = p[1]
417 else:
418 p[0] = p[3]
419
420 def p_stmts(self, p):
421 """stmts : stmts stmt
422 | stmt"""
423 if len(p) == 3:
424 p[0] = p[1] + p[2]
425 else:
426 p[0] = p[1]
427
428 def p_comparison(self, p):
429 """comparison : comparison PLUS comparison
430 | comparison MINUS comparison
431 | comparison MULT comparison
432 | comparison DIV comparison
433 | comparison MOD comparison
434 | comparison EQ comparison
435 | comparison LE comparison
436 | comparison GE comparison
437 | comparison LTU comparison
438 | comparison GTU comparison
439 | comparison LT comparison
440 | comparison GT comparison
441 | comparison BITOR comparison
442 | comparison BITAND comparison
443 | PLUS comparison
444 | comparison MINUS
445 | INVERT comparison
446 | comparison APPEND comparison
447 | power"""
448 if len(p) == 4:
449 print(list(p))
450 if p[2] == '<u':
451 p[0] = ast.Call(ast.Name("ltu"), (p[1], p[3]), [])
452 elif p[2] == '>u':
453 p[0] = ast.Call(ast.Name("gtu"), (p[1], p[3]), [])
454 elif p[2] == '||':
455 l = check_concat(p[1]) + check_concat(p[3])
456 p[0] = ast.Call(ast.Name("concat"), l, [])
457 elif p[2] in ['<', '>', '=', '<=', '>=']:
458 p[0] = binary_ops[p[2]]((p[1], p[3]))
459 elif identify_sint_mul_pattern(p):
460 keywords=[ast.keyword(arg='repeat', value=p[3])]
461 l = p[1].elts
462 p[0] = ast.Call(ast.Name("concat"), l, keywords)
463 else:
464 p[0] = ast.BinOp(p[1], binary_ops[p[2]], p[3])
465 elif len(p) == 3:
466 if isinstance(p[2], str) and p[2] == '-':
467 p[0] = ast.UnaryOp(unary_ops[p[2]], p[1])
468 else:
469 p[0] = ast.UnaryOp(unary_ops[p[1]], p[2])
470 else:
471 p[0] = p[1]
472
473 # power: atom trailer* ['**' factor]
474 # trailers enables function calls (and subscripts).
475 # so this is 'trailerlist'
476 def p_power(self, p):
477 """power : atom
478 | atom trailerlist"""
479 if len(p) == 2:
480 p[0] = p[1]
481 else:
482 print("power dump atom")
483 print(astor.dump_tree(p[1]))
484 print("power dump trailerlist")
485 print(astor.dump_tree(p[2]))
486 p[0] = apply_trailer(p[1], p[2])
487
488 def p_atom_name(self, p):
489 """atom : NAME"""
490 p[0] = ast.Name(id=p[1], ctx=ast.Load())
491
492 def p_atom_number(self, p):
493 """atom : BINARY
494 | NUMBER
495 | STRING"""
496 p[0] = ast.Constant(p[1])
497
498 # '[' [listmaker] ']' |
499
500 def p_atom_listmaker(self, p):
501 """atom : LBRACK listmaker RBRACK"""
502 p[0] = p[2]
503
504 def p_listmaker(self, p):
505 """listmaker : test COMMA listmaker
506 | test
507 """
508 if len(p) == 2:
509 p[0] = ast.List([p[1]])
510 else:
511 p[0] = ast.List([p[1]] + p[3].nodes)
512
513 def p_atom_tuple(self, p):
514 """atom : LPAR testlist RPAR"""
515 print("tuple", p[2])
516 print("astor dump")
517 print(astor.dump_tree(p[2]))
518
519 if isinstance(p[2], ast.Name):
520 print("tuple name", p[2].id)
521 if p[2].id in self.gprs:
522 self.read_regs.add(p[2].id) # add to list of regs to read
523 #p[0] = ast.Subscript(ast.Name("GPR"), ast.Str(p[2].id))
524 # return
525 p[0] = p[2]
526 elif isinstance(p[2], ast.BinOp):
527 if isinstance(p[2].left, ast.Name) and \
528 isinstance(p[2].right, ast.Constant) and \
529 p[2].right.value == 0 and \
530 p[2].left.id in self.gprs:
531 rid = p[2].left.id
532 self.read_regs.add(rid) # add to list of regs to read
533 # create special call to GPR.getz
534 gprz = ast.Name("GPR")
535 gprz = ast.Attribute(gprz, "getz") # get testzero function
536 # *sigh* see class GPR. we need index itself not reg value
537 ridx = ast.Name("_%s" % rid)
538 p[0] = ast.Call(gprz, [ridx], [])
539 print("tree", astor.dump_tree(p[0]))
540 else:
541 p[0] = p[2]
542 else:
543 p[0] = p[2]
544
545 def p_trailerlist(self, p):
546 """trailerlist : trailer trailerlist
547 | trailer
548 """
549 if len(p) == 2:
550 p[0] = p[1]
551 else:
552 p[0] = ("TLIST", p[1], p[2])
553
554 # trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
555 def p_trailer(self, p):
556 """trailer : trailer_arglist
557 | trailer_subscript
558 """
559 p[0] = p[1]
560
561 def p_trailer_arglist(self, p):
562 "trailer_arglist : LPAR arglist RPAR"
563 p[0] = ("CALL", p[2])
564
565 def p_trailer_subscript(self, p):
566 "trailer_subscript : LBRACK subscript RBRACK"
567 p[0] = ("SUBS", p[2])
568
569 # subscript: '.' '.' '.' | test | [test] ':' [test]
570
571 def p_subscript(self, p):
572 """subscript : test COLON test
573 | test
574 """
575 if len(p) == 4:
576 # add one to end
577 if isinstance(p[3], ast.Constant):
578 end = ast.Constant(p[3].value+1)
579 else:
580 end = ast.BinOp(p[3], ast.Add(), ast.Constant(1))
581 p[0] = [p[1], end]
582 else:
583 p[0] = [p[1]]
584
585 # testlist: test (',' test)* [',']
586 # Contains shift/reduce error
587
588 def p_testlist(self, p):
589 """testlist : testlist_multi COMMA
590 | testlist_multi """
591 if len(p) == 2:
592 p[0] = p[1]
593 else:
594 # May need to promote singleton to tuple
595 if isinstance(p[1], list):
596 p[0] = p[1]
597 else:
598 p[0] = [p[1]]
599 # Convert into a tuple?
600 if isinstance(p[0], list):
601 p[0] = ast.Tuple(p[0])
602
603 def p_testlist_multi(self, p):
604 """testlist_multi : testlist_multi COMMA test
605 | test"""
606 if len(p) == 2:
607 # singleton
608 p[0] = p[1]
609 else:
610 if isinstance(p[1], list):
611 p[0] = p[1] + [p[3]]
612 else:
613 # singleton -> tuple
614 p[0] = [p[1], p[3]]
615
616 # test: or_test ['if' or_test 'else' test] | lambdef
617 # as I don't support 'and', 'or', and 'not' this works down to 'comparison'
618
619 def p_test(self, p):
620 "test : comparison"
621 p[0] = p[1]
622
623 # arglist: (argument ',')* (argument [',']| '*' test [',' '**' test]
624 # | '**' test)
625 # XXX INCOMPLETE: this doesn't allow the trailing comma
626
627 def p_arglist(self, p):
628 """arglist : arglist COMMA argument
629 | argument"""
630 if len(p) == 4:
631 p[0] = p[1] + [p[3]]
632 else:
633 p[0] = [p[1]]
634
635 # argument: test [gen_for] | test '=' test # Really [keyword '='] test
636 def p_argument(self, p):
637 "argument : test"
638 p[0] = p[1]
639
640 def p_error(self, p):
641 # print "Error!", repr(p)
642 raise SyntaxError(p)
643
644
645 class GardenSnakeParser(PowerParser):
646 def __init__(self, lexer=None):
647 PowerParser.__init__(self)
648 if lexer is None:
649 lexer = IndentLexer(debug=0)
650 self.lexer = lexer
651 self.tokens = lexer.tokens
652 self.parser = yacc.yacc(module=self, start="file_input_end",
653 debug=False, write_tables=False)
654
655 self.sd = create_pdecode()
656
657 def parse(self, code):
658 # self.lexer.input(code)
659 result = self.parser.parse(code, lexer=self.lexer, debug=False)
660 return ast.Module(result)
661
662
663 ###### Code generation ######
664
665 #from compiler import misc, syntax, pycodegen
666
667 class GardenSnakeCompiler(object):
668 def __init__(self):
669 self.parser = GardenSnakeParser()
670
671 def compile(self, code, mode="exec", filename="<string>"):
672 tree = self.parser.parse(code)
673 print("snake")
674 pprint(tree)
675 return tree
676 #misc.set_filename(filename, tree)
677 return compile(tree, mode="exec", filename="<string>")
678 # syntax.check(tree)
679 gen = pycodegen.ModuleCodeGenerator(tree)
680 code = gen.getCode()
681 return code