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