1 # Based on GardenSnake - a parser generator demonstration program
2 # GardenSnake was released into the Public Domain by Andrew Dalke.
4 # Portions of this work are derived from Python's Grammar definition
5 # and may be covered under the Python copyright and license
7 # Andrew Dalke / Dalke Scientific Software, LLC
8 # 30 August 2006 / Cape Town, South Africa
10 # Modifications for inclusion in PLY distribution
12 from pprint
import pprint
14 from ply
import lex
, yacc
30 'NUMBER', # Python decimals
31 'STRING', # single quoted strings only; syntax of raw strings
57 # taken from decmial.py but without the leading sign
59 r
"""(\d+(\.\d*)?|\.\d+)([eE][-+]? \d+)?"""
60 t
.value
= int(t
.value
)
64 r
"'([^\\']+|\\'|\\\\)*'" # I think this is right ...
65 t
.value
=t
.value
[1:-1].decode("string-escape") # .swapcase() # for fun
81 # Ply nicely documented how to do this.
94 r
'[a-zA-Z_][a-zA-Z0-9_]*'
95 t
.type = RESERVED
.get(t
.value
, "NAME")
98 # Putting this before t_WS let it consume lines with only comments in
99 # them so the latter code never sees the WS part. Not consuming the
100 # newline. Needed for "if 1: #comment"
102 r
"[ ]*\043[^\n]*" # \043 is '#'
109 if t
.lexer
.at_line_start
and t
.lexer
.paren_count
== 0 and \
110 t
.lexer
.brack_count
== 0:
113 # Don't generate newline tokens when inside of parenthesis, eg
118 t
.lexer
.lineno
+= len(t
.value
)
120 if t
.lexer
.paren_count
== 0 and t
.lexer
.brack_count
== 0:
125 t
.lexer
.brack_count
+= 1
130 # check for underflow? should be the job of the parser
131 t
.lexer
.brack_count
-= 1
136 t
.lexer
.paren_count
+= 1
141 # check for underflow? should be the job of the parser
142 t
.lexer
.paren_count
-= 1
148 raise SyntaxError("Unknown symbol %r" % (t
.value
[0],))
149 print ("Skipping", repr(t
.value
[0]))
152 ## I implemented INDENT / DEDENT generation as a post-processing filter
154 # The original lex token stream contains WS and NEWLINE characters.
155 # WS will only occur before any other tokens on a line.
157 # I have three filters. One tags tokens by adding two attributes.
158 # "must_indent" is True if the token must be indented from the
159 # previous code. The other is "at_line_start" which is True for WS
160 # and the first non-WS/non-NEWLINE on a line. It flags the check so
161 # see if the new line has changed indication level.
163 # Python's syntax has three INDENT states
164 # 0) no colon hence no need to indent
165 # 1) "if 1: go()" - simple statements have a COLON but no need for an indent
166 # 2) "if 1:\n go()" - complex statements have a COLON NEWLINE and must indent
171 # only care about whitespace at the start of a line
172 def track_tokens_filter(lexer
, tokens
):
173 oldignore
= lexer
.lexignore
174 lexer
.at_line_start
= at_line_start
= True
178 #print ("token", token)
179 token
.at_line_start
= at_line_start
181 if token
.type == "COLON":
182 at_line_start
= False
184 token
.must_indent
= False
186 elif token
.type == "NEWLINE":
188 if indent
== MAY_INDENT
:
190 token
.must_indent
= False
192 elif token
.type == "WS":
193 assert token
.at_line_start
== True
195 token
.must_indent
= False
198 # A real token; only indent after COLON NEWLINE
199 if indent
== MUST_INDENT
:
200 token
.must_indent
= True
202 token
.must_indent
= False
203 at_line_start
= False
206 # really bad hack that changes ignore lexer state.
207 # when "must indent" is seen (basically "real tokens" seen)
208 # then ignore whitespace.
209 if token
.must_indent
:
210 lexer
.lexignore
= ('ignore', ' ')
212 lexer
.lexignore
= oldignore
214 token
.indent
= indent
216 lexer
.at_line_start
= at_line_start
218 def _new_token(type, lineno
):
226 # Synthesize a DEDENT tag
228 return _new_token("DEDENT", lineno
)
230 # Synthesize an INDENT tag
232 return _new_token("INDENT", lineno
)
235 # Track the indentation level and emit the right INDENT / DEDENT events.
236 def indentation_filter(tokens
):
237 # A stack of indentation levels; will never pop item 0
244 print ("Process", depth
, token
.indent
, token
,)
245 if token
.at_line_start
:
246 print ("at_line_start",)
247 if token
.must_indent
:
248 print ("must_indent",)
251 # WS only occurs at the start of the line
252 # There may be WS followed by NEWLINE so
253 # only track the depth here. Don't indent/dedent
254 # until there's something real.
255 if token
.type == "WS":
257 depth
= len(token
.value
)
259 # WS tokens are never passed to the parser
262 if token
.type == "NEWLINE":
264 if prev_was_ws
or token
.at_line_start
:
267 # pass the other cases on through
271 # then it must be a real token (not WS, not NEWLINE)
272 # which can affect the indentation level
275 if token
.must_indent
:
276 # The current depth must be larger than the previous level
277 if not (depth
> levels
[-1]):
278 raise IndentationError("expected an indented block")
281 yield INDENT(token
.lineno
)
283 elif token
.at_line_start
:
284 # Must be on the same level or one of the previous levels
285 if depth
== levels
[-1]:
288 elif depth
> levels
[-1]:
289 raise IndentationError("indentation increase but not in new block")
291 # Back up; but only if it matches a previous level
293 i
= levels
.index(depth
)
295 raise IndentationError("inconsistent indentation")
296 for _
in range(i
+1, len(levels
)):
297 yield DEDENT(token
.lineno
)
302 ### Finished processing ###
304 # Must dedent any remaining levels
306 assert token
is not None
307 for _
in range(1, len(levels
)):
308 yield DEDENT(token
.lineno
)
311 # The top-level filter adds an ENDMARKER, if requested.
312 # Python's grammar uses it.
313 def filter(lexer
, add_endmarker
= True):
315 tokens
= iter(lexer
.token
, None)
316 tokens
= track_tokens_filter(lexer
, tokens
)
317 for token
in indentation_filter(tokens
):
322 if token
is not None:
323 lineno
= token
.lineno
324 yield _new_token("ENDMARKER", lineno
)
326 # Combine Ply and my filters into a new lexer
328 class IndentLexer(object):
329 def __init__(self
, debug
=0, optimize
=0, lextab
='lextab', reflags
=0):
330 self
.lexer
= lex
.lex(debug
=debug
, optimize
=optimize
, lextab
=lextab
, reflags
=reflags
)
331 self
.token_stream
= None
332 def input(self
, s
, add_endmarker
=True):
333 self
.lexer
.paren_count
= 0
334 self
.lexer
.brack_count
= 0
336 self
.token_stream
= filter(self
.lexer
, add_endmarker
)
339 return next(self
.token_stream
)
340 except StopIteration:
343 ########## Parser (tokens -> AST) ######
348 # I use the Python AST
349 #from compiler import ast
353 def Assign(left
, right
):
355 if isinstance(left
, ast
.Name
):
356 # Single assignment on left
357 return ast
.Assign([ast
.Name(left
.id, ast
.Store())], right
)
358 elif isinstance(left
, ast
.Tuple
):
359 # List of things - make sure they are Name nodes
361 for child
in left
.getChildren():
362 if not isinstance(child
, ast
.Name
):
363 raise SyntaxError("that assignment not supported")
364 names
.append(child
.name
)
365 ass_list
= [ast
.AssName(name
, 'OP_ASSIGN') for name
in names
]
366 return ast
.Assign([ast
.AssTuple(ass_list
)], right
)
368 raise SyntaxError("Can't do that yet")
371 # The grammar comments come from Python's Grammar/Grammar file
373 ## NB: compound_stmt in single_input is followed by extra NEWLINE!
374 # file_input: (NEWLINE | stmt)* ENDMARKER
375 def p_file_input_end(p
):
376 """file_input_end : file_input ENDMARKER"""
381 """file_input : file_input NEWLINE
385 if isinstance(p
[len(p
)-1], str):
389 p
[0] = [] # p == 2 --> only a blank line
397 # funcdef: [decorators] 'def' NAME parameters ':' suite
398 # ignoring decorators
400 "funcdef : DEF NAME parameters COLON suite"
401 p
[0] = ast
.Function(None, p
[2], list(p
[3]), (), 0, None, p
[5])
403 # parameters: '(' [varargslist] ')'
405 """parameters : LPAR RPAR
406 | LPAR varargslist RPAR"""
413 # varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] | '**' NAME) |
415 def p_varargslist(p
):
416 """varargslist : varargslist COMMA NAME
423 # stmt: simple_stmt | compound_stmt
424 def p_stmt_simple(p
):
425 """stmt : simple_stmt"""
426 # simple_stmt is a list
429 def p_stmt_compound(p
):
430 """stmt : compound_stmt"""
433 # simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
434 def p_simple_stmt(p
):
435 """simple_stmt : small_stmts NEWLINE
436 | small_stmts SEMICOLON NEWLINE"""
439 def p_small_stmts(p
):
440 """small_stmts : small_stmts SEMICOLON small_stmt
447 # small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
448 # import_stmt | global_stmt | exec_stmt | assert_stmt
450 """small_stmt : flow_stmt
454 # expr_stmt: testlist (augassign (yield_expr|testlist) |
455 # ('=' (yield_expr|testlist))*)
456 # augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
457 # '<<=' | '>>=' | '**=' | '//=')
459 """expr_stmt : testlist ASSIGN testlist
462 # a list of expressions
463 #p[0] = ast.Discard(p[1])
466 p
[0] = Assign(p
[1], p
[3])
469 "flow_stmt : return_stmt"
472 # return_stmt: 'return' [testlist]
473 def p_return_stmt(p
):
474 "return_stmt : RETURN testlist"
475 p
[0] = ast
.Return(p
[2])
478 def p_compound_stmt(p
):
479 """compound_stmt : if_stmt
486 """while_stmt : WHILE test COLON suite ELSE COLON suite
487 | WHILE test COLON suite
490 p
[0] = ast
.While(p
[2], p
[4], [])
492 p
[0] = ast
.While(p
[2], p
[4], p
[7])
495 """if_stmt : IF test COLON suite ELSE COLON suite
496 | IF test COLON suite
499 p
[0] = ast
.If(p
[2], p
[4], [])
501 p
[0] = ast
.If(p
[2], p
[4], p
[7])
504 """suite : simple_stmt
505 | NEWLINE INDENT stmts DEDENT"""
513 """stmts : stmts stmt
520 ## No using Python's approach because Ply supports precedence
522 # comparison: expr (comp_op expr)*
523 # arith_expr: term (('+'|'-') term)*
524 # term: factor (('*'|'/'|'%'|'//') factor)*
525 # factor: ('+'|'-'|'~') factor | power
526 # comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
528 def make_lt_compare(arg
):
530 return ast
.Compare(left
, [ast
.Lt()], [right
])
531 def make_gt_compare(arg
):
533 return ast
.Compare(left
, [ast
.Gt()], [right
])
534 def make_eq_compare(arg
):
536 return ast
.Compare(left
, [ast
.Eq()], [right
])
544 "<": make_lt_compare
,
545 ">": make_gt_compare
,
546 "==": make_eq_compare
,
553 ("left", "EQ", "GT", "LT"),
554 ("left", "PLUS", "MINUS"),
555 ("left", "MULT", "DIV"),
558 def check_concat(node
): # checks if the comparison is already a concat
560 if not isinstance(node
, ast
.Call
):
562 if node
[0].id != 'concat':
567 """comparison : comparison PLUS comparison
568 | comparison MINUS comparison
569 | comparison MULT comparison
570 | comparison DIV comparison
571 | comparison LT comparison
572 | comparison EQ comparison
573 | comparison GT comparison
576 | comparison APPEND comparison
581 l
= check_concat(p
[1]) + check_concat(p
[3])
582 p
[0] = ast
.Call(ast
.Name("concat"), l
, [])
583 elif p
[2] in ['<', '>', '==']:
584 p
[0] = binary_ops
[p
[2]]((p
[1],p
[3]))
586 p
[0] = ast
.BinOp(p
[1], binary_ops
[p
[2]], p
[3])
588 p
[0] = unary_ops
[p
[1]](p
[2])
592 # power: atom trailer* ['**' factor]
593 # trailers enables function calls (and subscripts).
594 # I only allow one level of calls
595 # so this is 'trailer'
602 if p
[2][0] == "CALL":
603 p
[0] = ast
.Expr(ast
.Call(p
[1], p
[2][1], []))
604 #if p[1].id == 'print':
605 # p[0] = ast.Printnl(ast.Tuple(p[2][1]), None, None)
607 # p[0] = ast.CallFunc(p[1], p[2][1], None, None)
610 #raise AssertionError("not implemented %s" % p[2][0])
615 idx
= ast
.Slice(subs
[0], subs
[1], None)
616 p
[0] = ast
.Subscript(p
[1], idx
)
620 p
[0] = ast
.Name(p
[1], ctx
=ast
.Load())
622 def p_atom_number(p
):
625 p
[0] = ast
.Constant(p
[1])
627 #'[' [listmaker] ']' |
629 def p_atom_listmaker(p
):
630 """atom : LBRACK listmaker RBRACK"""
634 """listmaker : test COMMA listmaker
638 p
[0] = ast
.List([p
[1]])
640 p
[0] = ast
.List([p
[1]] + p
[3].nodes
)
643 """atom : LPAR testlist RPAR"""
646 # trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
648 """trailer : trailer_arglist
653 def p_trailer_arglist(p
):
654 "trailer_arglist : LPAR arglist RPAR"
655 p
[0] = ("CALL", p
[2])
657 def p_trailer_subscript(p
):
658 "trailer_subscript : LBRACK subscript RBRACK"
659 p
[0] = ("SUBS", p
[2])
661 #subscript: '.' '.' '.' | test | [test] ':' [test]
664 """subscript : test COLON test
673 # testlist: test (',' test)* [',']
674 # Contains shift/reduce error
676 """testlist : testlist_multi COMMA
681 # May need to promote singleton to tuple
682 if isinstance(p
[1], list):
686 # Convert into a tuple?
687 if isinstance(p
[0], list):
688 p
[0] = ast
.Tuple(p
[0])
690 def p_testlist_multi(p
):
691 """testlist_multi : testlist_multi COMMA test
697 if isinstance(p
[1], list):
704 # test: or_test ['if' or_test 'else' test] | lambdef
705 # as I don't support 'and', 'or', and 'not' this works down to 'comparison'
712 # arglist: (argument ',')* (argument [',']| '*' test [',' '**' test] | '**' test)
713 # XXX INCOMPLETE: this doesn't allow the trailing comma
715 """arglist : arglist COMMA argument
722 # argument: test [gen_for] | test '=' test # Really [keyword '='] test
728 #print "Error!", repr(p)
732 class GardenSnakeParser(object):
733 def __init__(self
, lexer
= None):
735 lexer
= IndentLexer(debug
=1)
737 self
.parser
= yacc
.yacc(start
="file_input_end",
738 debug
=False, write_tables
=False)
740 def parse(self
, code
):
741 self
.lexer
.input(code
)
742 result
= self
.parser
.parse(lexer
= self
.lexer
, debug
=False)
743 return ast
.Module(result
)
746 ###### Code generation ######
748 #from compiler import misc, syntax, pycodegen
750 class GardenSnakeCompiler(object):
752 self
.parser
= GardenSnakeParser()
753 def compile(self
, code
, mode
="exec", filename
="<string>"):
754 tree
= self
.parser
.parse(code
)
758 #misc.set_filename(filename, tree)
759 return compile(tree
, mode
="exec", filename
="<string>")
761 gen
= pycodegen
.ModuleCodeGenerator(tree
)
765 ####### Test code #######
767 from soc
.decoder
.power_fieldsn
import create_sigdecode
771 index <- (RS)[8*i:8*i+7]
776 RA <- [0]*56|| perm[0:7]
782 index <- (RS)[8*i:8*i+7]
783 RA <- [0]*56 || perm[0:7]
789 lexer
= IndentLexer(debug
=1)
790 # Give the lexer some input
799 break # No more input
804 # Set up the GardenSnake run-time environment
807 print ("-->", " ".join(map(str,args
)))
813 sd
= create_sigdecode()
814 print ("forms", sd
.df
.forms
)
815 for f
in sd
.df
.FormX
:
818 _compile
= GardenSnakeCompiler().compile
820 tree
= _compile(code
, mode
="single", filename
="string")
822 tree
= ast
.fix_missing_locations(tree
)
823 print ( ast
.dump(tree
) )
826 print (astor
.dump_tree(tree
))
828 source
= astor
.to_source(tree
)
831 #from compiler import parse
832 #tree = parse(code, "exec")
834 print (compiled_code
)
836 exec (compiled_code
, d
)