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 from soc
.decoder
.power_decoder
import create_pdecode
18 from nmigen
.back
.pysim
import Simulator
, Delay
19 from nmigen
import Module
, Signal
22 # I use the Python AST
23 #from compiler import ast
27 def Assign(left
, right
):
29 if isinstance(left
, ast
.Name
):
30 # Single assignment on left
31 return ast
.Assign([ast
.Name(left
.id, ast
.Store())], right
)
32 elif isinstance(left
, ast
.Tuple
):
33 # List of things - make sure they are Name nodes
35 for child
in left
.getChildren():
36 if not isinstance(child
, ast
.Name
):
37 raise SyntaxError("that assignment not supported")
38 names
.append(child
.name
)
39 ass_list
= [ast
.AssName(name
, 'OP_ASSIGN') for name
in names
]
40 return ast
.Assign([ast
.AssTuple(ass_list
)], right
)
42 raise SyntaxError("Can't do that yet")
45 ## I implemented INDENT / DEDENT generation as a post-processing filter
47 # The original lex token stream contains WS and NEWLINE characters.
48 # WS will only occur before any other tokens on a line.
50 # I have three filters. One tags tokens by adding two attributes.
51 # "must_indent" is True if the token must be indented from the
52 # previous code. The other is "at_line_start" which is True for WS
53 # and the first non-WS/non-NEWLINE on a line. It flags the check so
54 # see if the new line has changed indication level.
56 # Python's syntax has three INDENT states
57 # 0) no colon hence no need to indent
58 # 1) "if 1: go()" - simple statements have a COLON but no need for an indent
59 # 2) "if 1:\n go()" - complex statements have a COLON NEWLINE and must indent
64 # turn into python-like colon syntax from pseudo-code syntax
65 def python_colonify(lexer
, tokens
):
69 #print ("track colon token", token, token.type)
71 if token
.type == 'THEN':
72 # turn then into colon
75 elif token
.type == 'ELSE':
80 elif token
.type in ['WHILE', 'FOR']:
83 elif token
.type == 'NEWLINE':
94 # only care about whitespace at the start of a line
95 def track_tokens_filter(lexer
, tokens
):
96 oldignore
= lexer
.lexignore
97 lexer
.at_line_start
= at_line_start
= True
101 #print ("track token", token, token.type)
102 token
.at_line_start
= at_line_start
104 if token
.type == "COLON":
105 at_line_start
= False
107 token
.must_indent
= False
109 elif token
.type == "NEWLINE":
111 if indent
== MAY_INDENT
:
113 token
.must_indent
= False
115 elif token
.type == "WS":
116 assert token
.at_line_start
== True
118 token
.must_indent
= False
121 # A real token; only indent after COLON NEWLINE
122 if indent
== MUST_INDENT
:
123 token
.must_indent
= True
125 token
.must_indent
= False
126 at_line_start
= False
129 # really bad hack that changes ignore lexer state.
130 # when "must indent" is seen (basically "real tokens" seen)
131 # then ignore whitespace.
132 if token
.must_indent
:
133 lexer
.lexignore
= ('ignore', ' ')
135 lexer
.lexignore
= oldignore
137 token
.indent
= indent
139 lexer
.at_line_start
= at_line_start
141 def _new_token(type, lineno
):
149 # Synthesize a DEDENT tag
151 return _new_token("DEDENT", lineno
)
153 # Synthesize an INDENT tag
155 return _new_token("INDENT", lineno
)
158 # Track the indentation level and emit the right INDENT / DEDENT events.
159 def indentation_filter(tokens
):
160 # A stack of indentation levels; will never pop item 0
167 print ("Process", depth
, token
.indent
, token
,)
168 if token
.at_line_start
:
169 print ("at_line_start",)
170 if token
.must_indent
:
171 print ("must_indent",)
174 # WS only occurs at the start of the line
175 # There may be WS followed by NEWLINE so
176 # only track the depth here. Don't indent/dedent
177 # until there's something real.
178 if token
.type == "WS":
180 depth
= len(token
.value
)
182 # WS tokens are never passed to the parser
185 if token
.type == "NEWLINE":
187 if prev_was_ws
or token
.at_line_start
:
190 # pass the other cases on through
194 # then it must be a real token (not WS, not NEWLINE)
195 # which can affect the indentation level
198 if token
.must_indent
:
199 # The current depth must be larger than the previous level
200 if not (depth
> levels
[-1]):
201 raise IndentationError("expected an indented block")
204 yield INDENT(token
.lineno
)
206 elif token
.at_line_start
:
207 # Must be on the same level or one of the previous levels
208 if depth
== levels
[-1]:
211 elif depth
> levels
[-1]:
212 raise IndentationError("indent increase but not in new block")
214 # Back up; but only if it matches a previous level
216 i
= levels
.index(depth
)
218 raise IndentationError("inconsistent indentation")
219 for _
in range(i
+1, len(levels
)):
220 yield DEDENT(token
.lineno
)
225 ### Finished processing ###
227 # Must dedent any remaining levels
229 assert token
is not None
230 for _
in range(1, len(levels
)):
231 yield DEDENT(token
.lineno
)
234 # The top-level filter adds an ENDMARKER, if requested.
235 # Python's grammar uses it.
236 def filter(lexer
, add_endmarker
= True):
238 tokens
= iter(lexer
.token
, None)
239 tokens
= python_colonify(lexer
, tokens
)
240 tokens
= track_tokens_filter(lexer
, tokens
)
241 for token
in indentation_filter(tokens
):
246 if token
is not None:
247 lineno
= token
.lineno
248 yield _new_token("ENDMARKER", lineno
)
250 ## No using Python's approach because Ply supports precedence
252 # comparison: expr (comp_op expr)*
253 # arith_expr: term (('+'|'-') term)*
254 # term: factor (('*'|'/'|'%'|'//') factor)*
255 # factor: ('+'|'-'|'~') factor | power
256 # comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
258 def make_lt_compare(arg
):
260 return ast
.Compare(left
, [ast
.Lt()], [right
])
261 def make_gt_compare(arg
):
263 return ast
.Compare(left
, [ast
.Gt()], [right
])
264 def make_eq_compare(arg
):
266 return ast
.Compare(left
, [ast
.Eq()], [right
])
274 "<": make_lt_compare
,
275 ">": make_gt_compare
,
276 "=": make_eq_compare
,
283 ("left", "EQ", "GT", "LT"),
284 ("left", "PLUS", "MINUS"),
285 ("left", "MULT", "DIV"),
288 def check_concat(node
): # checks if the comparison is already a concat
290 if not isinstance(node
, ast
.Call
):
292 if node
[0].id != 'concat':
311 'NUMBER', # Python decimals
312 'BINARY', # Python binary
313 'STRING', # single quoted strings only; syntax of raw strings
339 def build(self
,**kwargs
):
340 self
.lexer
= lex
.lex(module
=self
, **kwargs
)
342 def t_BINARY(self
, t
):
344 t
.value
= int(t
.value
, 2)
348 # taken from decmial.py but without the leading sign
349 def t_NUMBER(self
, t
):
350 r
"""(\d+(\.\d*)?|\.\d+)([eE][-+]? \d+)?"""
351 t
.value
= int(t
.value
)
354 def t_STRING(self
, t
):
355 r
"'([^\\']+|\\'|\\\\)*'" # I think this is right ...
356 t
.value
=t
.value
[1:-1].decode("string-escape") # .swapcase() # for fun
372 # Ply nicely documented how to do this.
388 r
'[a-zA-Z_][a-zA-Z0-9_]*'
389 t
.type = self
.RESERVED
.get(t
.value
, "NAME")
392 # Putting this before t_WS let it consume lines with only comments in
393 # them so the latter code never sees the WS part. Not consuming the
394 # newline. Needed for "if 1: #comment"
395 def t_comment(self
, t
):
396 r
"[ ]*\043[^\n]*" # \043 is '#'
403 if t
.lexer
.at_line_start
and t
.lexer
.paren_count
== 0 and \
404 t
.lexer
.brack_count
== 0:
407 # Don't generate newline tokens when inside of parenthesis, eg
410 def t_newline(self
, t
):
412 t
.lexer
.lineno
+= len(t
.value
)
414 if t
.lexer
.paren_count
== 0 and t
.lexer
.brack_count
== 0:
417 def t_LBRACK(self
, t
):
419 t
.lexer
.brack_count
+= 1
422 def t_RBRACK(self
, t
):
424 # check for underflow? should be the job of the parser
425 t
.lexer
.brack_count
-= 1
430 t
.lexer
.paren_count
+= 1
435 # check for underflow? should be the job of the parser
436 t
.lexer
.paren_count
-= 1
441 def t_error(self
, t
):
442 raise SyntaxError("Unknown symbol %r" % (t
.value
[0],))
443 print ("Skipping", repr(t
.value
[0]))
446 # Combine Ply and my filters into a new lexer
448 class IndentLexer(PowerLexer
):
449 def __init__(self
, debug
=0, optimize
=0, lextab
='lextab', reflags
=0):
450 self
.build(debug
=debug
, optimize
=optimize
,
451 lextab
=lextab
, reflags
=reflags
)
452 self
.token_stream
= None
453 def input(self
, s
, add_endmarker
=True):
454 self
.lexer
.paren_count
= 0
455 self
.lexer
.brack_count
= 0
457 self
.token_stream
= filter(self
.lexer
, add_endmarker
)
461 return next(self
.token_stream
)
462 except StopIteration:
466 ########## Parser (tokens -> AST) ######
475 for rname
in ['RA', 'RB', 'RC', 'RT', 'RS']:
476 self
.gprs
[rname
] = None
480 # The grammar comments come from Python's Grammar/Grammar file
482 ## NB: compound_stmt in single_input is followed by extra NEWLINE!
483 # file_input: (NEWLINE | stmt)* ENDMARKER
485 def p_file_input_end(self
, p
):
486 """file_input_end : file_input ENDMARKER"""
490 def p_file_input(self
, p
):
491 """file_input : file_input NEWLINE
495 if isinstance(p
[len(p
)-1], str):
499 p
[0] = [] # p == 2 --> only a blank line
507 # funcdef: [decorators] 'def' NAME parameters ':' suite
508 # ignoring decorators
509 def p_funcdef(self
, p
):
510 "funcdef : DEF NAME parameters COLON suite"
511 p
[0] = ast
.FunctionDef(p
[2], p
[3], p
[5], ())
513 # parameters: '(' [varargslist] ')'
514 def p_parameters(self
, p
):
515 """parameters : LPAR RPAR
516 | LPAR varargslist RPAR"""
521 p
[0] = ast
.arguments(args
=args
, vararg
=None, kwarg
=None, defaults
=[])
524 # varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' '**' NAME] |
527 def p_varargslist(self
, p
):
528 """varargslist : varargslist COMMA NAME
535 # stmt: simple_stmt | compound_stmt
536 def p_stmt_simple(self
, p
):
537 """stmt : simple_stmt"""
538 # simple_stmt is a list
541 def p_stmt_compound(self
, p
):
542 """stmt : compound_stmt"""
545 # simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
546 def p_simple_stmt(self
, p
):
547 """simple_stmt : small_stmts NEWLINE
548 | small_stmts SEMICOLON NEWLINE"""
551 def p_small_stmts(self
, p
):
552 """small_stmts : small_stmts SEMICOLON small_stmt
559 # small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
560 # import_stmt | global_stmt | exec_stmt | assert_stmt
561 def p_small_stmt(self
, p
):
562 """small_stmt : flow_stmt
565 if isinstance(p
[1], ast
.Call
):
566 p
[0] = ast
.Expr(p
[1])
570 # expr_stmt: testlist (augassign (yield_expr|testlist) |
571 # ('=' (yield_expr|testlist))*)
572 # augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
573 # '<<=' | '>>=' | '**=' | '//=')
574 def p_expr_stmt(self
, p
):
575 """expr_stmt : testlist ASSIGN testlist
578 # a list of expressions
579 #p[0] = ast.Discard(p[1])
582 if p
[1].id in self
.gprs
:
583 self
.write_regs
.append(p
[1].id) # add to list of regs to write
584 p
[0] = Assign(p
[1], p
[3])
586 def p_flow_stmt(self
, p
):
587 "flow_stmt : return_stmt"
590 # return_stmt: 'return' [testlist]
591 def p_return_stmt(self
, p
):
592 "return_stmt : RETURN testlist"
593 p
[0] = ast
.Return(p
[2])
596 def p_compound_stmt(self
, p
):
597 """compound_stmt : if_stmt
604 def p_break_stmt(self
, p
):
605 """break_stmt : BREAK
609 def p_for_stmt(self
, p
):
610 """for_stmt : FOR test EQ test TO test COLON suite
612 p
[0] = ast
.While(p
[2], p
[4], [])
613 # auto-add-one (sigh) due to python range
615 end
= ast
.BinOp(p
[6], ast
.Add(), ast
.Constant(1))
616 it
= ast
.Call(ast
.Name("range"), [start
, end
], [])
617 p
[0] = ast
.For(p
[2], it
, p
[8], [])
619 def p_while_stmt(self
, p
):
620 """while_stmt : DO WHILE test COLON suite ELSE COLON suite
621 | DO WHILE test COLON suite
624 p
[0] = ast
.While(p
[3], p
[5], [])
626 p
[0] = ast
.While(p
[3], p
[5], p
[8])
628 def p_if_stmt(self
, p
):
629 """if_stmt : IF test COLON suite ELSE COLON suite
630 | IF test COLON suite
633 p
[0] = ast
.If(p
[2], p
[4], [])
635 p
[0] = ast
.If(p
[2], p
[4], p
[7])
637 def p_suite(self
, p
):
638 """suite : simple_stmt
639 | NEWLINE INDENT stmts DEDENT"""
646 def p_stmts(self
, p
):
647 """stmts : stmts stmt
654 def p_comparison(self
, p
):
655 """comparison : comparison PLUS comparison
656 | comparison MINUS comparison
657 | comparison MULT comparison
658 | comparison DIV comparison
659 | comparison LT comparison
660 | comparison EQ comparison
661 | comparison GT comparison
664 | comparison APPEND comparison
669 l
= check_concat(p
[1]) + check_concat(p
[3])
670 p
[0] = ast
.Call(ast
.Name("concat"), l
, [])
671 elif p
[2] in ['<', '>', '=']:
672 p
[0] = binary_ops
[p
[2]]((p
[1],p
[3]))
674 p
[0] = ast
.BinOp(p
[1], binary_ops
[p
[2]], p
[3])
676 p
[0] = unary_ops
[p
[1]](p
[2])
680 # power: atom trailer* ['**' factor]
681 # trailers enables function calls (and subscripts).
682 # I only allow one level of calls
683 # so this is 'trailer'
684 def p_power(self
, p
):
690 if p
[2][0] == "CALL":
691 #p[0] = ast.Expr(ast.Call(p[1], p[2][1], []))
692 p
[0] = ast
.Call(p
[1], p
[2][1], [])
693 #if p[1].id == 'print':
694 # p[0] = ast.Printnl(ast.Tuple(p[2][1]), None, None)
696 # p[0] = ast.CallFunc(p[1], p[2][1], None, None)
699 #raise AssertionError("not implemented %s" % p[2][0])
704 idx
= ast
.Slice(subs
[0], subs
[1], None)
705 p
[0] = ast
.Subscript(p
[1], idx
)
707 def p_atom_name(self
, p
):
709 p
[0] = ast
.Name(p
[1], ctx
=ast
.Load())
711 def p_atom_number(self
, p
):
715 p
[0] = ast
.Constant(p
[1])
717 #'[' [listmaker] ']' |
719 def p_atom_listmaker(self
, p
):
720 """atom : LBRACK listmaker RBRACK"""
723 def p_listmaker(self
, p
):
724 """listmaker : test COMMA listmaker
728 p
[0] = ast
.List([p
[1]])
730 p
[0] = ast
.List([p
[1]] + p
[3].nodes
)
732 def p_atom_tuple(self
, p
):
733 """atom : LPAR testlist RPAR"""
734 print ("tuple", p
[2])
735 if isinstance(p
[2], ast
.Name
):
736 print ("tuple name", p
[2].id)
737 if p
[2].id in self
.gprs
:
738 self
.read_regs
.append(p
[2].id) # add to list of regs to read
739 #p[0] = ast.Subscript(ast.Name("GPR"), ast.Str(p[2].id))
743 # trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
744 def p_trailer(self
, p
):
745 """trailer : trailer_arglist
750 def p_trailer_arglist(self
, p
):
751 "trailer_arglist : LPAR arglist RPAR"
752 p
[0] = ("CALL", p
[2])
754 def p_trailer_subscript(self
, p
):
755 "trailer_subscript : LBRACK subscript RBRACK"
756 p
[0] = ("SUBS", p
[2])
758 #subscript: '.' '.' '.' | test | [test] ':' [test]
760 def p_subscript(self
, p
):
761 """subscript : test COLON test
770 # testlist: test (',' test)* [',']
771 # Contains shift/reduce error
772 def p_testlist(self
, p
):
773 """testlist : testlist_multi COMMA
778 # May need to promote singleton to tuple
779 if isinstance(p
[1], list):
783 # Convert into a tuple?
784 if isinstance(p
[0], list):
785 p
[0] = ast
.Tuple(p
[0])
787 def p_testlist_multi(self
, p
):
788 """testlist_multi : testlist_multi COMMA test
794 if isinstance(p
[1], list):
801 # test: or_test ['if' or_test 'else' test] | lambdef
802 # as I don't support 'and', 'or', and 'not' this works down to 'comparison'
809 # arglist: (argument ',')* (argument [',']| '*' test [',' '**' test]
811 # XXX INCOMPLETE: this doesn't allow the trailing comma
812 def p_arglist(self
, p
):
813 """arglist : arglist COMMA argument
820 # argument: test [gen_for] | test '=' test # Really [keyword '='] test
821 def p_argument(self
, p
):
825 def p_error(self
, p
):
826 #print "Error!", repr(p)
830 class GardenSnakeParser(PowerParser
):
831 def __init__(self
, lexer
= None):
832 PowerParser
.__init
__(self
)
834 lexer
= IndentLexer(debug
=1)
836 self
.tokens
= lexer
.tokens
837 self
.parser
= yacc
.yacc(module
=self
, start
="file_input_end",
838 debug
=False, write_tables
=False)
840 self
.sd
= create_pdecode()
842 def parse(self
, code
):
843 self
.lexer
.input(code
)
844 result
= self
.parser
.parse(lexer
= self
.lexer
, debug
=False)
845 return ast
.Module(result
)
848 ###### Code generation ######
850 #from compiler import misc, syntax, pycodegen
852 class GardenSnakeCompiler(object):
854 self
.parser
= GardenSnakeParser()
855 def compile(self
, code
, mode
="exec", filename
="<string>"):
856 tree
= self
.parser
.parse(code
)
860 #misc.set_filename(filename, tree)
861 return compile(tree
, mode
="exec", filename
="<string>")
863 gen
= pycodegen
.ModuleCodeGenerator(tree
)
867 ####### Test code #######
872 index <- (RS)[8*i:8*i+7]
873 RA <- [0]*56 || perm[0:7]
878 if index < 64 then index <- 0
889 index <- (RS)[8*i:8*i+7]
894 RA <- [0]*56|| perm[0:7]
900 if (RS)[63-n] = 0b1 then
911 lexer
= IndentLexer(debug
=1)
912 # Give the lexer some input
921 break # No more input
929 l
.append(1 if (num
& (1<<i
)) else 0)
934 def get_reg_hex(reg
):
935 report
= ''.join(map(str, reg
))
936 return hex(int('0b%s' % report
, 2))
939 gsc
= GardenSnakeCompiler()
941 def __init__(self
, sd
, regfile
):
944 self
.regfile
= regfile
948 def set_form(self
, form
):
951 def ___getitem__(self
, attr
):
952 print ("GPR getitem", attr
)
953 getform
= self
.sd
.sigforms
[self
.form
]
954 rnum
= getattr(getform
, attr
)
955 print ("GPR get", rnum
, rnum
, dir(rnum
))
957 print (l
[0]._as
_const
())
959 #print (x, x.value, dir(x))
960 #print (x.value, dir(x.value))
962 return self
.regfile
[rnum
]
968 gsc
.gpr
= GPR(gsc
.parser
.sd
, gsc
.regfile
)
970 _compile
= gsc
.compile
973 tree
= _compile(code
, mode
="single", filename
="string")
975 tree
= ast
.fix_missing_locations(tree
)
976 print ( ast
.dump(tree
) )
979 print (astor
.dump_tree(tree
))
981 source
= astor
.to_source(tree
)
986 # Set up the GardenSnake run-time environment
989 print ("-->", " ".join(map(str,args
)))
991 def listconcat(l1
, l2
):
994 from soc
.decoder
.helpers
import (EXTS64
, EXTZ64
, ROTL64
, ROTL32
, MASK
,)
1000 d
["concat"] = listconcat
1004 gsc
.gpr
.set_form(form
)
1005 getform
= gsc
.parser
.sd
.sigforms
[form
]._asdict
()
1006 #print ("getform", form)
1007 #for k, f in getform.items():
1011 compiled_code
= compile(source
, mode
="exec", filename
="<string>")
1015 instruction
= Signal(32)
1017 m
.submodules
.decode
= decode
= gsc
.parser
.sd
1018 comb
+= decode
.raw_opcode_in
.eq(instruction
)
1021 instr
= [0x11111117]
1025 print("0x{:X}".format(ins
& 0xffffffff))
1027 # ask the decoder to decode this binary data (endian'd)
1028 yield decode
.bigendian
.eq(0) # little / big?
1029 yield instruction
.eq(ins
) # raw binary instr.
1032 # read regs, drop them into dict for function
1033 for rname
in gsc
.parser
.read_regs
:
1034 regidx
= yield getattr(decode
.sigforms
['X'], rname
)
1035 d
[rname
] = gsc
.gpr
[regidx
]
1036 print ("read reg", rname
, regidx
, get_reg_hex(d
[rname
]))
1038 exec (compiled_code
, d
)
1043 print (decode
.sigforms
['X'])
1044 x
= yield decode
.sigforms
['X'].RS
1045 ra
= yield decode
.sigforms
['X'].RA
1046 print ("RA", ra
, d
['RA'])
1049 for wname
in gsc
.parser
.write_regs
:
1050 reg
= getform
[wname
]
1051 print ("write regs", wname
, d
[wname
], reg
)
1053 gsc
.gpr
[regidx
] = tolist(d
[wname
])
1055 sim
.add_process(process
)
1056 with sim
.write_vcd("simulator.vcd", "simulator.gtkw",
1057 traces
=[decode
.ports()]):
1060 for i
in range(len(gsc
.gpr
)):
1061 print ("regfile", i
, get_reg_hex(gsc
.gpr
[i
]))
1064 if __name__
== '__main__':