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