add modulo to parser (and div to SelectableInt)
[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 return node.args
137
138
139 ########## Parser (tokens -> AST) ######
140
141 # also part of Ply
142 #import yacc
143
144 # https://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_precedence.html
145 # python operator precedence
146 # Highest precedence at top, lowest at bottom.
147 # Operators in the same box evaluate left to right.
148 #
149 # Operator Description
150 # () Parentheses (grouping)
151 # f(args...) Function call
152 # x[index:index] Slicing
153 # x[index] Subscription
154 # x.attribute Attribute reference
155 # ** Exponentiation
156 # ~x Bitwise not
157 # +x, -x Positive, negative
158 # *, /, % mul, div, remainder
159 # +, - Addition, subtraction
160 # <<, >> Bitwise shifts
161 # & Bitwise AND
162 # ^ Bitwise XOR
163 # | Bitwise OR
164 # in, not in, is, is not, <, <=, >, >=, <>, !=, == comp, membership, ident
165 # not x Boolean NOT
166 # and Boolean AND
167 # or Boolean OR
168 # lambda Lambda expression
169
170 class PowerParser:
171
172 precedence = (
173 ("left", "EQ", "GT", "LT", "LE", "GE", "LTU", "GTU"),
174 ("left", "BITOR"),
175 ("left", "BITAND"),
176 ("left", "PLUS", "MINUS"),
177 ("left", "MULT", "DIV", "MOD"),
178 ("left", "INVERT"),
179 )
180
181 def __init__(self):
182 self.gprs = {}
183 for rname in ['RA', 'RB', 'RC', 'RT', 'RS']:
184 self.gprs[rname] = None
185 self.read_regs = []
186 self.uninit_regs = []
187 self.write_regs = []
188
189 # The grammar comments come from Python's Grammar/Grammar file
190
191 # NB: compound_stmt in single_input is followed by extra NEWLINE!
192 # file_input: (NEWLINE | stmt)* ENDMARKER
193
194 def p_file_input_end(self, p):
195 """file_input_end : file_input ENDMARKER"""
196 print("end", p[1])
197 p[0] = p[1]
198
199 def p_file_input(self, p):
200 """file_input : file_input NEWLINE
201 | file_input stmt
202 | NEWLINE
203 | stmt"""
204 if isinstance(p[len(p)-1], str):
205 if len(p) == 3:
206 p[0] = p[1]
207 else:
208 p[0] = [] # p == 2 --> only a blank line
209 else:
210 if len(p) == 3:
211 p[0] = p[1] + p[2]
212 else:
213 p[0] = p[1]
214
215 # funcdef: [decorators] 'def' NAME parameters ':' suite
216 # ignoring decorators
217
218 def p_funcdef(self, p):
219 "funcdef : DEF NAME parameters COLON suite"
220 p[0] = ast.FunctionDef(p[2], p[3], p[5], ())
221
222 # parameters: '(' [varargslist] ')'
223 def p_parameters(self, p):
224 """parameters : LPAR RPAR
225 | LPAR varargslist RPAR"""
226 if len(p) == 3:
227 args = []
228 else:
229 args = p[2]
230 p[0] = ast.arguments(args=args, vararg=None, kwarg=None, defaults=[])
231
232 # varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] |
233 # '**' NAME) |
234 # highly simplified
235
236 def p_varargslist(self, p):
237 """varargslist : varargslist COMMA NAME
238 | NAME"""
239 if len(p) == 4:
240 p[0] = p[1] + p[3]
241 else:
242 p[0] = [p[1]]
243
244 # stmt: simple_stmt | compound_stmt
245 def p_stmt_simple(self, p):
246 """stmt : simple_stmt"""
247 # simple_stmt is a list
248 p[0] = p[1]
249
250 def p_stmt_compound(self, p):
251 """stmt : compound_stmt"""
252 p[0] = [p[1]]
253
254 # simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
255 def p_simple_stmt(self, p):
256 """simple_stmt : small_stmts NEWLINE
257 | small_stmts SEMICOLON NEWLINE"""
258 p[0] = p[1]
259
260 def p_small_stmts(self, p):
261 """small_stmts : small_stmts SEMICOLON small_stmt
262 | small_stmt"""
263 if len(p) == 4:
264 p[0] = p[1] + [p[3]]
265 else:
266 p[0] = [p[1]]
267
268 # small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
269 # import_stmt | global_stmt | exec_stmt | assert_stmt
270 def p_small_stmt(self, p):
271 """small_stmt : flow_stmt
272 | break_stmt
273 | expr_stmt"""
274 if isinstance(p[1], ast.Call):
275 p[0] = ast.Expr(p[1])
276 else:
277 p[0] = p[1]
278
279 # expr_stmt: testlist (augassign (yield_expr|testlist) |
280 # ('=' (yield_expr|testlist))*)
281 # augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
282 # '<<=' | '>>=' | '**=' | '//=')
283 def p_expr_stmt(self, p):
284 """expr_stmt : testlist ASSIGN testlist
285 | testlist """
286 print("expr_stmt", p)
287 if len(p) == 2:
288 # a list of expressions
289 #p[0] = ast.Discard(p[1])
290 p[0] = p[1]
291 else:
292 if isinstance(p[1], ast.Name):
293 name = p[1].id
294 elif isinstance(p[1], ast.Subscript):
295 name = p[1].value.id
296 if name in self.gprs:
297 # add to list of uninitialised
298 self.uninit_regs.append(name)
299 print("expr assign", name, p[1])
300 if name in self.gprs:
301 self.write_regs.append(name) # add to list of regs to write
302 p[0] = Assign(p[1], p[3])
303
304 def p_flow_stmt(self, p):
305 "flow_stmt : return_stmt"
306 p[0] = p[1]
307
308 # return_stmt: 'return' [testlist]
309 def p_return_stmt(self, p):
310 "return_stmt : RETURN testlist"
311 p[0] = ast.Return(p[2])
312
313 def p_compound_stmt(self, p):
314 """compound_stmt : if_stmt
315 | while_stmt
316 | for_stmt
317 | funcdef
318 """
319 p[0] = p[1]
320
321 def p_break_stmt(self, p):
322 """break_stmt : BREAK
323 """
324 p[0] = ast.Break()
325
326 def p_for_stmt(self, p):
327 """for_stmt : FOR test EQ test TO test COLON suite
328 """
329 p[0] = ast.While(p[2], p[4], [])
330 # auto-add-one (sigh) due to python range
331 start = p[4]
332 end = ast.BinOp(p[6], ast.Add(), ast.Constant(1))
333 it = ast.Call(ast.Name("range"), [start, end], [])
334 p[0] = ast.For(p[2], it, p[8], [])
335
336 def p_while_stmt(self, p):
337 """while_stmt : DO WHILE test COLON suite ELSE COLON suite
338 | DO WHILE test COLON suite
339 """
340 if len(p) == 6:
341 p[0] = ast.While(p[3], p[5], [])
342 else:
343 p[0] = ast.While(p[3], p[5], p[8])
344
345 def p_if_stmt(self, p):
346 """if_stmt : IF test COLON suite ELSE COLON if_stmt
347 | IF test COLON suite ELSE COLON suite
348 | IF test COLON suite
349 """
350 if len(p) == 8 and isinstance(p[7], ast.If):
351 p[0] = ast.If(p[2], p[4], [p[7]])
352 elif len(p) == 5:
353 p[0] = ast.If(p[2], p[4], [])
354 else:
355 p[0] = ast.If(p[2], p[4], p[7])
356
357 def p_suite(self, p):
358 """suite : simple_stmt
359 | NEWLINE INDENT stmts DEDENT"""
360 if len(p) == 2:
361 p[0] = p[1]
362 else:
363 p[0] = p[3]
364
365 def p_stmts(self, p):
366 """stmts : stmts stmt
367 | stmt"""
368 if len(p) == 3:
369 p[0] = p[1] + p[2]
370 else:
371 p[0] = p[1]
372
373 def p_comparison(self, p):
374 """comparison : comparison PLUS comparison
375 | comparison MINUS comparison
376 | comparison MULT comparison
377 | comparison DIV comparison
378 | comparison MOD comparison
379 | comparison EQ comparison
380 | comparison LE comparison
381 | comparison GE comparison
382 | comparison LTU comparison
383 | comparison GTU comparison
384 | comparison LT comparison
385 | comparison GT comparison
386 | comparison BITOR comparison
387 | comparison BITAND comparison
388 | PLUS comparison
389 | comparison MINUS
390 | INVERT comparison
391 | comparison APPEND comparison
392 | power"""
393 if len(p) == 4:
394 print(list(p))
395 if p[2] == '<u':
396 p[0] = ast.Call(ast.Name("ltu"), (p[1], p[3]), [])
397 elif p[2] == '>u':
398 p[0] = ast.Call(ast.Name("gtu"), (p[1], p[3]), [])
399 elif p[2] == '||':
400 l = check_concat(p[1]) + check_concat(p[3])
401 p[0] = ast.Call(ast.Name("concat"), l, [])
402 elif p[2] in ['<', '>', '=', '<=', '>=']:
403 p[0] = binary_ops[p[2]]((p[1], p[3]))
404 else:
405 p[0] = ast.BinOp(p[1], binary_ops[p[2]], p[3])
406 elif len(p) == 3:
407 if isinstance(p[2], str) and p[2] == '-':
408 p[0] = ast.UnaryOp(unary_ops[p[2]], p[1])
409 else:
410 p[0] = ast.UnaryOp(unary_ops[p[1]], p[2])
411 else:
412 p[0] = p[1]
413
414 # power: atom trailer* ['**' factor]
415 # trailers enables function calls (and subscripts).
416 # I only allow one level of calls
417 # so this is 'trailer'
418 def p_power(self, p):
419 """power : atom
420 | atom trailer"""
421 if len(p) == 2:
422 p[0] = p[1]
423 else:
424 if p[2][0] == "CALL":
425 #p[0] = ast.Expr(ast.Call(p[1], p[2][1], []))
426 p[0] = ast.Call(p[1], p[2][1], [])
427 # if p[1].id == 'print':
428 # p[0] = ast.Printnl(ast.Tuple(p[2][1]), None, None)
429 # else:
430 # p[0] = ast.CallFunc(p[1], p[2][1], None, None)
431 else:
432 print("subscript atom", p[2][1])
433 #raise AssertionError("not implemented %s" % p[2][0])
434 subs = p[2][1]
435 if len(subs) == 1:
436 idx = subs[0]
437 else:
438 idx = ast.Slice(subs[0], subs[1], None)
439 p[0] = ast.Subscript(p[1], idx, ast.Load())
440
441 def p_atom_name(self, p):
442 """atom : NAME"""
443 p[0] = ast.Name(id=p[1], ctx=ast.Load())
444
445 def p_atom_number(self, p):
446 """atom : BINARY
447 | NUMBER
448 | STRING"""
449 p[0] = ast.Constant(p[1])
450
451 # '[' [listmaker] ']' |
452
453 def p_atom_listmaker(self, p):
454 """atom : LBRACK listmaker RBRACK"""
455 p[0] = p[2]
456
457 def p_listmaker(self, p):
458 """listmaker : test COMMA listmaker
459 | test
460 """
461 if len(p) == 2:
462 p[0] = ast.List([p[1]])
463 else:
464 p[0] = ast.List([p[1]] + p[3].nodes)
465
466 def p_atom_tuple(self, p):
467 """atom : LPAR testlist RPAR"""
468 print("tuple", p[2])
469 if isinstance(p[2], ast.Name):
470 print("tuple name", p[2].id)
471 if p[2].id in self.gprs:
472 self.read_regs.append(p[2].id) # add to list of regs to read
473 #p[0] = ast.Subscript(ast.Name("GPR"), ast.Str(p[2].id))
474 # return
475 p[0] = p[2]
476
477 # trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
478 def p_trailer(self, p):
479 """trailer : trailer_arglist
480 | trailer_subscript
481 """
482 p[0] = p[1]
483
484 def p_trailer_arglist(self, p):
485 "trailer_arglist : LPAR arglist RPAR"
486 p[0] = ("CALL", p[2])
487
488 def p_trailer_subscript(self, p):
489 "trailer_subscript : LBRACK subscript RBRACK"
490 p[0] = ("SUBS", p[2])
491
492 # subscript: '.' '.' '.' | test | [test] ':' [test]
493
494 def p_subscript(self, p):
495 """subscript : test COLON test
496 | test
497 """
498 if len(p) == 4:
499 # add one to end
500 if isinstance(p[3], ast.Constant):
501 end = ast.Constant(p[3].value+1)
502 else:
503 end = ast.BinOp(p[3], ast.Add(), ast.Constant(1))
504 p[0] = [p[1], end]
505 else:
506 p[0] = [p[1]]
507
508 # testlist: test (',' test)* [',']
509 # Contains shift/reduce error
510
511 def p_testlist(self, p):
512 """testlist : testlist_multi COMMA
513 | testlist_multi """
514 if len(p) == 2:
515 p[0] = p[1]
516 else:
517 # May need to promote singleton to tuple
518 if isinstance(p[1], list):
519 p[0] = p[1]
520 else:
521 p[0] = [p[1]]
522 # Convert into a tuple?
523 if isinstance(p[0], list):
524 p[0] = ast.Tuple(p[0])
525
526 def p_testlist_multi(self, p):
527 """testlist_multi : testlist_multi COMMA test
528 | test"""
529 if len(p) == 2:
530 # singleton
531 p[0] = p[1]
532 else:
533 if isinstance(p[1], list):
534 p[0] = p[1] + [p[3]]
535 else:
536 # singleton -> tuple
537 p[0] = [p[1], p[3]]
538
539 # test: or_test ['if' or_test 'else' test] | lambdef
540 # as I don't support 'and', 'or', and 'not' this works down to 'comparison'
541
542 def p_test(self, p):
543 "test : comparison"
544 p[0] = p[1]
545
546 # arglist: (argument ',')* (argument [',']| '*' test [',' '**' test]
547 # | '**' test)
548 # XXX INCOMPLETE: this doesn't allow the trailing comma
549
550 def p_arglist(self, p):
551 """arglist : arglist COMMA argument
552 | argument"""
553 if len(p) == 4:
554 p[0] = p[1] + [p[3]]
555 else:
556 p[0] = [p[1]]
557
558 # argument: test [gen_for] | test '=' test # Really [keyword '='] test
559 def p_argument(self, p):
560 "argument : test"
561 p[0] = p[1]
562
563 def p_error(self, p):
564 # print "Error!", repr(p)
565 raise SyntaxError(p)
566
567
568 class GardenSnakeParser(PowerParser):
569 def __init__(self, lexer=None):
570 PowerParser.__init__(self)
571 if lexer is None:
572 lexer = IndentLexer(debug=0)
573 self.lexer = lexer
574 self.tokens = lexer.tokens
575 self.parser = yacc.yacc(module=self, start="file_input_end",
576 debug=False, write_tables=False)
577
578 self.sd = create_pdecode()
579
580 def parse(self, code):
581 # self.lexer.input(code)
582 result = self.parser.parse(code, lexer=self.lexer, debug=False)
583 return ast.Module(result)
584
585
586 ###### Code generation ######
587
588 #from compiler import misc, syntax, pycodegen
589
590 class GardenSnakeCompiler(object):
591 def __init__(self):
592 self.parser = GardenSnakeParser()
593
594 def compile(self, code, mode="exec", filename="<string>"):
595 tree = self.parser.parse(code)
596 print("snake")
597 pprint(tree)
598 return tree
599 #misc.set_filename(filename, tree)
600 return compile(tree, mode="exec", filename="<string>")
601 # syntax.check(tree)
602 gen = pycodegen.ModuleCodeGenerator(tree)
603 code = gen.getCode()
604 return code