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
31 'NUMBER', # Python decimals
32 'STRING', # single quoted strings only; syntax of raw strings
58 # taken from decmial.py but without the leading sign
60 r
"""(\d+(\.\d*)?|\.\d+)([eE][-+]? \d+)?"""
61 t
.value
= int(t
.value
)
65 r
"'([^\\']+|\\'|\\\\)*'" # I think this is right ...
66 t
.value
=t
.value
[1:-1].decode("string-escape") # .swapcase() # for fun
82 # Ply nicely documented how to do this.
97 r
'[a-zA-Z_][a-zA-Z0-9_]*'
98 t
.type = RESERVED
.get(t
.value
, "NAME")
101 # Putting this before t_WS let it consume lines with only comments in
102 # them so the latter code never sees the WS part. Not consuming the
103 # newline. Needed for "if 1: #comment"
105 r
"[ ]*\043[^\n]*" # \043 is '#'
112 if t
.lexer
.at_line_start
and t
.lexer
.paren_count
== 0 and \
113 t
.lexer
.brack_count
== 0:
116 # Don't generate newline tokens when inside of parenthesis, eg
121 t
.lexer
.lineno
+= len(t
.value
)
123 if t
.lexer
.paren_count
== 0 and t
.lexer
.brack_count
== 0:
128 t
.lexer
.brack_count
+= 1
133 # check for underflow? should be the job of the parser
134 t
.lexer
.brack_count
-= 1
139 t
.lexer
.paren_count
+= 1
144 # check for underflow? should be the job of the parser
145 t
.lexer
.paren_count
-= 1
151 raise SyntaxError("Unknown symbol %r" % (t
.value
[0],))
152 print ("Skipping", repr(t
.value
[0]))
155 ## I implemented INDENT / DEDENT generation as a post-processing filter
157 # The original lex token stream contains WS and NEWLINE characters.
158 # WS will only occur before any other tokens on a line.
160 # I have three filters. One tags tokens by adding two attributes.
161 # "must_indent" is True if the token must be indented from the
162 # previous code. The other is "at_line_start" which is True for WS
163 # and the first non-WS/non-NEWLINE on a line. It flags the check so
164 # see if the new line has changed indication level.
166 # Python's syntax has three INDENT states
167 # 0) no colon hence no need to indent
168 # 1) "if 1: go()" - simple statements have a COLON but no need for an indent
169 # 2) "if 1:\n go()" - complex statements have a COLON NEWLINE and must indent
174 # turn into python-like colon syntax from pseudo-code syntax
175 def python_colonify(lexer
, tokens
):
179 print ("track colon token", token
, token
.type)
181 if token
.type == 'DO':
182 continue # skip. do while is redundant
183 elif token
.type == 'THEN':
184 # turn then into colon
187 elif token
.type == 'ELSE':
192 elif token
.type == 'WHILE':
195 elif token
.type == 'NEWLINE':
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
490 # expr_stmt: testlist (augassign (yield_expr|testlist) |
491 # ('=' (yield_expr|testlist))*)
492 # augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
493 # '<<=' | '>>=' | '**=' | '//=')
495 """expr_stmt : testlist ASSIGN testlist
498 # a list of expressions
499 #p[0] = ast.Discard(p[1])
502 p
[0] = Assign(p
[1], p
[3])
505 "flow_stmt : return_stmt"
508 # return_stmt: 'return' [testlist]
509 def p_return_stmt(p
):
510 "return_stmt : RETURN testlist"
511 p
[0] = ast
.Return(p
[2])
514 def p_compound_stmt(p
):
515 """compound_stmt : if_stmt
522 """while_stmt : WHILE test COLON suite ELSE COLON suite
523 | WHILE test COLON suite
526 p
[0] = ast
.While(p
[2], p
[4], [])
528 p
[0] = ast
.While(p
[2], p
[4], p
[7])
531 """if_stmt : IF test COLON suite ELSE COLON suite
532 | IF test COLON suite
535 p
[0] = ast
.If(p
[2], p
[4], [])
537 p
[0] = ast
.If(p
[2], p
[4], p
[7])
540 """suite : simple_stmt
541 | NEWLINE INDENT stmts DEDENT"""
549 """stmts : stmts stmt
556 ## No using Python's approach because Ply supports precedence
558 # comparison: expr (comp_op expr)*
559 # arith_expr: term (('+'|'-') term)*
560 # term: factor (('*'|'/'|'%'|'//') factor)*
561 # factor: ('+'|'-'|'~') factor | power
562 # comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
564 def make_lt_compare(arg
):
566 return ast
.Compare(left
, [ast
.Lt()], [right
])
567 def make_gt_compare(arg
):
569 return ast
.Compare(left
, [ast
.Gt()], [right
])
570 def make_eq_compare(arg
):
572 return ast
.Compare(left
, [ast
.Eq()], [right
])
580 "<": make_lt_compare
,
581 ">": make_gt_compare
,
582 "==": make_eq_compare
,
589 ("left", "EQ", "GT", "LT"),
590 ("left", "PLUS", "MINUS"),
591 ("left", "MULT", "DIV"),
594 def check_concat(node
): # checks if the comparison is already a concat
596 if not isinstance(node
, ast
.Call
):
598 if node
[0].id != 'concat':
603 """comparison : comparison PLUS comparison
604 | comparison MINUS comparison
605 | comparison MULT comparison
606 | comparison DIV comparison
607 | comparison LT comparison
608 | comparison EQ comparison
609 | comparison GT comparison
612 | comparison APPEND comparison
617 l
= check_concat(p
[1]) + check_concat(p
[3])
618 p
[0] = ast
.Call(ast
.Name("concat"), l
, [])
619 elif p
[2] in ['<', '>', '==']:
620 p
[0] = binary_ops
[p
[2]]((p
[1],p
[3]))
622 p
[0] = ast
.BinOp(p
[1], binary_ops
[p
[2]], p
[3])
624 p
[0] = unary_ops
[p
[1]](p
[2])
628 # power: atom trailer* ['**' factor]
629 # trailers enables function calls (and subscripts).
630 # I only allow one level of calls
631 # so this is 'trailer'
638 if p
[2][0] == "CALL":
639 p
[0] = ast
.Expr(ast
.Call(p
[1], p
[2][1], []))
640 #if p[1].id == 'print':
641 # p[0] = ast.Printnl(ast.Tuple(p[2][1]), None, None)
643 # p[0] = ast.CallFunc(p[1], p[2][1], None, None)
646 #raise AssertionError("not implemented %s" % p[2][0])
651 idx
= ast
.Slice(subs
[0], subs
[1], None)
652 p
[0] = ast
.Subscript(p
[1], idx
)
656 p
[0] = ast
.Name(p
[1], ctx
=ast
.Load())
658 def p_atom_number(p
):
661 p
[0] = ast
.Constant(p
[1])
663 #'[' [listmaker] ']' |
665 def p_atom_listmaker(p
):
666 """atom : LBRACK listmaker RBRACK"""
670 """listmaker : test COMMA listmaker
674 p
[0] = ast
.List([p
[1]])
676 p
[0] = ast
.List([p
[1]] + p
[3].nodes
)
679 """atom : LPAR testlist RPAR"""
682 # trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
684 """trailer : trailer_arglist
689 def p_trailer_arglist(p
):
690 "trailer_arglist : LPAR arglist RPAR"
691 p
[0] = ("CALL", p
[2])
693 def p_trailer_subscript(p
):
694 "trailer_subscript : LBRACK subscript RBRACK"
695 p
[0] = ("SUBS", p
[2])
697 #subscript: '.' '.' '.' | test | [test] ':' [test]
700 """subscript : test COLON test
709 # testlist: test (',' test)* [',']
710 # Contains shift/reduce error
712 """testlist : testlist_multi COMMA
717 # May need to promote singleton to tuple
718 if isinstance(p
[1], list):
722 # Convert into a tuple?
723 if isinstance(p
[0], list):
724 p
[0] = ast
.Tuple(p
[0])
726 def p_testlist_multi(p
):
727 """testlist_multi : testlist_multi COMMA test
733 if isinstance(p
[1], list):
740 # test: or_test ['if' or_test 'else' test] | lambdef
741 # as I don't support 'and', 'or', and 'not' this works down to 'comparison'
748 # arglist: (argument ',')* (argument [',']| '*' test [',' '**' test] | '**' test)
749 # XXX INCOMPLETE: this doesn't allow the trailing comma
751 """arglist : arglist COMMA argument
758 # argument: test [gen_for] | test '=' test # Really [keyword '='] test
764 #print "Error!", repr(p)
768 class GardenSnakeParser(object):
769 def __init__(self
, lexer
= None):
771 lexer
= IndentLexer(debug
=1)
773 self
.parser
= yacc
.yacc(start
="file_input_end",
774 debug
=False, write_tables
=False)
776 def parse(self
, code
):
777 self
.lexer
.input(code
)
778 result
= self
.parser
.parse(lexer
= self
.lexer
, debug
=False)
779 return ast
.Module(result
)
782 ###### Code generation ######
784 #from compiler import misc, syntax, pycodegen
786 class GardenSnakeCompiler(object):
788 self
.parser
= GardenSnakeParser()
789 def compile(self
, code
, mode
="exec", filename
="<string>"):
790 tree
= self
.parser
.parse(code
)
794 #misc.set_filename(filename, tree)
795 return compile(tree
, mode
="exec", filename
="<string>")
797 gen
= pycodegen
.ModuleCodeGenerator(tree
)
801 ####### Test code #######
803 from soc
.decoder
.power_fieldsn
import create_sigdecode
807 index <- (RS)[8*i:8*i+7]
812 RA <- [0]*56|| perm[0:7]
818 index <- (RS)[8*i:8*i+7]
819 RA <- [0]*56 || perm[0:7]
824 if index < 64 then index <- 0
831 lexer
= IndentLexer(debug
=1)
832 # Give the lexer some input
841 break # No more input
846 # Set up the GardenSnake run-time environment
849 print ("-->", " ".join(map(str,args
)))
855 sd
= create_sigdecode()
856 print ("forms", sd
.df
.forms
)
857 for f
in sd
.df
.FormX
:
860 _compile
= GardenSnakeCompiler().compile
862 tree
= _compile(code
, mode
="single", filename
="string")
864 tree
= ast
.fix_missing_locations(tree
)
865 print ( ast
.dump(tree
) )
868 print (astor
.dump_tree(tree
))
870 source
= astor
.to_source(tree
)
873 #from compiler import parse
874 #tree = parse(code, "exec")
876 print (compiled_code
)
878 exec (compiled_code
, d
)