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