vendor.lattice_{ecp5,machxo_2_3l}: remove -forceAll from Diamond scripts.
[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 return Pins(*args, invert=True, **kwargs)
59
60
61 class DiffPairs:
62 def __init__(self, p, n, *, dir="io", invert=False, conn=None, assert_width=None):
63 self.p = Pins(p, dir=dir, conn=conn, assert_width=assert_width)
64 self.n = Pins(n, dir=dir, conn=conn, assert_width=assert_width)
65
66 if len(self.p.names) != len(self.n.names):
67 raise TypeError("Positive and negative pins must have the same width, but {!r} "
68 "and {!r} do not"
69 .format(self.p, self.n))
70
71 self.dir = dir
72 self.invert = bool(invert)
73
74 def __len__(self):
75 return len(self.p.names)
76
77 def __iter__(self):
78 return zip(self.p.names, self.n.names)
79
80 def __repr__(self):
81 return "(diffpairs{} {} (p {}) (n {}))".format("-n" if self.invert else "",
82 self.dir, " ".join(self.p.names), " ".join(self.n.names))
83
84
85 def DiffPairsN(*args, **kwargs):
86 return DiffPairs(*args, invert=True, **kwargs)
87
88
89 class Attrs(OrderedDict):
90 def __init__(self, **attrs):
91 for key, value in attrs.items():
92 if not (value is None or isinstance(value, (str, int)) or hasattr(value, "__call__")):
93 raise TypeError("Value of attribute {} must be None, int, str, or callable, "
94 "not {!r}"
95 .format(key, value))
96
97 super().__init__(**attrs)
98
99 def __repr__(self):
100 items = []
101 for key, value in self.items():
102 if value is None:
103 items.append("!" + key)
104 else:
105 items.append(key + "=" + repr(value))
106 return "(attrs {})".format(" ".join(items))
107
108
109 class Clock:
110 def __init__(self, frequency):
111 if not isinstance(frequency, (float, int)):
112 raise TypeError("Clock frequency must be a number")
113
114 self.frequency = float(frequency)
115
116 @property
117 def period(self):
118 return 1 / self.frequency
119
120 def __repr__(self):
121 return "(clock {})".format(self.frequency)
122
123
124 class Subsignal:
125 def __init__(self, name, *args):
126 self.name = name
127 self.ios = []
128 self.attrs = Attrs()
129 self.clock = None
130
131 if not args:
132 raise ValueError("Missing I/O constraints")
133 for arg in args:
134 if isinstance(arg, (Pins, DiffPairs)):
135 if not self.ios:
136 self.ios.append(arg)
137 else:
138 raise TypeError("Pins and DiffPairs are incompatible with other location or "
139 "subsignal constraints, but {!r} appears after {!r}"
140 .format(arg, self.ios[-1]))
141 elif isinstance(arg, Subsignal):
142 if not self.ios or isinstance(self.ios[-1], Subsignal):
143 self.ios.append(arg)
144 else:
145 raise TypeError("Subsignal is incompatible with location constraints, but "
146 "{!r} appears after {!r}"
147 .format(arg, self.ios[-1]))
148 elif isinstance(arg, Attrs):
149 self.attrs.update(arg)
150 elif isinstance(arg, Clock):
151 if self.ios and isinstance(self.ios[-1], (Pins, DiffPairs)):
152 if self.clock is None:
153 self.clock = arg
154 else:
155 raise ValueError("Clock constraint can be applied only once")
156 else:
157 raise TypeError("Clock constraint can only be applied to Pins or DiffPairs, "
158 "not {!r}"
159 .format(self.ios[-1]))
160 else:
161 raise TypeError("Constraint must be one of Pins, DiffPairs, Subsignal, Attrs, "
162 "or Clock, not {!r}"
163 .format(arg))
164
165 def _content_repr(self):
166 parts = []
167 for io in self.ios:
168 parts.append(repr(io))
169 if self.clock is not None:
170 parts.append(repr(self.clock))
171 if self.attrs:
172 parts.append(repr(self.attrs))
173 return " ".join(parts)
174
175 def __repr__(self):
176 return "(subsignal {} {})".format(self.name, self._content_repr())
177
178
179 class Resource(Subsignal):
180 @classmethod
181 def family(cls, name_or_number, number=None, *, ios, default_name, name_suffix=""):
182 # This constructor accepts two different forms:
183 # 1. Number-only form:
184 # Resource.family(0, default_name="name", ios=[Pins("A0 A1")])
185 # 2. Name-and-number (name override) form:
186 # Resource.family("override", 0, default_name="name", ios=...)
187 # This makes it easier to build abstractions for resources, e.g. an SPIResource abstraction
188 # could simply delegate to `Resource.family(*args, default_name="spi", ios=ios)`.
189 # The name_suffix argument is meant to support creating resources with
190 # similar names, such as spi_flash, spi_flash_2x, etc.
191 if name_suffix: # Only add "_" if we actually have a suffix.
192 name_suffix = "_" + name_suffix
193
194 if number is None: # name_or_number is number
195 return cls(default_name + name_suffix, name_or_number, *ios)
196 else: # name_or_number is name
197 return cls(name_or_number + name_suffix, number, *ios)
198
199 def __init__(self, name, number, *args):
200 super().__init__(name, *args)
201
202 self.number = number
203
204 def __repr__(self):
205 return "(resource {} {} {})".format(self.name, self.number, self._content_repr())
206
207
208 class Connector:
209 def __init__(self, name, number, io, *, conn=None):
210 self.name = name
211 self.number = number
212 mapping = OrderedDict()
213
214 if isinstance(io, dict):
215 for conn_pin, plat_pin in io.items():
216 if not isinstance(conn_pin, str):
217 raise TypeError("Connector pin name must be a string, not {!r}"
218 .format(conn_pin))
219 if not isinstance(plat_pin, str):
220 raise TypeError("Platform pin name must be a string, not {!r}"
221 .format(plat_pin))
222 mapping[conn_pin] = plat_pin
223
224 elif isinstance(io, str):
225 for conn_pin, plat_pin in enumerate(io.split(), start=1):
226 if plat_pin == "-":
227 continue
228
229 mapping[str(conn_pin)] = plat_pin
230 else:
231 raise TypeError("Connector I/Os must be a dictionary or a string, not {!r}"
232 .format(io))
233
234 if conn is not None:
235 conn_name, conn_number = conn
236 if not (isinstance(conn_name, str) and isinstance(conn_number, (int, str))):
237 raise TypeError("Connector must be None or a pair of string (connector name) and "
238 "integer/string (connector number), not {!r}"
239 .format(conn))
240
241 for conn_pin, plat_pin in mapping.items():
242 mapping[conn_pin] = "{}_{}:{}".format(conn_name, conn_number, plat_pin)
243
244 self.mapping = mapping
245
246 def __repr__(self):
247 return "(connector {} {} {})".format(self.name, self.number,
248 " ".join("{}=>{}".format(conn, plat)
249 for conn, plat in self.mapping.items()))
250
251 def __len__(self):
252 return len(self.mapping)
253
254 def __iter__(self):
255 for conn_pin, plat_pin in self.mapping.items():
256 yield "{}_{}:{}".format(self.name, self.number, conn_pin), plat_pin