class decl cleanup
[sv2nmigen.git] / absyn.py
1 from lib2to3.pytree import Node, Leaf
2 from lib2to3.pgen2 import token
3 from lib2to3.pygram import python_symbols as syms
4
5 preamble = """# this file has been generated by sv2nmigen
6
7 from nmigen import Signal, Module, Const, Cat, Elaboratable
8
9
10
11 """
12
13 indent_debug = 0
14
15 class Absyn:
16 def __init__(self):
17 self.outputfile = open("output.py","w")
18 self.outputfile.write(preamble)
19 def printpy(self,p):
20 self.outputfile.write(str(p)+"\n")
21 def assign(self,p):
22 p = list(p)
23 if(p[1]=="assign"):
24 self.printpy(p[4])
25 # m.d.comb += [l.eq(r)]
26 def indent(self,count):
27 if(indent_debug):
28 return Leaf(token.INDENT, '>>> '*count)
29 else:
30 return Leaf(token.INDENT, ' '*4*count)
31
32 def dedent(self,count):
33 return Leaf(token.DEDENT, '')
34 def nl(self):
35 return Leaf(token.NEWLINE, '#\n')
36
37 def initPorts(self,params,ports):
38 pass_stmt = Node(syms.pass_stmt ,[Leaf(token.NAME, "def __init__(self):")])
39 if params:
40 params = [Leaf(token.LPAR, '(')] + params + [Leaf(token.RPAR, ')')]
41 fn = [Leaf(token.NAME, 'def'),
42 Leaf(token.NAME, '__initXXX__', prefix=' '),
43 Node(syms.parameters, params),
44 Leaf(token.COLON, ':')]
45 fndef = Node(syms.funcdef, fn)
46 stmts = Node(syms.stmt, [fndef])
47 else:
48 stmts = Node(syms.small_stmt, [pass_stmt, Leaf(token.NEWLINE, '\n')])
49 stmts = Node(syms.stmt, [stmts])
50
51 for port in ports:
52 stmts.children.append(self.indent(2))
53 stmts.children.append(port)
54 stmts.children.append(self.nl())
55
56 return stmts
57
58
59 def module_1(self,p):
60 params = p[7]
61 ports = p[8]
62 clsname = [Leaf(token.NAME, 'class'),
63 Leaf(token.NAME, p[4], prefix=' '),
64 Leaf(token.LPAR,'('),
65 Leaf(token.NAME, 'Elaboratable'),
66 Leaf(token.LPAR,')'),
67 Leaf(token.COLON, ':'),
68 ]
69
70 suite = Node(syms.suite, [Leaf(token.NEWLINE, '\n'),
71 self.indent(1),
72 self.initPorts(params,ports),
73 self.dedent(1)
74 ])
75 clsdecl = Node(syms.classdef, clsname + [suite])
76 clsdecl = Node(syms.compound_stmt, [clsdecl])
77 #.printpy("#clsdecl"+ repr(clsdecl))
78 #absyn.printpy("#clsstr:")
79 self.printpy(str(clsdecl))
80 return clsdecl