identify [0]*16 pattern and produce repeat-of-int
[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
18 # I use the Python AST
19 #from compiler import ast
20 import ast
21
22 # Helper function
23
24
25 def Assign(left, right):
26 names = []
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
37 names = []
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...
47 ls = left.slice
48 if isinstance(ls, ast.Slice):
49 lower, upper, step = ls.lower, ls.upper, ls.step
50 print("slice assign", lower, upper, step)
51 if step is None:
52 ls = (lower, upper, None)
53 else:
54 ls = (lower, upper, step)
55 ls = ast.Tuple(ls)
56 return ast.Call(ast.Name("selectassign"),
57 [left.value, ls, right], [])
58 else:
59 print("Assign fail")
60 raise SyntaxError("Can't do that yet")
61
62
63 # I implemented INDENT / DEDENT generation as a post-processing filter
64
65 # The original lex token stream contains WS and NEWLINE characters.
66 # WS will only occur before any other tokens on a line.
67
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.
73
74
75 # No using Python's approach because Ply supports precedence
76
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'
82
83 def make_le_compare(arg):
84 (left, right) = arg
85 return ast.Compare(left, [ast.LtE()], [right])
86
87
88 def make_ge_compare(arg):
89 (left, right) = arg
90 return ast.Compare(left, [ast.GtE()], [right])
91
92
93 def make_lt_compare(arg):
94 (left, right) = arg
95 return ast.Compare(left, [ast.Lt()], [right])
96
97
98 def make_gt_compare(arg):
99 (left, right) = arg
100 return ast.Compare(left, [ast.Gt()], [right])
101
102
103 def make_eq_compare(arg):
104 (left, right) = arg
105 return ast.Compare(left, [ast.Eq()], [right])
106
107
108 binary_ops = {
109 "&": ast.BitAnd(),
110 "|": ast.BitOr(),
111 "+": ast.Add(),
112 "-": ast.Sub(),
113 "*": ast.Mult(),
114 "/": ast.Div(),
115 "%": ast.Mod(),
116 "<=": make_le_compare,
117 ">=": make_ge_compare,
118 "<": make_lt_compare,
119 ">": make_gt_compare,
120 "=": make_eq_compare,
121 }
122 unary_ops = {
123 "+": ast.UAdd(),
124 "-": ast.USub(),
125 "¬": ast.Invert(),
126 }
127
128
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):
132 return [node]
133 print("func", node.func.id)
134 if node.func.id != 'concat':
135 return [node]
136 if node.keywords: # a repeated list-constant, don't optimise
137 return [node]
138 return node.args
139
140
141 # identify SelectableInt pattern
142 def identify_sint_mul_pattern(p):
143 if not isinstance(p[3], ast.Constant):
144 return False
145 if not isinstance(p[1], ast.List):
146 return False
147 l = p[1].elts
148 if len(l) != 1:
149 return False
150 elt = l[0]
151 return isinstance(elt, ast.Constant)
152
153
154 ########## Parser (tokens -> AST) ######
155
156 # also part of Ply
157 #import yacc
158
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.
163 #
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
170 # ** Exponentiation
171 # ~x Bitwise not
172 # +x, -x Positive, negative
173 # *, /, % mul, div, remainder
174 # +, - Addition, subtraction
175 # <<, >> Bitwise shifts
176 # & Bitwise AND
177 # ^ Bitwise XOR
178 # | Bitwise OR
179 # in, not in, is, is not, <, <=, >, >=, <>, !=, == comp, membership, ident
180 # not x Boolean NOT
181 # and Boolean AND
182 # or Boolean OR
183 # lambda Lambda expression
184
185 class PowerParser:
186
187 precedence = (
188 ("left", "EQ", "GT", "LT", "LE", "GE", "LTU", "GTU"),
189 ("left", "BITOR"),
190 ("left", "BITAND"),
191 ("left", "PLUS", "MINUS"),
192 ("left", "MULT", "DIV", "MOD"),
193 ("left", "INVERT"),
194 )
195
196 def __init__(self):
197 self.gprs = {}
198 for rname in ['RA', 'RB', 'RC', 'RT', 'RS']:
199 self.gprs[rname] = None
200 self.read_regs = []
201 self.uninit_regs = []
202 self.write_regs = []
203
204 # The grammar comments come from Python's Grammar/Grammar file
205
206 # NB: compound_stmt in single_input is followed by extra NEWLINE!
207 # file_input: (NEWLINE | stmt)* ENDMARKER
208
209 def p_file_input_end(self, p):
210 """file_input_end : file_input ENDMARKER"""
211 print("end", p[1])
212 p[0] = p[1]
213
214 def p_file_input(self, p):
215 """file_input : file_input NEWLINE
216 | file_input stmt
217 | NEWLINE
218 | stmt"""
219 if isinstance(p[len(p)-1], str):
220 if len(p) == 3:
221 p[0] = p[1]
222 else:
223 p[0] = [] # p == 2 --> only a blank line
224 else:
225 if len(p) == 3:
226 p[0] = p[1] + p[2]
227 else:
228 p[0] = p[1]
229
230 # funcdef: [decorators] 'def' NAME parameters ':' suite
231 # ignoring decorators
232
233 def p_funcdef(self, p):
234 "funcdef : DEF NAME parameters COLON suite"
235 p[0] = ast.FunctionDef(p[2], p[3], p[5], ())
236
237 # parameters: '(' [varargslist] ')'
238 def p_parameters(self, p):
239 """parameters : LPAR RPAR
240 | LPAR varargslist RPAR"""
241 if len(p) == 3:
242 args = []
243 else:
244 args = p[2]
245 p[0] = ast.arguments(args=args, vararg=None, kwarg=None, defaults=[])
246
247 # varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] |
248 # '**' NAME) |
249 # highly simplified
250
251 def p_varargslist(self, p):
252 """varargslist : varargslist COMMA NAME
253 | NAME"""
254 if len(p) == 4:
255 p[0] = p[1] + p[3]
256 else:
257 p[0] = [p[1]]
258
259 # stmt: simple_stmt | compound_stmt
260 def p_stmt_simple(self, p):
261 """stmt : simple_stmt"""
262 # simple_stmt is a list
263 p[0] = p[1]
264
265 def p_stmt_compound(self, p):
266 """stmt : compound_stmt"""
267 p[0] = [p[1]]
268
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"""
273 p[0] = p[1]
274
275 def p_small_stmts(self, p):
276 """small_stmts : small_stmts SEMICOLON small_stmt
277 | small_stmt"""
278 if len(p) == 4:
279 p[0] = p[1] + [p[3]]
280 else:
281 p[0] = [p[1]]
282
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
287 | break_stmt
288 | expr_stmt"""
289 if isinstance(p[1], ast.Call):
290 p[0] = ast.Expr(p[1])
291 else:
292 p[0] = p[1]
293
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
300 | testlist """
301 print("expr_stmt", p)
302 if len(p) == 2:
303 # a list of expressions
304 #p[0] = ast.Discard(p[1])
305 p[0] = p[1]
306 else:
307 if isinstance(p[1], ast.Name):
308 name = p[1].id
309 elif isinstance(p[1], ast.Subscript):
310 name = p[1].value.id
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])
318
319 def p_flow_stmt(self, p):
320 "flow_stmt : return_stmt"
321 p[0] = p[1]
322
323 # return_stmt: 'return' [testlist]
324 def p_return_stmt(self, p):
325 "return_stmt : RETURN testlist"
326 p[0] = ast.Return(p[2])
327
328 def p_compound_stmt(self, p):
329 """compound_stmt : if_stmt
330 | while_stmt
331 | for_stmt
332 | funcdef
333 """
334 p[0] = p[1]
335
336 def p_break_stmt(self, p):
337 """break_stmt : BREAK
338 """
339 p[0] = ast.Break()
340
341 def p_for_stmt(self, p):
342 """for_stmt : FOR test EQ test TO test COLON suite
343 """
344 p[0] = ast.While(p[2], p[4], [])
345 # auto-add-one (sigh) due to python range
346 start = p[4]
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], [])
350
351 def p_while_stmt(self, p):
352 """while_stmt : DO WHILE test COLON suite ELSE COLON suite
353 | DO WHILE test COLON suite
354 """
355 if len(p) == 6:
356 p[0] = ast.While(p[3], p[5], [])
357 else:
358 p[0] = ast.While(p[3], p[5], p[8])
359
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
364 """
365 if len(p) == 8 and isinstance(p[7], ast.If):
366 p[0] = ast.If(p[2], p[4], [p[7]])
367 elif len(p) == 5:
368 p[0] = ast.If(p[2], p[4], [])
369 else:
370 p[0] = ast.If(p[2], p[4], p[7])
371
372 def p_suite(self, p):
373 """suite : simple_stmt
374 | NEWLINE INDENT stmts DEDENT"""
375 if len(p) == 2:
376 p[0] = p[1]
377 else:
378 p[0] = p[3]
379
380 def p_stmts(self, p):
381 """stmts : stmts stmt
382 | stmt"""
383 if len(p) == 3:
384 p[0] = p[1] + p[2]
385 else:
386 p[0] = p[1]
387
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
403 | PLUS comparison
404 | comparison MINUS
405 | INVERT comparison
406 | comparison APPEND comparison
407 | power"""
408 if len(p) == 4:
409 print(list(p))
410 if p[2] == '<u':
411 p[0] = ast.Call(ast.Name("ltu"), (p[1], p[3]), [])
412 elif p[2] == '>u':
413 p[0] = ast.Call(ast.Name("gtu"), (p[1], p[3]), [])
414 elif p[2] == '||':
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])]
421 l = p[1].elts
422 p[0] = ast.Call(ast.Name("concat"), l, keywords)
423 else:
424 p[0] = ast.BinOp(p[1], binary_ops[p[2]], p[3])
425 elif len(p) == 3:
426 if isinstance(p[2], str) and p[2] == '-':
427 p[0] = ast.UnaryOp(unary_ops[p[2]], p[1])
428 else:
429 p[0] = ast.UnaryOp(unary_ops[p[1]], p[2])
430 else:
431 p[0] = p[1]
432
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):
438 """power : atom
439 | atom trailer"""
440 if len(p) == 2:
441 p[0] = p[1]
442 else:
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)
448 # else:
449 # p[0] = ast.CallFunc(p[1], p[2][1], None, None)
450 else:
451 print("subscript atom", p[2][1])
452 #raise AssertionError("not implemented %s" % p[2][0])
453 subs = p[2][1]
454 if len(subs) == 1:
455 idx = subs[0]
456 else:
457 idx = ast.Slice(subs[0], subs[1], None)
458 p[0] = ast.Subscript(p[1], idx, ast.Load())
459
460 def p_atom_name(self, p):
461 """atom : NAME"""
462 p[0] = ast.Name(id=p[1], ctx=ast.Load())
463
464 def p_atom_number(self, p):
465 """atom : BINARY
466 | NUMBER
467 | STRING"""
468 p[0] = ast.Constant(p[1])
469
470 # '[' [listmaker] ']' |
471
472 def p_atom_listmaker(self, p):
473 """atom : LBRACK listmaker RBRACK"""
474 p[0] = p[2]
475
476 def p_listmaker(self, p):
477 """listmaker : test COMMA listmaker
478 | test
479 """
480 if len(p) == 2:
481 p[0] = ast.List([p[1]])
482 else:
483 p[0] = ast.List([p[1]] + p[3].nodes)
484
485 def p_atom_tuple(self, p):
486 """atom : LPAR testlist RPAR"""
487 print("tuple", p[2])
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))
493 # return
494 p[0] = p[2]
495
496 # trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
497 def p_trailer(self, p):
498 """trailer : trailer_arglist
499 | trailer_subscript
500 """
501 p[0] = p[1]
502
503 def p_trailer_arglist(self, p):
504 "trailer_arglist : LPAR arglist RPAR"
505 p[0] = ("CALL", p[2])
506
507 def p_trailer_subscript(self, p):
508 "trailer_subscript : LBRACK subscript RBRACK"
509 p[0] = ("SUBS", p[2])
510
511 # subscript: '.' '.' '.' | test | [test] ':' [test]
512
513 def p_subscript(self, p):
514 """subscript : test COLON test
515 | test
516 """
517 if len(p) == 4:
518 # add one to end
519 if isinstance(p[3], ast.Constant):
520 end = ast.Constant(p[3].value+1)
521 else:
522 end = ast.BinOp(p[3], ast.Add(), ast.Constant(1))
523 p[0] = [p[1], end]
524 else:
525 p[0] = [p[1]]
526
527 # testlist: test (',' test)* [',']
528 # Contains shift/reduce error
529
530 def p_testlist(self, p):
531 """testlist : testlist_multi COMMA
532 | testlist_multi """
533 if len(p) == 2:
534 p[0] = p[1]
535 else:
536 # May need to promote singleton to tuple
537 if isinstance(p[1], list):
538 p[0] = p[1]
539 else:
540 p[0] = [p[1]]
541 # Convert into a tuple?
542 if isinstance(p[0], list):
543 p[0] = ast.Tuple(p[0])
544
545 def p_testlist_multi(self, p):
546 """testlist_multi : testlist_multi COMMA test
547 | test"""
548 if len(p) == 2:
549 # singleton
550 p[0] = p[1]
551 else:
552 if isinstance(p[1], list):
553 p[0] = p[1] + [p[3]]
554 else:
555 # singleton -> tuple
556 p[0] = [p[1], p[3]]
557
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'
560
561 def p_test(self, p):
562 "test : comparison"
563 p[0] = p[1]
564
565 # arglist: (argument ',')* (argument [',']| '*' test [',' '**' test]
566 # | '**' test)
567 # XXX INCOMPLETE: this doesn't allow the trailing comma
568
569 def p_arglist(self, p):
570 """arglist : arglist COMMA argument
571 | argument"""
572 if len(p) == 4:
573 p[0] = p[1] + [p[3]]
574 else:
575 p[0] = [p[1]]
576
577 # argument: test [gen_for] | test '=' test # Really [keyword '='] test
578 def p_argument(self, p):
579 "argument : test"
580 p[0] = p[1]
581
582 def p_error(self, p):
583 # print "Error!", repr(p)
584 raise SyntaxError(p)
585
586
587 class GardenSnakeParser(PowerParser):
588 def __init__(self, lexer=None):
589 PowerParser.__init__(self)
590 if lexer is None:
591 lexer = IndentLexer(debug=0)
592 self.lexer = lexer
593 self.tokens = lexer.tokens
594 self.parser = yacc.yacc(module=self, start="file_input_end",
595 debug=False, write_tables=False)
596
597 self.sd = create_pdecode()
598
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)
603
604
605 ###### Code generation ######
606
607 #from compiler import misc, syntax, pycodegen
608
609 class GardenSnakeCompiler(object):
610 def __init__(self):
611 self.parser = GardenSnakeParser()
612
613 def compile(self, code, mode="exec", filename="<string>"):
614 tree = self.parser.parse(code)
615 print("snake")
616 pprint(tree)
617 return tree
618 #misc.set_filename(filename, tree)
619 return compile(tree, mode="exec", filename="<string>")
620 # syntax.check(tree)
621 gen = pycodegen.ModuleCodeGenerator(tree)
622 code = gen.getCode()
623 return code