build.{dsl,res}: allow removing attributes from subsignals.
[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", 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)):
18 raise TypeError("Connector must be None or a pair of string and integer, not {!r}"
19 .format(conn))
20 names = ["{}_{}:{}".format(conn_name, conn_number, name) for name in names]
21
22 if dir not in ("i", "o", "io", "oe"):
23 raise TypeError("Direction must be one of \"i\", \"o\", \"oe\", or \"io\", not {!r}"
24 .format(dir))
25
26 if assert_width is not None and len(names) != assert_width:
27 raise AssertionError("{} names are specified ({}), but {} names are expected"
28 .format(len(names), " ".join(names), assert_width))
29
30 self.names = names
31 self.dir = dir
32 self.invert = False
33
34 def __len__(self):
35 return len(self.names)
36
37 def __iter__(self):
38 return iter(self.names)
39
40 def map_names(self, mapping, resource):
41 mapped_names = []
42 for name in self.names:
43 while ":" in name:
44 if name not in mapping:
45 raise NameError("Resource {!r} refers to nonexistent connector pin {}"
46 .format(resource, name))
47 name = mapping[name]
48 mapped_names.append(name)
49 return mapped_names
50
51 def __repr__(self):
52 return "(pins{} {} {})".format("-n" if self.invert else "",
53 self.dir, " ".join(self.names))
54
55
56 def PinsN(*args, **kwargs):
57 pins = Pins(*args, **kwargs)
58 pins.invert = True
59 return pins
60
61
62 class DiffPairs:
63 def __init__(self, p, n, *, dir="io", conn=None, assert_width=None):
64 self.p = Pins(p, dir=dir, conn=conn, assert_width=assert_width)
65 self.n = Pins(n, dir=dir, conn=conn, assert_width=assert_width)
66
67 if len(self.p.names) != len(self.n.names):
68 raise TypeError("Positive and negative pins must have the same width, but {!r} "
69 "and {!r} do not"
70 .format(self.p, self.n))
71
72 self.dir = dir
73 self.invert = False
74
75 def __len__(self):
76 return len(self.p.names)
77
78 def __iter__(self):
79 return zip(self.p.names, self.n.names)
80
81 def __repr__(self):
82 return "(diffpairs{} {} (p {}) (n {}))".format("-n" if self.invert else "",
83 self.dir, " ".join(self.p.names), " ".join(self.n.names))
84
85
86 def DiffPairsN(*args, **kwargs):
87 diff_pairs = DiffPairs(*args, **kwargs)
88 diff_pairs.invert = True
89 return diff_pairs
90
91
92 class Attrs(OrderedDict):
93 def __init__(self, **attrs):
94 for attr_key, attr_value in attrs.items():
95 if not (attr_value is None or isinstance(attr_value, str)):
96 raise TypeError("Attribute value must be None or str, not {!r}"
97 .format(attr_value))
98
99 super().__init__(**attrs)
100
101 def __repr__(self):
102 items = []
103 for key, value in self.items():
104 if value is None:
105 items.append("!" + key)
106 else:
107 items.append(key + "=" + value)
108 return "(attrs {})".format(" ".join(items))
109
110
111 class Clock:
112 def __init__(self, frequency):
113 if not isinstance(frequency, (float, int)):
114 raise TypeError("Clock frequency must be a number")
115
116 self.frequency = float(frequency)
117
118 @property
119 def period(self):
120 return 1 / self.frequency
121
122 def __repr__(self):
123 return "(clock {})".format(self.frequency)
124
125
126 class Subsignal:
127 def __init__(self, name, *args):
128 self.name = name
129 self.ios = []
130 self.attrs = Attrs()
131 self.clock = None
132
133 if not args:
134 raise ValueError("Missing I/O constraints")
135 for arg in args:
136 if isinstance(arg, (Pins, DiffPairs)):
137 if not self.ios:
138 self.ios.append(arg)
139 else:
140 raise TypeError("Pins and DiffPairs are incompatible with other location or "
141 "subsignal constraints, but {!r} appears after {!r}"
142 .format(arg, self.ios[-1]))
143 elif isinstance(arg, Subsignal):
144 if not self.ios or isinstance(self.ios[-1], Subsignal):
145 self.ios.append(arg)
146 else:
147 raise TypeError("Subsignal is incompatible with location constraints, but "
148 "{!r} appears after {!r}"
149 .format(arg, self.ios[-1]))
150 elif isinstance(arg, Attrs):
151 self.attrs.update(arg)
152 elif isinstance(arg, Clock):
153 if self.ios and isinstance(self.ios[-1], (Pins, DiffPairs)):
154 if self.clock is None:
155 self.clock = arg
156 else:
157 raise ValueError("Clock constraint can be applied only once")
158 else:
159 raise TypeError("Clock constraint can only be applied to Pins or DiffPairs, "
160 "not {!r}"
161 .format(self.ios[-1]))
162 else:
163 raise TypeError("Constraint must be one of Pins, DiffPairs, Subsignal, Attrs, "
164 "or Clock, not {!r}"
165 .format(arg))
166
167 def _content_repr(self):
168 parts = []
169 for io in self.ios:
170 parts.append(repr(io))
171 if self.clock is not None:
172 parts.append(repr(self.clock))
173 if self.attrs:
174 parts.append(repr(self.attrs))
175 return " ".join(parts)
176
177 def __repr__(self):
178 return "(subsignal {} {})".format(self.name, self._content_repr())
179
180
181 class Resource(Subsignal):
182 def __init__(self, name, number, *args):
183 super().__init__(name, *args)
184
185 self.number = number
186
187 def __repr__(self):
188 return "(resource {} {} {})".format(self.name, self.number, self._content_repr())
189
190
191 class Connector:
192 def __init__(self, name, number, io):
193 self.name = name
194 self.number = number
195 self.mapping = OrderedDict()
196
197 if isinstance(io, dict):
198 for conn_pin, plat_pin in io.items():
199 if not isinstance(conn_pin, str):
200 raise TypeError("Connector pin name must be a string, not {!r}"
201 .format(conn_pin))
202 if not isinstance(plat_pin, str):
203 raise TypeError("Platform pin name must be a string, not {!r}"
204 .format(plat_pin))
205 self.mapping[conn_pin] = plat_pin
206
207 elif isinstance(io, str):
208 for conn_pin, plat_pin in enumerate(io.split(), start=1):
209 if plat_pin == "-":
210 continue
211 self.mapping[str(conn_pin)] = plat_pin
212
213 else:
214 raise TypeError("Connector I/Os must be a dictionary or a string, not {!r}"
215 .format(io))
216
217 def __repr__(self):
218 return "(connector {} {} {})".format(self.name, self.number,
219 " ".join("{}=>{}".format(conn, plat)
220 for conn, plat in self.mapping.items()))
221
222 def __len__(self):
223 return len(self.mapping)
224
225 def __iter__(self):
226 for conn_pin, plat_pin in self.mapping.items():
227 yield "{}_{}:{}".format(self.name, self.number, conn_pin), plat_pin