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
29 'NUMBER', # Python decimals
30 'STRING', # single quoted strings only; syntax of raw strings
55 # taken from decmial.py but without the leading sign
57 r
"""(\d+(\.\d*)?|\.\d+)([eE][-+]? \d+)?"""
58 t
.value
= int(t
.value
)
62 r
"'([^\\']+|\\'|\\\\)*'" # I think this is right ...
63 t
.value
=t
.value
[1:-1].decode("string-escape") # .swapcase() # for fun
78 # Ply nicely documented how to do this.
91 r
'[a-zA-Z_][a-zA-Z0-9_]*'
92 t
.type = RESERVED
.get(t
.value
, "NAME")
95 # Putting this before t_WS let it consume lines with only comments in
96 # them so the latter code never sees the WS part. Not consuming the
97 # newline. Needed for "if 1: #comment"
99 r
"[ ]*\043[^\n]*" # \043 is '#'
106 if t
.lexer
.at_line_start
and t
.lexer
.paren_count
== 0 and \
107 t
.lexer
.brack_count
== 0:
110 # Don't generate newline tokens when inside of parenthesis, eg
115 t
.lexer
.lineno
+= len(t
.value
)
117 if t
.lexer
.paren_count
== 0 and t
.lexer
.brack_count
== 0:
122 t
.lexer
.brack_count
+= 1
127 # check for underflow? should be the job of the parser
128 t
.lexer
.brack_count
-= 1
133 t
.lexer
.paren_count
+= 1
138 # check for underflow? should be the job of the parser
139 t
.lexer
.paren_count
-= 1
145 raise SyntaxError("Unknown symbol %r" % (t
.value
[0],))
146 print ("Skipping", repr(t
.value
[0]))
149 ## I implemented INDENT / DEDENT generation as a post-processing filter
151 # The original lex token stream contains WS and NEWLINE characters.
152 # WS will only occur before any other tokens on a line.
154 # I have three filters. One tags tokens by adding two attributes.
155 # "must_indent" is True if the token must be indented from the
156 # previous code. The other is "at_line_start" which is True for WS
157 # and the first non-WS/non-NEWLINE on a line. It flags the check so
158 # see if the new line has changed indication level.
160 # Python's syntax has three INDENT states
161 # 0) no colon hence no need to indent
162 # 1) "if 1: go()" - simple statements have a COLON but no need for an indent
163 # 2) "if 1:\n go()" - complex statements have a COLON NEWLINE and must indent
168 # only care about whitespace at the start of a line
169 def track_tokens_filter(lexer
, tokens
):
170 oldignore
= lexer
.lexignore
171 lexer
.at_line_start
= at_line_start
= True
175 #print ("token", token)
176 token
.at_line_start
= at_line_start
178 if token
.type == "COLON":
179 at_line_start
= False
181 token
.must_indent
= False
183 elif token
.type == "NEWLINE":
185 if indent
== MAY_INDENT
:
187 token
.must_indent
= False
189 elif token
.type == "WS":
190 assert token
.at_line_start
== True
192 token
.must_indent
= False
195 # A real token; only indent after COLON NEWLINE
196 if indent
== MUST_INDENT
:
197 token
.must_indent
= True
199 token
.must_indent
= False
200 at_line_start
= False
203 # really bad hack that changes ignore lexer state.
204 # when "must indent" is seen (basically "real tokens" seen)
205 # then ignore whitespace.
206 if token
.must_indent
:
207 lexer
.lexignore
= ('ignore', ' ')
209 lexer
.lexignore
= oldignore
211 token
.indent
= indent
213 lexer
.at_line_start
= at_line_start
215 def _new_token(type, lineno
):
223 # Synthesize a DEDENT tag
225 return _new_token("DEDENT", lineno
)
227 # Synthesize an INDENT tag
229 return _new_token("INDENT", lineno
)
232 # Track the indentation level and emit the right INDENT / DEDENT events.
233 def indentation_filter(tokens
):
234 # A stack of indentation levels; will never pop item 0
241 print ("Process", depth
, token
.indent
, token
,)
242 if token
.at_line_start
:
243 print ("at_line_start",)
244 if token
.must_indent
:
245 print ("must_indent",)
248 # WS only occurs at the start of the line
249 # There may be WS followed by NEWLINE so
250 # only track the depth here. Don't indent/dedent
251 # until there's something real.
252 if token
.type == "WS":
254 depth
= len(token
.value
)
256 # WS tokens are never passed to the parser
259 if token
.type == "NEWLINE":
261 if prev_was_ws
or token
.at_line_start
:
264 # pass the other cases on through
268 # then it must be a real token (not WS, not NEWLINE)
269 # which can affect the indentation level
272 if token
.must_indent
:
273 # The current depth must be larger than the previous level
274 if not (depth
> levels
[-1]):
275 raise IndentationError("expected an indented block")
278 yield INDENT(token
.lineno
)
280 elif token
.at_line_start
:
281 # Must be on the same level or one of the previous levels
282 if depth
== levels
[-1]:
285 elif depth
> levels
[-1]:
286 raise IndentationError("indentation increase but not in new block")
288 # Back up; but only if it matches a previous level
290 i
= levels
.index(depth
)
292 raise IndentationError("inconsistent indentation")
293 for _
in range(i
+1, len(levels
)):
294 yield DEDENT(token
.lineno
)
299 ### Finished processing ###
301 # Must dedent any remaining levels
303 assert token
is not None
304 for _
in range(1, len(levels
)):
305 yield DEDENT(token
.lineno
)
308 # The top-level filter adds an ENDMARKER, if requested.
309 # Python's grammar uses it.
310 def filter(lexer
, add_endmarker
= True):
312 tokens
= iter(lexer
.token
, None)
313 tokens
= track_tokens_filter(lexer
, tokens
)
314 for token
in indentation_filter(tokens
):
319 if token
is not None:
320 lineno
= token
.lineno
321 yield _new_token("ENDMARKER", lineno
)
323 # Combine Ply and my filters into a new lexer
325 class IndentLexer(object):
326 def __init__(self
, debug
=0, optimize
=0, lextab
='lextab', reflags
=0):
327 self
.lexer
= lex
.lex(debug
=debug
, optimize
=optimize
, lextab
=lextab
, reflags
=reflags
)
328 self
.token_stream
= None
329 def input(self
, s
, add_endmarker
=True):
330 self
.lexer
.paren_count
= 0
331 self
.lexer
.brack_count
= 0
333 self
.token_stream
= filter(self
.lexer
, add_endmarker
)
336 return next(self
.token_stream
)
337 except StopIteration:
340 ########## Parser (tokens -> AST) ######
345 # I use the Python AST
346 #from compiler import ast
350 def Assign(left
, right
):
352 if isinstance(left
, ast
.Name
):
353 # Single assignment on left
354 return ast
.Assign([ast
.Name(left
.id, ast
.Store())], right
)
355 elif isinstance(left
, ast
.Tuple
):
356 # List of things - make sure they are Name nodes
358 for child
in left
.getChildren():
359 if not isinstance(child
, ast
.Name
):
360 raise SyntaxError("that assignment not supported")
361 names
.append(child
.name
)
362 ass_list
= [ast
.AssName(name
, 'OP_ASSIGN') for name
in names
]
363 return ast
.Assign([ast
.AssTuple(ass_list
)], right
)
365 raise SyntaxError("Can't do that yet")
368 # The grammar comments come from Python's Grammar/Grammar file
370 ## NB: compound_stmt in single_input is followed by extra NEWLINE!
371 # file_input: (NEWLINE | stmt)* ENDMARKER
372 def p_file_input_end(p
):
373 """file_input_end : file_input ENDMARKER"""
378 """file_input : file_input NEWLINE
382 if isinstance(p
[len(p
)-1], str):
386 p
[0] = [] # p == 2 --> only a blank line
394 # funcdef: [decorators] 'def' NAME parameters ':' suite
395 # ignoring decorators
397 "funcdef : DEF NAME parameters COLON suite"
398 p
[0] = ast
.Function(None, p
[2], list(p
[3]), (), 0, None, p
[5])
400 # parameters: '(' [varargslist] ')'
402 """parameters : LPAR RPAR
403 | LPAR varargslist RPAR"""
410 # varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] | '**' NAME) |
412 def p_varargslist(p
):
413 """varargslist : varargslist COMMA NAME
420 # stmt: simple_stmt | compound_stmt
421 def p_stmt_simple(p
):
422 """stmt : simple_stmt"""
423 # simple_stmt is a list
426 def p_stmt_compound(p
):
427 """stmt : compound_stmt"""
430 # simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
431 def p_simple_stmt(p
):
432 """simple_stmt : small_stmts NEWLINE
433 | small_stmts SEMICOLON NEWLINE"""
436 def p_small_stmts(p
):
437 """small_stmts : small_stmts SEMICOLON small_stmt
444 # small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
445 # import_stmt | global_stmt | exec_stmt | assert_stmt
447 """small_stmt : flow_stmt
451 # expr_stmt: testlist (augassign (yield_expr|testlist) |
452 # ('=' (yield_expr|testlist))*)
453 # augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
454 # '<<=' | '>>=' | '**=' | '//=')
456 """expr_stmt : testlist ASSIGN testlist
459 # a list of expressions
460 #p[0] = ast.Discard(p[1])
463 p
[0] = Assign(p
[1], p
[3])
466 "flow_stmt : return_stmt"
469 # return_stmt: 'return' [testlist]
470 def p_return_stmt(p
):
471 "return_stmt : RETURN testlist"
472 p
[0] = ast
.Return(p
[2])
475 def p_compound_stmt(p
):
476 """compound_stmt : if_stmt
483 """while_stmt : WHILE test COLON suite ELSE COLON suite
484 | WHILE test COLON suite
487 p
[0] = ast
.While(p
[2], p
[4], None)
489 p
[0] = ast
.While(p
[2], p
[4], p
[7])
492 """if_stmt : IF test COLON suite ELSE COLON suite
493 | IF test COLON suite
496 p
[0] = ast
.If([(p
[2], p
[4])], None)
498 p
[0] = ast
.If([(p
[2], p
[4])], p
[7])
501 """suite : simple_stmt
502 | NEWLINE INDENT stmts DEDENT"""
510 """stmts : stmts stmt
517 ## No using Python's approach because Ply supports precedence
519 # comparison: expr (comp_op expr)*
520 # arith_expr: term (('+'|'-') term)*
521 # term: factor (('*'|'/'|'%'|'//') factor)*
522 # factor: ('+'|'-'|'~') factor | power
523 # comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
525 def make_lt_compare(arg
):
527 return ast
.Compare(left
, [('<', right
),])
528 def make_gt_compare(arg
):
530 return ast
.Compare(left
, [('>', right
),])
531 def make_eq_compare(arg
):
533 return ast
.Compare(left
, [('==', right
),])
541 "<": make_lt_compare
,
542 ">": make_gt_compare
,
543 "==": make_eq_compare
,
550 ("left", "EQ", "GT", "LT"),
551 ("left", "PLUS", "MINUS"),
552 ("left", "MULT", "DIV"),
556 """comparison : comparison PLUS comparison
557 | comparison MINUS comparison
558 | comparison MULT comparison
559 | comparison DIV comparison
560 | comparison LT comparison
561 | comparison EQ comparison
562 | comparison GT comparison
567 p
[0] = ast
.BinOp(p
[1], binary_ops
[p
[2]], p
[3])
569 p
[0] = unary_ops
[p
[1]](p
[2])
573 # power: atom trailer* ['**' factor]
574 # trailers enables function calls (and subscripts).
575 # I only allow one level of calls
576 # so this is 'trailer'
583 if p
[2][0] == "CALL":
584 p
[0] = ast
.Expr(ast
.Call(p
[1], p
[2][1], []))
585 #if p[1].id == 'print':
586 # p[0] = ast.Printnl(ast.Tuple(p[2][1]), None, None)
588 # p[0] = ast.CallFunc(p[1], p[2][1], None, None)
591 #raise AssertionError("not implemented %s" % p[2][0])
594 p
[0] = ast
.Subscript(p
[1], 'OP_APPLY', subs
[0])
596 p
[0] = ast
.Slice(p
[1], 'OP_APPLY', subs
[0], subs
[1])
600 p
[0] = ast
.Name(p
[1], ctx
=ast
.Load())
602 def p_atom_number(p
):
605 p
[0] = ast
.Constant(p
[1])
607 #'[' [listmaker] ']' |
609 def p_atom_listmaker(p
):
610 """atom : LBRACK listmaker RBRACK"""
614 """listmaker : test COMMA listmaker
618 p
[0] = ast
.List([p
[1]])
620 p
[0] = ast
.List([p
[1]] + p
[3].nodes
)
623 """atom : LPAR testlist RPAR"""
626 # trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
628 """trailer : trailer_arglist
633 def p_trailer_arglist(p
):
634 "trailer_arglist : LPAR arglist RPAR"
635 p
[0] = ("CALL", p
[2])
637 def p_trailer_subscript(p
):
638 "trailer_subscript : LBRACK subscript RBRACK"
639 p
[0] = ("SUBS", p
[2])
641 #subscript: '.' '.' '.' | test | [test] ':' [test]
644 """subscript : test COLON test
653 # testlist: test (',' test)* [',']
654 # Contains shift/reduce error
656 """testlist : testlist_multi COMMA
661 # May need to promote singleton to tuple
662 if isinstance(p
[1], list):
666 # Convert into a tuple?
667 if isinstance(p
[0], list):
668 p
[0] = ast
.Tuple(p
[0])
670 def p_testlist_multi(p
):
671 """testlist_multi : testlist_multi COMMA test
677 if isinstance(p
[1], list):
684 # test: or_test ['if' or_test 'else' test] | lambdef
685 # as I don't support 'and', 'or', and 'not' this works down to 'comparison'
692 # arglist: (argument ',')* (argument [',']| '*' test [',' '**' test] | '**' test)
693 # XXX INCOMPLETE: this doesn't allow the trailing comma
695 """arglist : arglist COMMA argument
702 # argument: test [gen_for] | test '=' test # Really [keyword '='] test
708 #print "Error!", repr(p)
712 class GardenSnakeParser(object):
713 def __init__(self
, lexer
= None):
715 lexer
= IndentLexer(debug
=1)
717 self
.parser
= yacc
.yacc(start
="file_input_end",
718 debug
=False, write_tables
=False)
720 def parse(self
, code
):
721 self
.lexer
.input(code
)
722 result
= self
.parser
.parse(lexer
= self
.lexer
, debug
=False)
723 return ast
.Module(result
)
726 ###### Code generation ######
728 #from compiler import misc, syntax, pycodegen
730 class GardenSnakeCompiler(object):
732 self
.parser
= GardenSnakeParser()
733 def compile(self
, code
, mode
="exec", filename
="<string>"):
734 tree
= self
.parser
.parse(code
)
738 #misc.set_filename(filename, tree)
739 return compile(tree
, mode
="exec", filename
="<string>")
741 gen
= pycodegen
.ModuleCodeGenerator(tree
)
745 ####### Test code #######
747 from soc
.decoder
.power_fieldsn
import create_sigdecode
751 index <- (RS)[8*i:8*i+7]
756 RA <- [0]*56|| perm[0:7]
761 #index <- (RS)[8*i:8*i+7]
762 RA <- [0]*56 # || perm[0:7]
768 lexer
= IndentLexer(debug
=1)
769 # Give the lexer some input
778 break # No more input
783 # Set up the GardenSnake run-time environment
786 print ("-->", " ".join(map(str,args
)))
792 sd
= create_sigdecode()
793 print ("forms", sd
.df
.forms
)
794 for f
in sd
.df
.FormX
:
797 _compile
= GardenSnakeCompiler().compile
799 tree
= _compile(code
, mode
="single", filename
="string")
801 tree
= ast
.fix_missing_locations(tree
)
802 print ( ast
.dump(tree
) )
806 print (astor
.dump_tree(tree
))
808 source
= astor
.to_source(tree
)
811 #from compiler import parse
812 #tree = parse(code, "exec")
814 print (compiled_code
)
816 exec (compiled_code
, d
)