add invert operator, fix unary ops
[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 def Assign(left, right):
24 names = []
25 print ("Assign", left, right)
26 if isinstance(left, ast.Name):
27 # Single assignment on left
28 # XXX when doing IntClass, which will have an "eq" function,
29 # this is how to access it
30 # eq = ast.Attribute(left, "eq") # get eq fn
31 # return ast.Call(eq, [right], []) # now call left.eq(right)
32 return ast.Assign([ast.Name(left.id, ast.Store())], right)
33 elif isinstance(left, ast.Tuple):
34 # List of things - make sure they are Name nodes
35 names = []
36 for child in left.getChildren():
37 if not isinstance(child, ast.Name):
38 raise SyntaxError("that assignment not supported")
39 names.append(child.name)
40 ass_list = [ast.AssName(name, 'OP_ASSIGN') for name in names]
41 return ast.Assign([ast.AssTuple(ass_list)], right)
42 elif isinstance(left, ast.Subscript):
43 return ast.Assign([left], right)
44 # XXX HMMM probably not needed...
45 ls = left.slice
46 if isinstance(ls, ast.Slice):
47 lower, upper, step = ls.lower, ls.upper, ls.step
48 print ("slice assign", lower, upper, step)
49 if step is None:
50 ls = (lower, upper, None)
51 else:
52 ls = (lower, upper, step)
53 ls = ast.Tuple(ls)
54 return ast.Call(ast.Name("selectassign"),
55 [left.value, ls, right], [])
56 else:
57 print ("Assign fail")
58 raise SyntaxError("Can't do that yet")
59
60
61 ## I implemented INDENT / DEDENT generation as a post-processing filter
62
63 # The original lex token stream contains WS and NEWLINE characters.
64 # WS will only occur before any other tokens on a line.
65
66 # I have three filters. One tags tokens by adding two attributes.
67 # "must_indent" is True if the token must be indented from the
68 # previous code. The other is "at_line_start" which is True for WS
69 # and the first non-WS/non-NEWLINE on a line. It flags the check so
70 # see if the new line has changed indication level.
71
72
73 ## No using Python's approach because Ply supports precedence
74
75 # comparison: expr (comp_op expr)*
76 # arith_expr: term (('+'|'-') term)*
77 # term: factor (('*'|'/'|'%'|'//') factor)*
78 # factor: ('+'|'-'|'~') factor | power
79 # comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
80
81 def make_le_compare(arg):
82 (left, right) = arg
83 return ast.Compare(left, [ast.LtE()], [right])
84 def make_ge_compare(arg):
85 (left, right) = arg
86 return ast.Compare(left, [ast.GtE()], [right])
87 def make_lt_compare(arg):
88 (left, right) = arg
89 return ast.Compare(left, [ast.Lt()], [right])
90 def make_gt_compare(arg):
91 (left, right) = arg
92 return ast.Compare(left, [ast.Gt()], [right])
93 def make_eq_compare(arg):
94 (left, right) = arg
95 return ast.Compare(left, [ast.Eq()], [right])
96
97 binary_ops = {
98 "&": ast.BitAnd(),
99 "|": ast.BitOr(),
100 "+": ast.Add(),
101 "-": ast.Sub(),
102 "*": ast.Mult(),
103 "/": ast.Div(),
104 "<=": make_le_compare,
105 ">=": make_ge_compare,
106 "<": make_lt_compare,
107 ">": make_gt_compare,
108 "=": make_eq_compare,
109 }
110 unary_ops = {
111 "+": ast.UAdd(),
112 "-": ast.USub(),
113 "¬": ast.Invert(),
114 }
115
116 def check_concat(node): # checks if the comparison is already a concat
117 print ("check concat", node)
118 if not isinstance(node, ast.Call):
119 return [node]
120 print ("func", node.func.id)
121 if node.func.id != 'concat':
122 return [node]
123 return node.args
124
125
126 ########## Parser (tokens -> AST) ######
127
128 # also part of Ply
129 #import yacc
130
131 class PowerParser:
132
133 precedence = (
134 ("left", "BITOR", "BITAND"),
135 ("left", "EQ", "GT", "LT", "LE", "GE", "LTU", "GTU"),
136 ("left", "PLUS", "MINUS"),
137 ("left", "MULT", "DIV"),
138 ("left", "INVERT"),
139 )
140
141 def __init__(self):
142 self.gprs = {}
143 for rname in ['RA', 'RB', 'RC', 'RT', 'RS']:
144 self.gprs[rname] = None
145 self.read_regs = []
146 self.uninit_regs = []
147 self.write_regs = []
148
149 # The grammar comments come from Python's Grammar/Grammar file
150
151 ## NB: compound_stmt in single_input is followed by extra NEWLINE!
152 # file_input: (NEWLINE | stmt)* ENDMARKER
153
154 def p_file_input_end(self, p):
155 """file_input_end : file_input ENDMARKER"""
156 print ("end", p[1])
157 p[0] = p[1]
158
159 def p_file_input(self, p):
160 """file_input : file_input NEWLINE
161 | file_input stmt
162 | NEWLINE
163 | stmt"""
164 if isinstance(p[len(p)-1], str):
165 if len(p) == 3:
166 p[0] = p[1]
167 else:
168 p[0] = [] # p == 2 --> only a blank line
169 else:
170 if len(p) == 3:
171 p[0] = p[1] + p[2]
172 else:
173 p[0] = p[1]
174
175
176 # funcdef: [decorators] 'def' NAME parameters ':' suite
177 # ignoring decorators
178 def p_funcdef(self, p):
179 "funcdef : DEF NAME parameters COLON suite"
180 p[0] = ast.FunctionDef(p[2], p[3], p[5], ())
181
182 # parameters: '(' [varargslist] ')'
183 def p_parameters(self, p):
184 """parameters : LPAR RPAR
185 | LPAR varargslist RPAR"""
186 if len(p) == 3:
187 args=[]
188 else:
189 args = p[2]
190 p[0] = ast.arguments(args=args, vararg=None, kwarg=None, defaults=[])
191
192
193 # varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] |
194 # '**' NAME) |
195 # highly simplified
196 def p_varargslist(self, p):
197 """varargslist : varargslist COMMA NAME
198 | NAME"""
199 if len(p) == 4:
200 p[0] = p[1] + p[3]
201 else:
202 p[0] = [p[1]]
203
204 # stmt: simple_stmt | compound_stmt
205 def p_stmt_simple(self, p):
206 """stmt : simple_stmt"""
207 # simple_stmt is a list
208 p[0] = p[1]
209
210 def p_stmt_compound(self, p):
211 """stmt : compound_stmt"""
212 p[0] = [p[1]]
213
214 # simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
215 def p_simple_stmt(self, p):
216 """simple_stmt : small_stmts NEWLINE
217 | small_stmts SEMICOLON NEWLINE"""
218 p[0] = p[1]
219
220 def p_small_stmts(self, p):
221 """small_stmts : small_stmts SEMICOLON small_stmt
222 | small_stmt"""
223 if len(p) == 4:
224 p[0] = p[1] + [p[3]]
225 else:
226 p[0] = [p[1]]
227
228 # small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
229 # import_stmt | global_stmt | exec_stmt | assert_stmt
230 def p_small_stmt(self, p):
231 """small_stmt : flow_stmt
232 | break_stmt
233 | expr_stmt"""
234 if isinstance(p[1], ast.Call):
235 p[0] = ast.Expr(p[1])
236 else:
237 p[0] = p[1]
238
239 # expr_stmt: testlist (augassign (yield_expr|testlist) |
240 # ('=' (yield_expr|testlist))*)
241 # augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
242 # '<<=' | '>>=' | '**=' | '//=')
243 def p_expr_stmt(self, p):
244 """expr_stmt : testlist ASSIGN testlist
245 | testlist """
246 print ("expr_stmt", p)
247 if len(p) == 2:
248 # a list of expressions
249 #p[0] = ast.Discard(p[1])
250 p[0] = p[1]
251 else:
252 if isinstance(p[1], ast.Name):
253 name = p[1].id
254 elif isinstance(p[1], ast.Subscript):
255 name = p[1].value.id
256 if name in self.gprs:
257 self.uninit_regs.append(name) # add to list of uninitialised
258 print ("expr assign", name, p[1])
259 if name in self.gprs:
260 self.write_regs.append(name) # add to list of regs to write
261 p[0] = Assign(p[1], p[3])
262
263 def p_flow_stmt(self, p):
264 "flow_stmt : return_stmt"
265 p[0] = p[1]
266
267 # return_stmt: 'return' [testlist]
268 def p_return_stmt(self, p):
269 "return_stmt : RETURN testlist"
270 p[0] = ast.Return(p[2])
271
272
273 def p_compound_stmt(self, p):
274 """compound_stmt : if_stmt
275 | while_stmt
276 | for_stmt
277 | funcdef
278 """
279 p[0] = p[1]
280
281 def p_break_stmt(self, p):
282 """break_stmt : BREAK
283 """
284 p[0] = ast.Break()
285
286 def p_for_stmt(self, p):
287 """for_stmt : FOR test EQ test TO test COLON suite
288 """
289 p[0] = ast.While(p[2], p[4], [])
290 # auto-add-one (sigh) due to python range
291 start = p[4]
292 end = ast.BinOp(p[6], ast.Add(), ast.Constant(1))
293 it = ast.Call(ast.Name("range"), [start, end], [])
294 p[0] = ast.For(p[2], it, p[8], [])
295
296 def p_while_stmt(self, p):
297 """while_stmt : DO WHILE test COLON suite ELSE COLON suite
298 | DO WHILE test COLON suite
299 """
300 if len(p) == 6:
301 p[0] = ast.While(p[3], p[5], [])
302 else:
303 p[0] = ast.While(p[3], p[5], p[8])
304
305 def p_if_stmt(self, p):
306 """if_stmt : IF test COLON suite ELSE COLON if_stmt
307 | IF test COLON suite ELSE COLON suite
308 | IF test COLON suite
309 """
310 if len(p) == 8 and isinstance(p[7], ast.If):
311 p[0] = ast.If(p[2], p[4], [p[7]])
312 elif len(p) == 5:
313 p[0] = ast.If(p[2], p[4], [])
314 else:
315 p[0] = ast.If(p[2], p[4], p[7])
316
317 def p_suite(self, p):
318 """suite : simple_stmt
319 | NEWLINE INDENT stmts DEDENT"""
320 if len(p) == 2:
321 p[0] = p[1]
322 else:
323 p[0] = p[3]
324
325
326 def p_stmts(self, p):
327 """stmts : stmts stmt
328 | stmt"""
329 if len(p) == 3:
330 p[0] = p[1] + p[2]
331 else:
332 p[0] = p[1]
333
334 def p_comparison(self, p):
335 """comparison : comparison PLUS comparison
336 | comparison MINUS comparison
337 | comparison MULT comparison
338 | comparison DIV comparison
339 | comparison EQ comparison
340 | comparison LE comparison
341 | comparison GE comparison
342 | comparison LTU comparison
343 | comparison GTU comparison
344 | comparison LT comparison
345 | comparison GT comparison
346 | comparison BITOR comparison
347 | comparison BITAND comparison
348 | PLUS comparison
349 | MINUS comparison
350 | INVERT comparison
351 | comparison APPEND comparison
352 | power"""
353 if len(p) == 4:
354 print (list(p))
355 if p[2] == '<u':
356 p[0] = ast.Call(ast.Name("ltu"), (p[1], p[3]), [])
357 elif p[2] == '>u':
358 p[0] = ast.Call(ast.Name("gtu"), (p[1], p[3]), [])
359 elif p[2] == '||':
360 l = check_concat(p[1]) + check_concat(p[3])
361 p[0] = ast.Call(ast.Name("concat"), l, [])
362 elif p[2] in ['<', '>', '=', '<=', '>=']:
363 p[0] = binary_ops[p[2]]((p[1],p[3]))
364 else:
365 p[0] = ast.BinOp(p[1], binary_ops[p[2]], p[3])
366 elif len(p) == 3:
367 p[0] = ast.UnaryOp(unary_ops[p[1]], p[2])
368 else:
369 p[0] = p[1]
370
371 # power: atom trailer* ['**' factor]
372 # trailers enables function calls (and subscripts).
373 # I only allow one level of calls
374 # so this is 'trailer'
375 def p_power(self, p):
376 """power : atom
377 | atom trailer"""
378 if len(p) == 2:
379 p[0] = p[1]
380 else:
381 if p[2][0] == "CALL":
382 #p[0] = ast.Expr(ast.Call(p[1], p[2][1], []))
383 p[0] = ast.Call(p[1], p[2][1], [])
384 #if p[1].id == 'print':
385 # p[0] = ast.Printnl(ast.Tuple(p[2][1]), None, None)
386 #else:
387 # p[0] = ast.CallFunc(p[1], p[2][1], None, None)
388 else:
389 print ("subscript atom", p[2][1])
390 #raise AssertionError("not implemented %s" % p[2][0])
391 subs = p[2][1]
392 if len(subs) == 1:
393 idx = subs[0]
394 else:
395 idx = ast.Slice(subs[0], subs[1], None)
396 p[0] = ast.Subscript(p[1], idx)
397
398 def p_atom_name(self, p):
399 """atom : NAME"""
400 p[0] = ast.Name(p[1], ctx=ast.Load())
401
402 def p_atom_number(self, p):
403 """atom : BINARY
404 | NUMBER
405 | STRING"""
406 p[0] = ast.Constant(p[1])
407
408 #'[' [listmaker] ']' |
409
410 def p_atom_listmaker(self, p):
411 """atom : LBRACK listmaker RBRACK"""
412 p[0] = p[2]
413
414 def p_listmaker(self, p):
415 """listmaker : test COMMA listmaker
416 | test
417 """
418 if len(p) == 2:
419 p[0] = ast.List([p[1]])
420 else:
421 p[0] = ast.List([p[1]] + p[3].nodes)
422
423 def p_atom_tuple(self, p):
424 """atom : LPAR testlist RPAR"""
425 print ("tuple", p[2])
426 if isinstance(p[2], ast.Name):
427 print ("tuple name", p[2].id)
428 if p[2].id in self.gprs:
429 self.read_regs.append(p[2].id) # add to list of regs to read
430 #p[0] = ast.Subscript(ast.Name("GPR"), ast.Str(p[2].id))
431 #return
432 p[0] = p[2]
433
434 # trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
435 def p_trailer(self, p):
436 """trailer : trailer_arglist
437 | trailer_subscript
438 """
439 p[0] = p[1]
440
441 def p_trailer_arglist(self, p):
442 "trailer_arglist : LPAR arglist RPAR"
443 p[0] = ("CALL", p[2])
444
445 def p_trailer_subscript(self, p):
446 "trailer_subscript : LBRACK subscript RBRACK"
447 p[0] = ("SUBS", p[2])
448
449 #subscript: '.' '.' '.' | test | [test] ':' [test]
450
451 def p_subscript(self, p):
452 """subscript : test COLON test
453 | test
454 """
455 if len(p) == 4:
456 # add one to end
457 if isinstance(p[3], ast.Constant):
458 end = ast.Constant(p[3].value+1)
459 else:
460 end = ast.BinOp(p[3], ast.Add(), ast.Constant(1))
461 p[0] = [p[1], end]
462 else:
463 p[0] = [p[1]]
464
465
466 # testlist: test (',' test)* [',']
467 # Contains shift/reduce error
468 def p_testlist(self, p):
469 """testlist : testlist_multi COMMA
470 | testlist_multi """
471 if len(p) == 2:
472 p[0] = p[1]
473 else:
474 # May need to promote singleton to tuple
475 if isinstance(p[1], list):
476 p[0] = p[1]
477 else:
478 p[0] = [p[1]]
479 # Convert into a tuple?
480 if isinstance(p[0], list):
481 p[0] = ast.Tuple(p[0])
482
483 def p_testlist_multi(self, p):
484 """testlist_multi : testlist_multi COMMA test
485 | test"""
486 if len(p) == 2:
487 # singleton
488 p[0] = p[1]
489 else:
490 if isinstance(p[1], list):
491 p[0] = p[1] + [p[3]]
492 else:
493 # singleton -> tuple
494 p[0] = [p[1], p[3]]
495
496
497 # test: or_test ['if' or_test 'else' test] | lambdef
498 # as I don't support 'and', 'or', and 'not' this works down to 'comparison'
499 def p_test(self, p):
500 "test : comparison"
501 p[0] = p[1]
502
503
504
505 # arglist: (argument ',')* (argument [',']| '*' test [',' '**' test]
506 # | '**' test)
507 # XXX INCOMPLETE: this doesn't allow the trailing comma
508 def p_arglist(self, p):
509 """arglist : arglist COMMA argument
510 | argument"""
511 if len(p) == 4:
512 p[0] = p[1] + [p[3]]
513 else:
514 p[0] = [p[1]]
515
516 # argument: test [gen_for] | test '=' test # Really [keyword '='] test
517 def p_argument(self, p):
518 "argument : test"
519 p[0] = p[1]
520
521 def p_error(self, p):
522 #print "Error!", repr(p)
523 raise SyntaxError(p)
524
525
526 class GardenSnakeParser(PowerParser):
527 def __init__(self, lexer = None):
528 PowerParser.__init__(self)
529 if lexer is None:
530 lexer = IndentLexer(debug=0)
531 self.lexer = lexer
532 self.tokens = lexer.tokens
533 self.parser = yacc.yacc(module=self, start="file_input_end",
534 debug=False, write_tables=False)
535
536 self.sd = create_pdecode()
537
538 def parse(self, code):
539 #self.lexer.input(code)
540 result = self.parser.parse(code, lexer=self.lexer, debug=False)
541 return ast.Module(result)
542
543
544 ###### Code generation ######
545
546 #from compiler import misc, syntax, pycodegen
547
548 class GardenSnakeCompiler(object):
549 def __init__(self):
550 self.parser = GardenSnakeParser()
551
552 def compile(self, code, mode="exec", filename="<string>"):
553 tree = self.parser.parse(code)
554 print ("snake")
555 pprint(tree)
556 return tree
557 #misc.set_filename(filename, tree)
558 return compile(tree, mode="exec", filename="<string>")
559 #syntax.check(tree)
560 gen = pycodegen.ModuleCodeGenerator(tree)
561 code = gen.getCode()
562 return code
563