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