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
32 'NUMBER', # Python decimals
33 'STRING', # single quoted strings only; syntax of raw strings
59 # taken from decmial.py but without the leading sign
61 r
"""(\d+(\.\d*)?|\.\d+)([eE][-+]? \d+)?"""
62 t
.value
= int(t
.value
)
66 r
"'([^\\']+|\\'|\\\\)*'" # I think this is right ...
67 t
.value
=t
.value
[1:-1].decode("string-escape") # .swapcase() # for fun
83 # Ply nicely documented how to do this.
99 r
'[a-zA-Z_][a-zA-Z0-9_]*'
100 t
.type = RESERVED
.get(t
.value
, "NAME")
103 # Putting this before t_WS let it consume lines with only comments in
104 # them so the latter code never sees the WS part. Not consuming the
105 # newline. Needed for "if 1: #comment"
107 r
"[ ]*\043[^\n]*" # \043 is '#'
114 if t
.lexer
.at_line_start
and t
.lexer
.paren_count
== 0 and \
115 t
.lexer
.brack_count
== 0:
118 # Don't generate newline tokens when inside of parenthesis, eg
123 t
.lexer
.lineno
+= len(t
.value
)
125 if t
.lexer
.paren_count
== 0 and t
.lexer
.brack_count
== 0:
130 t
.lexer
.brack_count
+= 1
135 # check for underflow? should be the job of the parser
136 t
.lexer
.brack_count
-= 1
141 t
.lexer
.paren_count
+= 1
146 # check for underflow? should be the job of the parser
147 t
.lexer
.paren_count
-= 1
153 raise SyntaxError("Unknown symbol %r" % (t
.value
[0],))
154 print ("Skipping", repr(t
.value
[0]))
157 ## I implemented INDENT / DEDENT generation as a post-processing filter
159 # The original lex token stream contains WS and NEWLINE characters.
160 # WS will only occur before any other tokens on a line.
162 # I have three filters. One tags tokens by adding two attributes.
163 # "must_indent" is True if the token must be indented from the
164 # previous code. The other is "at_line_start" which is True for WS
165 # and the first non-WS/non-NEWLINE on a line. It flags the check so
166 # see if the new line has changed indication level.
168 # Python's syntax has three INDENT states
169 # 0) no colon hence no need to indent
170 # 1) "if 1: go()" - simple statements have a COLON but no need for an indent
171 # 2) "if 1:\n go()" - complex statements have a COLON NEWLINE and must indent
176 # turn into python-like colon syntax from pseudo-code syntax
177 def python_colonify(lexer
, tokens
):
179 forwhile_seen
= False
181 print ("track colon token", token
, token
.type)
183 if token
.type == 'THEN':
184 # turn then into colon
187 elif token
.type == 'ELSE':
192 elif token
.type in ['WHILE', 'FOR']:
195 elif token
.type == 'NEWLINE':
200 forwhile_seen
= False
206 # only care about whitespace at the start of a line
207 def track_tokens_filter(lexer
, tokens
):
208 oldignore
= lexer
.lexignore
209 lexer
.at_line_start
= at_line_start
= True
213 print ("track token", token
, token
.type)
214 token
.at_line_start
= at_line_start
216 if token
.type == "COLON":
217 at_line_start
= False
219 token
.must_indent
= False
221 elif token
.type == "NEWLINE":
223 if indent
== MAY_INDENT
:
225 token
.must_indent
= False
227 elif token
.type == "WS":
228 assert token
.at_line_start
== True
230 token
.must_indent
= False
233 # A real token; only indent after COLON NEWLINE
234 if indent
== MUST_INDENT
:
235 token
.must_indent
= True
237 token
.must_indent
= False
238 at_line_start
= False
241 # really bad hack that changes ignore lexer state.
242 # when "must indent" is seen (basically "real tokens" seen)
243 # then ignore whitespace.
244 if token
.must_indent
:
245 lexer
.lexignore
= ('ignore', ' ')
247 lexer
.lexignore
= oldignore
249 token
.indent
= indent
251 lexer
.at_line_start
= at_line_start
253 def _new_token(type, lineno
):
261 # Synthesize a DEDENT tag
263 return _new_token("DEDENT", lineno
)
265 # Synthesize an INDENT tag
267 return _new_token("INDENT", lineno
)
270 # Track the indentation level and emit the right INDENT / DEDENT events.
271 def indentation_filter(tokens
):
272 # A stack of indentation levels; will never pop item 0
279 print ("Process", depth
, token
.indent
, token
,)
280 if token
.at_line_start
:
281 print ("at_line_start",)
282 if token
.must_indent
:
283 print ("must_indent",)
286 # WS only occurs at the start of the line
287 # There may be WS followed by NEWLINE so
288 # only track the depth here. Don't indent/dedent
289 # until there's something real.
290 if token
.type == "WS":
292 depth
= len(token
.value
)
294 # WS tokens are never passed to the parser
297 if token
.type == "NEWLINE":
299 if prev_was_ws
or token
.at_line_start
:
302 # pass the other cases on through
306 # then it must be a real token (not WS, not NEWLINE)
307 # which can affect the indentation level
310 if token
.must_indent
:
311 # The current depth must be larger than the previous level
312 if not (depth
> levels
[-1]):
313 raise IndentationError("expected an indented block")
316 yield INDENT(token
.lineno
)
318 elif token
.at_line_start
:
319 # Must be on the same level or one of the previous levels
320 if depth
== levels
[-1]:
323 elif depth
> levels
[-1]:
324 raise IndentationError("indentation increase but not in new block")
326 # Back up; but only if it matches a previous level
328 i
= levels
.index(depth
)
330 raise IndentationError("inconsistent indentation")
331 for _
in range(i
+1, len(levels
)):
332 yield DEDENT(token
.lineno
)
337 ### Finished processing ###
339 # Must dedent any remaining levels
341 assert token
is not None
342 for _
in range(1, len(levels
)):
343 yield DEDENT(token
.lineno
)
346 # The top-level filter adds an ENDMARKER, if requested.
347 # Python's grammar uses it.
348 def filter(lexer
, add_endmarker
= True):
350 tokens
= iter(lexer
.token
, None)
351 tokens
= python_colonify(lexer
, tokens
)
352 tokens
= track_tokens_filter(lexer
, tokens
)
353 for token
in indentation_filter(tokens
):
358 if token
is not None:
359 lineno
= token
.lineno
360 yield _new_token("ENDMARKER", lineno
)
362 # Combine Ply and my filters into a new lexer
364 class IndentLexer(object):
365 def __init__(self
, debug
=0, optimize
=0, lextab
='lextab', reflags
=0):
366 self
.lexer
= lex
.lex(debug
=debug
, optimize
=optimize
, lextab
=lextab
, reflags
=reflags
)
367 self
.token_stream
= None
368 def input(self
, s
, add_endmarker
=True):
369 self
.lexer
.paren_count
= 0
370 self
.lexer
.brack_count
= 0
372 self
.token_stream
= filter(self
.lexer
, add_endmarker
)
375 return next(self
.token_stream
)
376 except StopIteration:
379 ########## Parser (tokens -> AST) ######
384 # I use the Python AST
385 #from compiler import ast
389 def Assign(left
, right
):
391 if isinstance(left
, ast
.Name
):
392 # Single assignment on left
393 return ast
.Assign([ast
.Name(left
.id, ast
.Store())], right
)
394 elif isinstance(left
, ast
.Tuple
):
395 # List of things - make sure they are Name nodes
397 for child
in left
.getChildren():
398 if not isinstance(child
, ast
.Name
):
399 raise SyntaxError("that assignment not supported")
400 names
.append(child
.name
)
401 ass_list
= [ast
.AssName(name
, 'OP_ASSIGN') for name
in names
]
402 return ast
.Assign([ast
.AssTuple(ass_list
)], right
)
404 raise SyntaxError("Can't do that yet")
407 # The grammar comments come from Python's Grammar/Grammar file
409 ## NB: compound_stmt in single_input is followed by extra NEWLINE!
410 # file_input: (NEWLINE | stmt)* ENDMARKER
411 def p_file_input_end(p
):
412 """file_input_end : file_input ENDMARKER"""
417 """file_input : file_input NEWLINE
421 if isinstance(p
[len(p
)-1], str):
425 p
[0] = [] # p == 2 --> only a blank line
433 # funcdef: [decorators] 'def' NAME parameters ':' suite
434 # ignoring decorators
436 "funcdef : DEF NAME parameters COLON suite"
437 p
[0] = ast
.Function(None, p
[2], list(p
[3]), (), 0, None, p
[5])
439 # parameters: '(' [varargslist] ')'
441 """parameters : LPAR RPAR
442 | LPAR varargslist RPAR"""
449 # varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] | '**' NAME) |
451 def p_varargslist(p
):
452 """varargslist : varargslist COMMA NAME
459 # stmt: simple_stmt | compound_stmt
460 def p_stmt_simple(p
):
461 """stmt : simple_stmt"""
462 # simple_stmt is a list
465 def p_stmt_compound(p
):
466 """stmt : compound_stmt"""
469 # simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
470 def p_simple_stmt(p
):
471 """simple_stmt : small_stmts NEWLINE
472 | small_stmts SEMICOLON NEWLINE"""
475 def p_small_stmts(p
):
476 """small_stmts : small_stmts SEMICOLON small_stmt
483 # small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
484 # import_stmt | global_stmt | exec_stmt | assert_stmt
486 """small_stmt : flow_stmt
491 # expr_stmt: testlist (augassign (yield_expr|testlist) |
492 # ('=' (yield_expr|testlist))*)
493 # augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
494 # '<<=' | '>>=' | '**=' | '//=')
496 """expr_stmt : testlist ASSIGN testlist
499 # a list of expressions
500 #p[0] = ast.Discard(p[1])
503 p
[0] = Assign(p
[1], p
[3])
506 "flow_stmt : return_stmt"
509 # return_stmt: 'return' [testlist]
510 def p_return_stmt(p
):
511 "return_stmt : RETURN testlist"
512 p
[0] = ast
.Return(p
[2])
515 def p_compound_stmt(p
):
516 """compound_stmt : if_stmt
524 """break_stmt : BREAK
529 """for_stmt : FOR test EQ test TO test COLON suite
531 p
[0] = ast
.While(p
[2], p
[4], [])
532 # auto-add-one (sigh) due to python range
534 end
= ast
.BinOp(p
[6], ast
.Add(), ast
.Constant(1))
535 it
= ast
.Call(ast
.Name("range"), [start
, end
], [])
536 p
[0] = ast
.For(p
[2], it
, p
[8], [])
539 """while_stmt : DO WHILE test COLON suite ELSE COLON suite
540 | DO WHILE test COLON suite
543 p
[0] = ast
.While(p
[3], p
[5], [])
545 p
[0] = ast
.While(p
[3], p
[5], p
[8])
548 """if_stmt : IF test COLON suite ELSE COLON suite
549 | IF test COLON suite
552 p
[0] = ast
.If(p
[2], p
[4], [])
554 p
[0] = ast
.If(p
[2], p
[4], p
[7])
557 """suite : simple_stmt
558 | NEWLINE INDENT stmts DEDENT"""
566 """stmts : stmts stmt
573 ## No using Python's approach because Ply supports precedence
575 # comparison: expr (comp_op expr)*
576 # arith_expr: term (('+'|'-') term)*
577 # term: factor (('*'|'/'|'%'|'//') factor)*
578 # factor: ('+'|'-'|'~') factor | power
579 # comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
581 def make_lt_compare(arg
):
583 return ast
.Compare(left
, [ast
.Lt()], [right
])
584 def make_gt_compare(arg
):
586 return ast
.Compare(left
, [ast
.Gt()], [right
])
587 def make_eq_compare(arg
):
589 return ast
.Compare(left
, [ast
.Eq()], [right
])
597 "<": make_lt_compare
,
598 ">": make_gt_compare
,
599 "=": make_eq_compare
,
606 ("left", "EQ", "GT", "LT"),
607 ("left", "PLUS", "MINUS"),
608 ("left", "MULT", "DIV"),
611 def check_concat(node
): # checks if the comparison is already a concat
613 if not isinstance(node
, ast
.Call
):
615 if node
[0].id != 'concat':
620 """comparison : comparison PLUS comparison
621 | comparison MINUS comparison
622 | comparison MULT comparison
623 | comparison DIV comparison
624 | comparison LT comparison
625 | comparison EQ comparison
626 | comparison GT comparison
629 | comparison APPEND comparison
634 l
= check_concat(p
[1]) + check_concat(p
[3])
635 p
[0] = ast
.Call(ast
.Name("concat"), l
, [])
636 elif p
[2] in ['<', '>', '=']:
637 p
[0] = binary_ops
[p
[2]]((p
[1],p
[3]))
639 p
[0] = ast
.BinOp(p
[1], binary_ops
[p
[2]], p
[3])
641 p
[0] = unary_ops
[p
[1]](p
[2])
645 # power: atom trailer* ['**' factor]
646 # trailers enables function calls (and subscripts).
647 # I only allow one level of calls
648 # so this is 'trailer'
655 if p
[2][0] == "CALL":
656 p
[0] = ast
.Expr(ast
.Call(p
[1], p
[2][1], []))
657 #if p[1].id == 'print':
658 # p[0] = ast.Printnl(ast.Tuple(p[2][1]), None, None)
660 # p[0] = ast.CallFunc(p[1], p[2][1], None, None)
663 #raise AssertionError("not implemented %s" % p[2][0])
668 idx
= ast
.Slice(subs
[0], subs
[1], None)
669 p
[0] = ast
.Subscript(p
[1], idx
)
673 p
[0] = ast
.Name(p
[1], ctx
=ast
.Load())
675 def p_atom_number(p
):
678 p
[0] = ast
.Constant(p
[1])
680 #'[' [listmaker] ']' |
682 def p_atom_listmaker(p
):
683 """atom : LBRACK listmaker RBRACK"""
687 """listmaker : test COMMA listmaker
691 p
[0] = ast
.List([p
[1]])
693 p
[0] = ast
.List([p
[1]] + p
[3].nodes
)
696 """atom : LPAR testlist RPAR"""
699 # trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
701 """trailer : trailer_arglist
706 def p_trailer_arglist(p
):
707 "trailer_arglist : LPAR arglist RPAR"
708 p
[0] = ("CALL", p
[2])
710 def p_trailer_subscript(p
):
711 "trailer_subscript : LBRACK subscript RBRACK"
712 p
[0] = ("SUBS", p
[2])
714 #subscript: '.' '.' '.' | test | [test] ':' [test]
717 """subscript : test COLON test
726 # testlist: test (',' test)* [',']
727 # Contains shift/reduce error
729 """testlist : testlist_multi COMMA
734 # May need to promote singleton to tuple
735 if isinstance(p
[1], list):
739 # Convert into a tuple?
740 if isinstance(p
[0], list):
741 p
[0] = ast
.Tuple(p
[0])
743 def p_testlist_multi(p
):
744 """testlist_multi : testlist_multi COMMA test
750 if isinstance(p
[1], list):
757 # test: or_test ['if' or_test 'else' test] | lambdef
758 # as I don't support 'and', 'or', and 'not' this works down to 'comparison'
765 # arglist: (argument ',')* (argument [',']| '*' test [',' '**' test] | '**' test)
766 # XXX INCOMPLETE: this doesn't allow the trailing comma
768 """arglist : arglist COMMA argument
775 # argument: test [gen_for] | test '=' test # Really [keyword '='] test
781 #print "Error!", repr(p)
785 class GardenSnakeParser(object):
786 def __init__(self
, lexer
= None):
788 lexer
= IndentLexer(debug
=1)
790 self
.parser
= yacc
.yacc(start
="file_input_end",
791 debug
=False, write_tables
=False)
793 def parse(self
, code
):
794 self
.lexer
.input(code
)
795 result
= self
.parser
.parse(lexer
= self
.lexer
, debug
=False)
796 return ast
.Module(result
)
799 ###### Code generation ######
801 #from compiler import misc, syntax, pycodegen
803 class GardenSnakeCompiler(object):
805 self
.parser
= GardenSnakeParser()
806 def compile(self
, code
, mode
="exec", filename
="<string>"):
807 tree
= self
.parser
.parse(code
)
811 #misc.set_filename(filename, tree)
812 return compile(tree
, mode
="exec", filename
="<string>")
814 gen
= pycodegen
.ModuleCodeGenerator(tree
)
818 ####### Test code #######
820 from soc
.decoder
.power_fieldsn
import create_sigdecode
825 index <- (RS)[8*i:8*i+7]
826 RA <- [0]*56 || perm[0:7]
831 if index < 64 then index <- 0
842 index <- (RS)[8*i:8*i+7]
847 RA <- [0]*56|| perm[0:7]
853 if (RS)[63-n] = 0b1 then
862 lexer
= IndentLexer(debug
=1)
863 # Give the lexer some input
872 break # No more input
877 # Set up the GardenSnake run-time environment
880 print ("-->", " ".join(map(str,args
)))
886 sd
= create_sigdecode()
887 print ("forms", sd
.df
.forms
)
888 for f
in sd
.df
.FormX
:
891 _compile
= GardenSnakeCompiler().compile
893 tree
= _compile(code
, mode
="single", filename
="string")
895 tree
= ast
.fix_missing_locations(tree
)
896 print ( ast
.dump(tree
) )
899 print (astor
.dump_tree(tree
))
901 source
= astor
.to_source(tree
)
904 #from compiler import parse
905 #tree = parse(code, "exec")
907 print (compiled_code
)
909 exec (compiled_code
, d
)