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
17 # I use the Python AST
18 #from compiler import ast
22 def Assign(left
, right
):
24 if isinstance(left
, ast
.Name
):
25 # Single assignment on left
26 return ast
.Assign([ast
.Name(left
.id, ast
.Store())], right
)
27 elif isinstance(left
, ast
.Tuple
):
28 # List of things - make sure they are Name nodes
30 for child
in left
.getChildren():
31 if not isinstance(child
, ast
.Name
):
32 raise SyntaxError("that assignment not supported")
33 names
.append(child
.name
)
34 ass_list
= [ast
.AssName(name
, 'OP_ASSIGN') for name
in names
]
35 return ast
.Assign([ast
.AssTuple(ass_list
)], right
)
37 raise SyntaxError("Can't do that yet")
40 ## I implemented INDENT / DEDENT generation as a post-processing filter
42 # The original lex token stream contains WS and NEWLINE characters.
43 # WS will only occur before any other tokens on a line.
45 # I have three filters. One tags tokens by adding two attributes.
46 # "must_indent" is True if the token must be indented from the
47 # previous code. The other is "at_line_start" which is True for WS
48 # and the first non-WS/non-NEWLINE on a line. It flags the check so
49 # see if the new line has changed indication level.
51 # Python's syntax has three INDENT states
52 # 0) no colon hence no need to indent
53 # 1) "if 1: go()" - simple statements have a COLON but no need for an indent
54 # 2) "if 1:\n go()" - complex statements have a COLON NEWLINE and must indent
59 # turn into python-like colon syntax from pseudo-code syntax
60 def python_colonify(lexer
, tokens
):
64 #print ("track colon token", token, token.type)
66 if token
.type == 'THEN':
67 # turn then into colon
70 elif token
.type == 'ELSE':
75 elif token
.type in ['WHILE', 'FOR']:
78 elif token
.type == 'NEWLINE':
89 # only care about whitespace at the start of a line
90 def track_tokens_filter(lexer
, tokens
):
91 oldignore
= lexer
.lexignore
92 lexer
.at_line_start
= at_line_start
= True
96 #print ("track token", token, token.type)
97 token
.at_line_start
= at_line_start
99 if token
.type == "COLON":
100 at_line_start
= False
102 token
.must_indent
= False
104 elif token
.type == "NEWLINE":
106 if indent
== MAY_INDENT
:
108 token
.must_indent
= False
110 elif token
.type == "WS":
111 assert token
.at_line_start
== True
113 token
.must_indent
= False
116 # A real token; only indent after COLON NEWLINE
117 if indent
== MUST_INDENT
:
118 token
.must_indent
= True
120 token
.must_indent
= False
121 at_line_start
= False
124 # really bad hack that changes ignore lexer state.
125 # when "must indent" is seen (basically "real tokens" seen)
126 # then ignore whitespace.
127 if token
.must_indent
:
128 lexer
.lexignore
= ('ignore', ' ')
130 lexer
.lexignore
= oldignore
132 token
.indent
= indent
134 lexer
.at_line_start
= at_line_start
136 def _new_token(type, lineno
):
144 # Synthesize a DEDENT tag
146 return _new_token("DEDENT", lineno
)
148 # Synthesize an INDENT tag
150 return _new_token("INDENT", lineno
)
153 # Track the indentation level and emit the right INDENT / DEDENT events.
154 def indentation_filter(tokens
):
155 # A stack of indentation levels; will never pop item 0
162 print ("Process", depth
, token
.indent
, token
,)
163 if token
.at_line_start
:
164 print ("at_line_start",)
165 if token
.must_indent
:
166 print ("must_indent",)
169 # WS only occurs at the start of the line
170 # There may be WS followed by NEWLINE so
171 # only track the depth here. Don't indent/dedent
172 # until there's something real.
173 if token
.type == "WS":
175 depth
= len(token
.value
)
177 # WS tokens are never passed to the parser
180 if token
.type == "NEWLINE":
182 if prev_was_ws
or token
.at_line_start
:
185 # pass the other cases on through
189 # then it must be a real token (not WS, not NEWLINE)
190 # which can affect the indentation level
193 if token
.must_indent
:
194 # The current depth must be larger than the previous level
195 if not (depth
> levels
[-1]):
196 raise IndentationError("expected an indented block")
199 yield INDENT(token
.lineno
)
201 elif token
.at_line_start
:
202 # Must be on the same level or one of the previous levels
203 if depth
== levels
[-1]:
206 elif depth
> levels
[-1]:
207 raise IndentationError("indentation increase but not in new block")
209 # Back up; but only if it matches a previous level
211 i
= levels
.index(depth
)
213 raise IndentationError("inconsistent indentation")
214 for _
in range(i
+1, len(levels
)):
215 yield DEDENT(token
.lineno
)
220 ### Finished processing ###
222 # Must dedent any remaining levels
224 assert token
is not None
225 for _
in range(1, len(levels
)):
226 yield DEDENT(token
.lineno
)
229 # The top-level filter adds an ENDMARKER, if requested.
230 # Python's grammar uses it.
231 def filter(lexer
, add_endmarker
= True):
233 tokens
= iter(lexer
.token
, None)
234 tokens
= python_colonify(lexer
, tokens
)
235 tokens
= track_tokens_filter(lexer
, tokens
)
236 for token
in indentation_filter(tokens
):
241 if token
is not None:
242 lineno
= token
.lineno
243 yield _new_token("ENDMARKER", lineno
)
245 ## No using Python's approach because Ply supports precedence
247 # comparison: expr (comp_op expr)*
248 # arith_expr: term (('+'|'-') term)*
249 # term: factor (('*'|'/'|'%'|'//') factor)*
250 # factor: ('+'|'-'|'~') factor | power
251 # comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
253 def make_lt_compare(arg
):
255 return ast
.Compare(left
, [ast
.Lt()], [right
])
256 def make_gt_compare(arg
):
258 return ast
.Compare(left
, [ast
.Gt()], [right
])
259 def make_eq_compare(arg
):
261 return ast
.Compare(left
, [ast
.Eq()], [right
])
269 "<": make_lt_compare
,
270 ">": make_gt_compare
,
271 "=": make_eq_compare
,
278 ("left", "EQ", "GT", "LT"),
279 ("left", "PLUS", "MINUS"),
280 ("left", "MULT", "DIV"),
283 def check_concat(node
): # checks if the comparison is already a concat
285 if not isinstance(node
, ast
.Call
):
287 if node
[0].id != 'concat':
306 'NUMBER', # Python decimals
307 'BINARY', # Python binary
308 'STRING', # single quoted strings only; syntax of raw strings
334 def build(self
,**kwargs
):
335 self
.lexer
= lex
.lex(module
=self
, **kwargs
)
337 def t_BINARY(self
, t
):
339 t
.value
= int(t
.value
, 2)
343 # taken from decmial.py but without the leading sign
344 def t_NUMBER(self
, t
):
345 r
"""(\d+(\.\d*)?|\.\d+)([eE][-+]? \d+)?"""
346 t
.value
= int(t
.value
)
349 def t_STRING(self
, t
):
350 r
"'([^\\']+|\\'|\\\\)*'" # I think this is right ...
351 t
.value
=t
.value
[1:-1].decode("string-escape") # .swapcase() # for fun
367 # Ply nicely documented how to do this.
383 r
'[a-zA-Z_][a-zA-Z0-9_]*'
384 t
.type = self
.RESERVED
.get(t
.value
, "NAME")
387 # Putting this before t_WS let it consume lines with only comments in
388 # them so the latter code never sees the WS part. Not consuming the
389 # newline. Needed for "if 1: #comment"
390 def t_comment(self
, t
):
391 r
"[ ]*\043[^\n]*" # \043 is '#'
398 if t
.lexer
.at_line_start
and t
.lexer
.paren_count
== 0 and \
399 t
.lexer
.brack_count
== 0:
402 # Don't generate newline tokens when inside of parenthesis, eg
405 def t_newline(self
, t
):
407 t
.lexer
.lineno
+= len(t
.value
)
409 if t
.lexer
.paren_count
== 0 and t
.lexer
.brack_count
== 0:
412 def t_LBRACK(self
, t
):
414 t
.lexer
.brack_count
+= 1
417 def t_RBRACK(self
, t
):
419 # check for underflow? should be the job of the parser
420 t
.lexer
.brack_count
-= 1
425 t
.lexer
.paren_count
+= 1
430 # check for underflow? should be the job of the parser
431 t
.lexer
.paren_count
-= 1
436 def t_error(self
, t
):
437 raise SyntaxError("Unknown symbol %r" % (t
.value
[0],))
438 print ("Skipping", repr(t
.value
[0]))
441 # Combine Ply and my filters into a new lexer
443 class IndentLexer(PowerLexer
):
444 def __init__(self
, debug
=0, optimize
=0, lextab
='lextab', reflags
=0):
445 self
.build(debug
=debug
, optimize
=optimize
,
446 lextab
=lextab
, reflags
=reflags
)
447 self
.token_stream
= None
448 def input(self
, s
, add_endmarker
=True):
449 self
.lexer
.paren_count
= 0
450 self
.lexer
.brack_count
= 0
452 self
.token_stream
= filter(self
.lexer
, add_endmarker
)
456 return next(self
.token_stream
)
457 except StopIteration:
461 ########## Parser (tokens -> AST) ######
468 # The grammar comments come from Python's Grammar/Grammar file
470 ## NB: compound_stmt in single_input is followed by extra NEWLINE!
471 # file_input: (NEWLINE | stmt)* ENDMARKER
473 def p_file_input_end(self
, p
):
474 """file_input_end : file_input ENDMARKER"""
478 def p_file_input(self
, p
):
479 """file_input : file_input NEWLINE
483 if isinstance(p
[len(p
)-1], str):
487 p
[0] = [] # p == 2 --> only a blank line
495 # funcdef: [decorators] 'def' NAME parameters ':' suite
496 # ignoring decorators
497 def p_funcdef(self
, p
):
498 "funcdef : DEF NAME parameters COLON suite"
499 p
[0] = ast
.Function(None, p
[2], list(p
[3]), (), 0, None, p
[5])
501 # parameters: '(' [varargslist] ')'
502 def p_parameters(self
, p
):
503 """parameters : LPAR RPAR
504 | LPAR varargslist RPAR"""
511 # varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] | '**' NAME) |
513 def p_varargslist(self
, p
):
514 """varargslist : varargslist COMMA NAME
521 # stmt: simple_stmt | compound_stmt
522 def p_stmt_simple(self
, p
):
523 """stmt : simple_stmt"""
524 # simple_stmt is a list
527 def p_stmt_compound(self
, p
):
528 """stmt : compound_stmt"""
531 # simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
532 def p_simple_stmt(self
, p
):
533 """simple_stmt : small_stmts NEWLINE
534 | small_stmts SEMICOLON NEWLINE"""
537 def p_small_stmts(self
, p
):
538 """small_stmts : small_stmts SEMICOLON small_stmt
545 # small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
546 # import_stmt | global_stmt | exec_stmt | assert_stmt
547 def p_small_stmt(self
, p
):
548 """small_stmt : flow_stmt
553 # expr_stmt: testlist (augassign (yield_expr|testlist) |
554 # ('=' (yield_expr|testlist))*)
555 # augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
556 # '<<=' | '>>=' | '**=' | '//=')
557 def p_expr_stmt(self
, p
):
558 """expr_stmt : testlist ASSIGN testlist
561 # a list of expressions
562 #p[0] = ast.Discard(p[1])
565 p
[0] = Assign(p
[1], p
[3])
567 def p_flow_stmt(self
, p
):
568 "flow_stmt : return_stmt"
571 # return_stmt: 'return' [testlist]
572 def p_return_stmt(self
, p
):
573 "return_stmt : RETURN testlist"
574 p
[0] = ast
.Return(p
[2])
577 def p_compound_stmt(self
, p
):
578 """compound_stmt : if_stmt
585 def p_break_stmt(self
, p
):
586 """break_stmt : BREAK
590 def p_for_stmt(self
, p
):
591 """for_stmt : FOR test EQ test TO test COLON suite
593 p
[0] = ast
.While(p
[2], p
[4], [])
594 # auto-add-one (sigh) due to python range
596 end
= ast
.BinOp(p
[6], ast
.Add(), ast
.Constant(1))
597 it
= ast
.Call(ast
.Name("range"), [start
, end
], [])
598 p
[0] = ast
.For(p
[2], it
, p
[8], [])
600 def p_while_stmt(self
, p
):
601 """while_stmt : DO WHILE test COLON suite ELSE COLON suite
602 | DO WHILE test COLON suite
605 p
[0] = ast
.While(p
[3], p
[5], [])
607 p
[0] = ast
.While(p
[3], p
[5], p
[8])
609 def p_if_stmt(self
, p
):
610 """if_stmt : IF test COLON suite ELSE COLON suite
611 | IF test COLON suite
614 p
[0] = ast
.If(p
[2], p
[4], [])
616 p
[0] = ast
.If(p
[2], p
[4], p
[7])
618 def p_suite(self
, p
):
619 """suite : simple_stmt
620 | NEWLINE INDENT stmts DEDENT"""
627 def p_stmts(self
, p
):
628 """stmts : stmts stmt
635 def p_comparison(self
, p
):
636 """comparison : comparison PLUS comparison
637 | comparison MINUS comparison
638 | comparison MULT comparison
639 | comparison DIV comparison
640 | comparison LT comparison
641 | comparison EQ comparison
642 | comparison GT comparison
645 | comparison APPEND comparison
650 l
= check_concat(p
[1]) + check_concat(p
[3])
651 p
[0] = ast
.Call(ast
.Name("concat"), l
, [])
652 elif p
[2] in ['<', '>', '=']:
653 p
[0] = binary_ops
[p
[2]]((p
[1],p
[3]))
655 p
[0] = ast
.BinOp(p
[1], binary_ops
[p
[2]], p
[3])
657 p
[0] = unary_ops
[p
[1]](p
[2])
661 # power: atom trailer* ['**' factor]
662 # trailers enables function calls (and subscripts).
663 # I only allow one level of calls
664 # so this is 'trailer'
665 def p_power(self
, p
):
671 if p
[2][0] == "CALL":
672 #p[0] = ast.Expr(ast.Call(p[1], p[2][1], []))
673 p
[0] = ast
.Call(p
[1], p
[2][1], [])
674 #if p[1].id == 'print':
675 # p[0] = ast.Printnl(ast.Tuple(p[2][1]), None, None)
677 # p[0] = ast.CallFunc(p[1], p[2][1], None, None)
680 #raise AssertionError("not implemented %s" % p[2][0])
685 idx
= ast
.Slice(subs
[0], subs
[1], None)
686 p
[0] = ast
.Subscript(p
[1], idx
)
688 def p_atom_name(self
, p
):
690 p
[0] = ast
.Name(p
[1], ctx
=ast
.Load())
692 def p_atom_number(self
, p
):
696 p
[0] = ast
.Constant(p
[1])
698 #'[' [listmaker] ']' |
700 def p_atom_listmaker(self
, p
):
701 """atom : LBRACK listmaker RBRACK"""
704 def p_listmaker(self
, p
):
705 """listmaker : test COMMA listmaker
709 p
[0] = ast
.List([p
[1]])
711 p
[0] = ast
.List([p
[1]] + p
[3].nodes
)
713 def p_atom_tuple(self
, p
):
714 """atom : LPAR testlist RPAR"""
717 # trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
718 def p_trailer(self
, p
):
719 """trailer : trailer_arglist
724 def p_trailer_arglist(self
, p
):
725 "trailer_arglist : LPAR arglist RPAR"
726 p
[0] = ("CALL", p
[2])
728 def p_trailer_subscript(self
, p
):
729 "trailer_subscript : LBRACK subscript RBRACK"
730 p
[0] = ("SUBS", p
[2])
732 #subscript: '.' '.' '.' | test | [test] ':' [test]
734 def p_subscript(self
, p
):
735 """subscript : test COLON test
744 # testlist: test (',' test)* [',']
745 # Contains shift/reduce error
746 def p_testlist(self
, p
):
747 """testlist : testlist_multi COMMA
752 # May need to promote singleton to tuple
753 if isinstance(p
[1], list):
757 # Convert into a tuple?
758 if isinstance(p
[0], list):
759 p
[0] = ast
.Tuple(p
[0])
761 def p_testlist_multi(self
, p
):
762 """testlist_multi : testlist_multi COMMA test
768 if isinstance(p
[1], list):
775 # test: or_test ['if' or_test 'else' test] | lambdef
776 # as I don't support 'and', 'or', and 'not' this works down to 'comparison'
783 # arglist: (argument ',')* (argument [',']| '*' test [',' '**' test] | '**' test)
784 # XXX INCOMPLETE: this doesn't allow the trailing comma
785 def p_arglist(self
, p
):
786 """arglist : arglist COMMA argument
793 # argument: test [gen_for] | test '=' test # Really [keyword '='] test
794 def p_argument(self
, p
):
798 def p_error(self
, p
):
799 #print "Error!", repr(p)
803 class GardenSnakeParser(PowerParser
):
804 def __init__(self
, lexer
= None):
806 lexer
= IndentLexer(debug
=1)
808 self
.tokens
= lexer
.tokens
809 self
.parser
= yacc
.yacc(module
=self
, start
="file_input_end",
810 debug
=False, write_tables
=False)
812 def parse(self
, code
):
813 self
.lexer
.input(code
)
814 result
= self
.parser
.parse(lexer
= self
.lexer
, debug
=False)
815 return ast
.Module(result
)
818 ###### Code generation ######
820 #from compiler import misc, syntax, pycodegen
822 class GardenSnakeCompiler(object):
824 self
.parser
= GardenSnakeParser()
825 def compile(self
, code
, mode
="exec", filename
="<string>"):
826 tree
= self
.parser
.parse(code
)
830 #misc.set_filename(filename, tree)
831 return compile(tree
, mode
="exec", filename
="<string>")
833 gen
= pycodegen
.ModuleCodeGenerator(tree
)
837 ####### Test code #######
839 from soc
.decoder
.power_fieldsn
import create_sigdecode
844 index <- (RS)[8*i:8*i+7]
845 RA <- [0]*56 || perm[0:7]
850 if index < 64 then index <- 0
861 index <- (RS)[8*i:8*i+7]
866 RA <- [0]*56|| perm[0:7]
872 if (RS)[63-n] = 0b1 then
881 lexer
= IndentLexer(debug
=1)
882 # Give the lexer some input
891 break # No more input
896 sd
= create_sigdecode()
897 print ("forms", sd
.df
.forms
)
898 for f
in sd
.df
.FormX
:
901 _compile
= GardenSnakeCompiler().compile
903 tree
= _compile(code
, mode
="single", filename
="string")
905 tree
= ast
.fix_missing_locations(tree
)
906 print ( ast
.dump(tree
) )
909 print (astor
.dump_tree(tree
))
911 source
= astor
.to_source(tree
)
916 from soc
.decoder
.power_fieldsn
import create_sigdecode
918 # Set up the GardenSnake run-time environment
921 print ("-->", " ".join(map(str,args
)))
923 def listconcat(l1
, l2
):
928 d
["concat"] = listconcat
931 sd
= create_sigdecode()
932 getform
= getattr(sd
.df
, "Form%s" % form
)
934 for k
, f
in sd
.df
.instrs
[form
].items():
935 d
[k
] = getattr(getform
, k
)
937 compiled_code
= compile(source
, mode
="exec", filename
="<string>")
939 exec (compiled_code
, d
)