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