whitespace pep8 cleanup
[pinmux.git] / src / bsv / interface_decl.py
1 import os.path
2
3 try:
4 from UserDict import UserDict
5 except ImportError:
6 from collections import UserDict
7
8 from bsv.wire_def import generic_io # special case
9 from bsv.wire_def import muxwire # special case
10 from ifacebase import InterfacesBase
11
12
13 class Pin(object):
14 """ pin interface declaration.
15 * name is the name of the pin
16 * ready, enabled and io all create a (* .... *) prefix
17 * action changes it to an "in" if true
18 """
19
20 def __init__(self, name,
21 ready=True,
22 enabled=True,
23 io=False,
24 action=False,
25 bitspec=None,
26 outenmode=False):
27 self.name = name
28 self.ready = ready
29 self.enabled = enabled
30 self.io = io
31 self.action = action
32 self.bitspec = bitspec if bitspec else 'Bit#(1)'
33 self.outenmode = outenmode
34
35 # bsv will look like this (method declaration):
36 """
37 (*always_ready,always_enabled*) method Bit#(1) io0_cell_outen;
38 (*always_ready,always_enabled,result="io"*) method
39 Action io0_inputval (Bit#(1) in);
40 """
41
42 def ifacefmt(self, fmtfn):
43 res = ' '
44 status = []
45 if self.ready:
46 status.append('always_ready')
47 if self.enabled:
48 status.append('always_enabled')
49 if self.io:
50 status.append('result="io"')
51 if status:
52 res += '(*'
53 res += ','.join(status)
54 res += '*)'
55 res += " method "
56 if self.io:
57 res += "\n "
58 name = fmtfn(self.name)
59 if self.action:
60 res += " Action "
61 res += name
62 res += ' (%s in)' % self.bitspec
63 else:
64 res += " %s " % self.bitspec
65 res += name
66 res += ";"
67 return res
68
69 # sample bsv method definition :
70 """
71 method Action cell0_mux(Bit#(2) in);
72 wrcell0_mux<=in;
73 endmethod
74 """
75
76 def ifacedef(self, fmtoutfn, fmtinfn, fmtdecfn):
77 res = ' method '
78 if self.action:
79 fmtname = fmtinfn(self.name)
80 res += "Action "
81 res += fmtdecfn(self.name)
82 res += '(%s in);\n' % self.bitspec
83 res += ' %s<=in;\n' % fmtname
84 res += ' endmethod'
85 else:
86 fmtname = fmtoutfn(self.name)
87 res += "%s=%s;" % (self.name, fmtname)
88 return res
89 # sample bsv wire (wire definiton):
90 """
91 Wire#(Bit#(2)) wrcell0_mux<-mkDWire(0);
92 """
93
94 def wirefmt(self, fmtoutfn, fmtinfn, fmtdecfn):
95 res = ' Wire#(%s) ' % self.bitspec
96 if self.action:
97 res += '%s' % fmtinfn(self.name)
98 else:
99 res += '%s' % fmtoutfn(self.name)
100 res += "<-mkDWire(0);"
101 return res
102
103
104 class Interface(object):
105 """ create an interface from a list of pinspecs.
106 each pinspec is a dictionary, see Pin class arguments
107 single indicates that there is only one of these, and
108 so the name must *not* be extended numerically (see pname)
109 """
110 # sample interface object:
111 """
112 twiinterface_decl = Interface('twi',
113 [{'name': 'sda', 'outen': True},
114 {'name': 'scl', 'outen': True},
115 ])
116 """
117
118 def __init__(self, ifacename, pinspecs, ganged=None, single=False):
119 self.ifacename = ifacename
120 self.ganged = ganged or {}
121 self.pins = [] # a list of instances of class Pin
122 self.pinspecs = pinspecs # a list of dictionary
123 self.single = single
124 for p in pinspecs:
125 _p = {}
126 _p.update(p)
127 if p.get('outen') is True: # special case, generate 3 pins
128 del _p['outen']
129 for psuffix in ['out', 'outen', 'in']:
130 # changing the name (like sda) to (twi_sda_out)
131 _p['name'] = "%s_%s" % (self.pname(p['name']), psuffix)
132 _p['action'] = psuffix != 'in'
133 self.pins.append(Pin(**_p))
134 # will look like {'name': 'twi_sda_out', 'action': True}
135 # {'name': 'twi_sda_outen', 'action': True}
136 #{'name': 'twi_sda_in', 'action': False}
137 # NOTice - outen key is removed
138 else:
139 _p['name'] = self.pname(p['name'])
140 self.pins.append(Pin(**_p))
141
142 # sample interface object:
143 """
144 uartinterface_decl = Interface('uart',
145 [{'name': 'rx'},
146 {'name': 'tx', 'action': True},
147 ])
148 """
149 """
150 getifacetype is called multiple times in actual_pinmux.py
151 x = ifaces.getifacetype(temp), where temp is uart_rx, spi_mosi
152 Purpose is to identify is function : input/output/inout
153 """
154
155 def getifacetype(self, name):
156 for p in self.pinspecs:
157 fname = "%s_%s" % (self.ifacename, p['name'])
158 #print "search", self.ifacename, name, fname
159 if fname == name:
160 if p.get('action'):
161 return 'out'
162 elif p.get('outen'):
163 return 'inout'
164 return 'input'
165 return None
166
167 def pname(self, name):
168 """ generates the interface spec e.g. flexbus_ale
169 if there is only one flexbus interface, or
170 sd{0}_cmd if there are several. string format
171 function turns this into sd0_cmd, sd1_cmd as
172 appropriate. single mode stops the numerical extension.
173 """
174 if self.single:
175 return '%s_%s' % (self.ifacename, name)
176 return '%s{0}_%s' % (self.ifacename, name)
177
178 def busfmt(self, *args):
179 """ this function creates a bus "ganging" system based
180 on input from the {interfacename}.txt file.
181 only inout pins that are under the control of the
182 interface may be "ganged" together.
183 """
184 if not self.ganged:
185 return '' # when self.ganged is None
186 #print self.ganged
187 res = []
188 for (k, pnames) in self.ganged.items():
189 name = self.pname('%senable' % k).format(*args)
190 decl = 'Bit#(1) %s = 0;' % name
191 res.append(decl)
192 ganged = []
193 for p in self.pinspecs:
194 if p['name'] not in pnames:
195 continue
196 pname = self.pname(p['name']).format(*args)
197 if p.get('outen') is True:
198 outname = self.ifacefmtoutfn(pname)
199 ganged.append("%s_outen" % outname) # match wirefmt
200
201 gangedfmt = '{%s} = duplicate(%s);'
202 res.append(gangedfmt % (',\n '.join(ganged), name))
203 return '\n'.join(res) + '\n\n'
204
205 def wirefmt(self, *args):
206 res = '\n'.join(map(self.wirefmtpin, self.pins)).format(*args)
207 res += '\n'
208 return '\n' + res
209
210 def ifacefmt(self, *args):
211 res = '\n'.join(map(self.ifacefmtdecpin, self.pins)).format(*args)
212 return '\n' + res # pins is a list
213
214 def ifacefmtdecfn(self, name):
215 return name # like: uart
216
217 def ifacefmtdecfn2(self, name):
218 return name # like: uart
219
220 def ifacefmtdecfn3(self, name):
221 """ HACK! """
222 return "%s_outen" % name # like uart_outen
223
224 def ifacefmtoutfn(self, name):
225 return "wr%s" % name # like wruart
226
227 def ifacefmtinfn(self, name):
228 return "wr%s" % name
229
230 def wirefmtpin(self, pin):
231 return pin.wirefmt(self.ifacefmtoutfn, self.ifacefmtinfn,
232 self.ifacefmtdecfn2)
233
234 def ifacefmtdecpin(self, pin):
235 return pin.ifacefmt(self.ifacefmtdecfn)
236
237 def ifacefmtpin(self, pin):
238 decfn = self.ifacefmtdecfn2
239 outfn = self.ifacefmtoutfn
240 #print pin, pin.outenmode
241 if pin.outenmode:
242 decfn = self.ifacefmtdecfn3
243 outfn = self.ifacefmtoutenfn
244 return pin.ifacedef(outfn, self.ifacefmtinfn,
245 decfn)
246
247 def ifacedef(self, *args):
248 res = '\n'.join(map(self.ifacefmtpin, self.pins))
249 res = res.format(*args)
250 return '\n' + res + '\n'
251
252
253 class MuxInterface(Interface):
254
255 def wirefmt(self, *args):
256 return muxwire.format(*args)
257
258
259 class IOInterface(Interface):
260
261 def ifacefmtoutenfn(self, name):
262 return "cell{0}_mux_outen"
263
264 def ifacefmtoutfn(self, name):
265 """ for now strip off io{0}_ part """
266 return "cell{0}_mux_out"
267
268 def ifacefmtinfn(self, name):
269 return "cell{0}_mux_in"
270
271 def wirefmt(self, *args):
272 return generic_io.format(*args)
273
274
275 class Interfaces(InterfacesBase):
276 """ contains a list of interface definitions
277 """
278
279 def __init__(self, pth=None):
280 InterfacesBase.__init__(self, Interface, pth)
281
282 def ifacedef(self, f, *args):
283 for (name, count) in self.ifacecount:
284 for i in range(count):
285 f.write(self.data[name].ifacedef(i))
286
287 def busfmt(self, f, *args):
288 f.write("import BUtils::*;\n\n")
289 for (name, count) in self.ifacecount:
290 for i in range(count):
291 bf = self.data[name].busfmt(i)
292 f.write(bf)
293
294 def ifacefmt(self, f, *args):
295 comment = '''
296 // interface declaration between %s-{0} and pinmux'''
297 for (name, count) in self.ifacecount:
298 for i in range(count):
299 c = comment % name.upper()
300 f.write(c.format(i))
301 f.write(self.data[name].ifacefmt(i))
302
303 def wirefmt(self, f, *args):
304 comment = '\n // following wires capture signals ' \
305 'to IO CELL if %s-{0} is\n' \
306 ' // allotted to it'
307 for (name, count) in self.ifacecount:
308 for i in range(count):
309 c = comment % name
310 f.write(c.format(i))
311 f.write(self.data[name].wirefmt(i))
312
313
314 # ========= Interface declarations ================ #
315
316 mux_interface = MuxInterface('cell',
317 [{'name': 'mux', 'ready': False, 'enabled': False,
318 'bitspec': '{1}', 'action': True}])
319
320 io_interface = IOInterface(
321 'io',
322 [{'name': 'cell_out', 'enabled': True, },
323 {'name': 'cell_outen', 'enabled': True, 'outenmode': True, },
324 {'name': 'cell_in', 'action': True, 'io': True}, ])
325
326 # == Peripheral Interface definitions == #
327 # these are the interface of the peripherals to the pin mux
328 # Outputs from the peripherals will be inputs to the pinmux
329 # module. Hence the change in direction for most pins
330
331 # ======================================= #
332
333 # basic test
334 if __name__ == '__main__':
335
336 uartinterface_decl = Interface('uart',
337 [{'name': 'rx'},
338 {'name': 'tx', 'action': True},
339 ])
340
341 twiinterface_decl = Interface('twi',
342 [{'name': 'sda', 'outen': True},
343 {'name': 'scl', 'outen': True},
344 ])
345
346 def _pinmunge(p, sep, repl, dedupe=True):
347 """ munges the text so it's easier to compare.
348 splits by separator, strips out blanks, re-joins.
349 """
350 p = p.strip()
351 p = p.split(sep)
352 if dedupe:
353 p = filter(lambda x: x, p) # filter out blanks
354 return repl.join(p)
355
356 def pinmunge(p):
357 """ munges the text so it's easier to compare.
358 """
359 # first join lines by semicolons, strip out returns
360 p = p.split(";")
361 p = map(lambda x: x.replace('\n', ''), p)
362 p = '\n'.join(p)
363 # now split first by brackets, then spaces (deduping on spaces)
364 p = _pinmunge(p, "(", " ( ", False)
365 p = _pinmunge(p, ")", " ) ", False)
366 p = _pinmunge(p, " ", " ")
367 return p
368
369 def zipcmp(l1, l2):
370 l1 = l1.split("\n")
371 l2 = l2.split("\n")
372 for p1, p2 in zip(l1, l2):
373 print (repr(p1))
374 print (repr(p2))
375 print ()
376 assert p1 == p2
377
378 ifaces = Interfaces()
379
380 ifaceuart = ifaces['uart']
381 print (ifaceuart.ifacedef(0))
382 print (uartinterface_decl.ifacedef(0))
383 assert ifaceuart.ifacedef(0) == uartinterface_decl.ifacedef(0)
384
385 ifacetwi = ifaces['twi']
386 print (ifacetwi.ifacedef(0))
387 print (twiinterface_decl.ifacedef(0))
388 assert ifacetwi.ifacedef(0) == twiinterface_decl.ifacedef(0)