9924e126a39a37639896d776b6cabdeae8960e19
[nmigen.git] / nmigen / build / dsl.py
1 from collections import OrderedDict
2
3
4 __all__ = ["Pins", "PinsN", "DiffPairs", "DiffPairsN",
5 "Attrs", "Clock", "Subsignal", "Resource", "Connector"]
6
7
8 class Pins:
9 def __init__(self, names, *, dir="io", invert=False, conn=None, assert_width=None):
10 if not isinstance(names, str):
11 raise TypeError("Names must be a whitespace-separated string, not {!r}"
12 .format(names))
13 names = names.split()
14
15 if conn is not None:
16 conn_name, conn_number = conn
17 if not (isinstance(conn_name, str) and isinstance(conn_number, (int, str))):
18 raise TypeError("Connector must be None or a pair of string (connector name) and "
19 "integer/string (connector number), not {!r}"
20 .format(conn))
21 names = ["{}_{}:{}".format(conn_name, conn_number, name) for name in names]
22
23 if dir not in ("i", "o", "io", "oe"):
24 raise TypeError("Direction must be one of \"i\", \"o\", \"oe\", or \"io\", not {!r}"
25 .format(dir))
26
27 if assert_width is not None and len(names) != assert_width:
28 raise AssertionError("{} names are specified ({}), but {} names are expected"
29 .format(len(names), " ".join(names), assert_width))
30
31 self.names = names
32 self.dir = dir
33 self.invert = bool(invert)
34
35 def __len__(self):
36 return len(self.names)
37
38 def __iter__(self):
39 return iter(self.names)
40
41 def map_names(self, mapping, resource):
42 mapped_names = []
43 for name in self.names:
44 while ":" in name:
45 if name not in mapping:
46 raise NameError("Resource {!r} refers to nonexistent connector pin {}"
47 .format(resource, name))
48 name = mapping[name]
49 mapped_names.append(name)
50 return mapped_names
51
52 def __repr__(self):
53 return "(pins{} {} {})".format("-n" if self.invert else "",
54 self.dir, " ".join(self.names))
55
56
57 def PinsN(*args, **kwargs):
58 pins = Pins(*args, **kwargs)
59 pins.invert = True
60 return pins
61
62
63 class DiffPairs:
64 def __init__(self, p, n, *, dir="io", conn=None, assert_width=None):
65 self.p = Pins(p, dir=dir, conn=conn, assert_width=assert_width)
66 self.n = Pins(n, dir=dir, conn=conn, assert_width=assert_width)
67
68 if len(self.p.names) != len(self.n.names):
69 raise TypeError("Positive and negative pins must have the same width, but {!r} "
70 "and {!r} do not"
71 .format(self.p, self.n))
72
73 self.dir = dir
74 self.invert = False
75
76 def __len__(self):
77 return len(self.p.names)
78
79 def __iter__(self):
80 return zip(self.p.names, self.n.names)
81
82 def __repr__(self):
83 return "(diffpairs{} {} (p {}) (n {}))".format("-n" if self.invert else "",
84 self.dir, " ".join(self.p.names), " ".join(self.n.names))
85
86
87 def DiffPairsN(*args, **kwargs):
88 diff_pairs = DiffPairs(*args, **kwargs)
89 diff_pairs.invert = True
90 return diff_pairs
91
92
93 class Attrs(OrderedDict):
94 def __init__(self, **attrs):
95 for key, value in attrs.items():
96 if not (value is None or isinstance(value, (str, int)) or hasattr(value, "__call__")):
97 raise TypeError("Value of attribute {} must be None, int, str, or callable, "
98 "not {!r}"
99 .format(key, value))
100
101 super().__init__(**attrs)
102
103 def __repr__(self):
104 items = []
105 for key, value in self.items():
106 if value is None:
107 items.append("!" + key)
108 else:
109 items.append(key + "=" + repr(value))
110 return "(attrs {})".format(" ".join(items))
111
112
113 class Clock:
114 def __init__(self, frequency):
115 if not isinstance(frequency, (float, int)):
116 raise TypeError("Clock frequency must be a number")
117
118 self.frequency = float(frequency)
119
120 @property
121 def period(self):
122 return 1 / self.frequency
123
124 def __repr__(self):
125 return "(clock {})".format(self.frequency)
126
127
128 class Subsignal:
129 def __init__(self, name, *args):
130 self.name = name
131 self.ios = []
132 self.attrs = Attrs()
133 self.clock = None
134
135 if not args:
136 raise ValueError("Missing I/O constraints")
137 for arg in args:
138 if isinstance(arg, (Pins, DiffPairs)):
139 if not self.ios:
140 self.ios.append(arg)
141 else:
142 raise TypeError("Pins and DiffPairs are incompatible with other location or "
143 "subsignal constraints, but {!r} appears after {!r}"
144 .format(arg, self.ios[-1]))
145 elif isinstance(arg, Subsignal):
146 if not self.ios or isinstance(self.ios[-1], Subsignal):
147 self.ios.append(arg)
148 else:
149 raise TypeError("Subsignal is incompatible with location constraints, but "
150 "{!r} appears after {!r}"
151 .format(arg, self.ios[-1]))
152 elif isinstance(arg, Attrs):
153 self.attrs.update(arg)
154 elif isinstance(arg, Clock):
155 if self.ios and isinstance(self.ios[-1], (Pins, DiffPairs)):
156 if self.clock is None:
157 self.clock = arg
158 else:
159 raise ValueError("Clock constraint can be applied only once")
160 else:
161 raise TypeError("Clock constraint can only be applied to Pins or DiffPairs, "
162 "not {!r}"
163 .format(self.ios[-1]))
164 else:
165 raise TypeError("Constraint must be one of Pins, DiffPairs, Subsignal, Attrs, "
166 "or Clock, not {!r}"
167 .format(arg))
168
169 def _content_repr(self):
170 parts = []
171 for io in self.ios:
172 parts.append(repr(io))
173 if self.clock is not None:
174 parts.append(repr(self.clock))
175 if self.attrs:
176 parts.append(repr(self.attrs))
177 return " ".join(parts)
178
179 def __repr__(self):
180 return "(subsignal {} {})".format(self.name, self._content_repr())
181
182
183 class Resource(Subsignal):
184 @classmethod
185 def family(cls, name_or_number, number=None, *, ios, default_name, name_suffix=""):
186 # This constructor accepts two different forms:
187 # 1. Number-only form:
188 # Resource.family(0, default_name="name", ios=[Pins("A0 A1")])
189 # 2. Name-and-number (name override) form:
190 # Resource.family("override", 0, default_name="name", ios=...)
191 # This makes it easier to build abstractions for resources, e.g. an SPIResource abstraction
192 # could simply delegate to `Resource.family(*args, default_name="spi", ios=ios)`.
193 # The name_suffix argument is meant to support creating resources with
194 # similar names, such as spi_flash, spi_flash_2x, etc.
195 if name_suffix: # Only add "_" if we actually have a suffix.
196 name_suffix = "_" + name_suffix
197
198 if number is None: # name_or_number is number
199 return cls(default_name + name_suffix, name_or_number, *ios)
200 else: # name_or_number is name
201 return cls(name_or_number + name_suffix, number, *ios)
202
203 def __init__(self, name, number, *args):
204 super().__init__(name, *args)
205
206 self.number = number
207
208 def __repr__(self):
209 return "(resource {} {} {})".format(self.name, self.number, self._content_repr())
210
211
212 class Connector:
213 def __init__(self, name, number, io, *, conn=None):
214 self.name = name
215 self.number = number
216 mapping = OrderedDict()
217
218 if isinstance(io, dict):
219 for conn_pin, plat_pin in io.items():
220 if not isinstance(conn_pin, str):
221 raise TypeError("Connector pin name must be a string, not {!r}"
222 .format(conn_pin))
223 if not isinstance(plat_pin, str):
224 raise TypeError("Platform pin name must be a string, not {!r}"
225 .format(plat_pin))
226 mapping[conn_pin] = plat_pin
227
228 elif isinstance(io, str):
229 for conn_pin, plat_pin in enumerate(io.split(), start=1):
230 if plat_pin == "-":
231 continue
232
233 mapping[str(conn_pin)] = plat_pin
234 else:
235 raise TypeError("Connector I/Os must be a dictionary or a string, not {!r}"
236 .format(io))
237
238 if conn is not None:
239 conn_name, conn_number = conn
240 if not (isinstance(conn_name, str) and isinstance(conn_number, (int, str))):
241 raise TypeError("Connector must be None or a pair of string (connector name) and "
242 "integer/string (connector number), not {!r}"
243 .format(conn))
244
245 for conn_pin, plat_pin in mapping.items():
246 mapping[conn_pin] = "{}_{}:{}".format(conn_name, conn_number, plat_pin)
247
248 self.mapping = mapping
249
250 def __repr__(self):
251 return "(connector {} {} {})".format(self.name, self.number,
252 " ".join("{}=>{}".format(conn, plat)
253 for conn, plat in self.mapping.items()))
254
255 def __len__(self):
256 return len(self.mapping)
257
258 def __iter__(self):
259 for conn_pin, plat_pin in self.mapping.items():
260 yield "{}_{}:{}".format(self.name, self.number, conn_pin), plat_pin