1 from abc
import ABCMeta
, abstractmethod
5 from collections
import OrderedDict
6 from collections
.abc
import Iterable
, MutableMapping
, MutableSet
, MutableSequence
14 "Value", "Const", "C", "AnyConst", "AnySeq", "Operator", "Mux", "Part", "Slice", "Cat", "Repl",
15 "Array", "ArrayProxy",
16 "Signal", "ClockSignal", "ResetSignal",
18 "Sample", "Past", "Stable", "Rose", "Fell", "Initial",
19 "Statement", "Assign", "Assert", "Assume", "Cover", "Switch", "Delay", "Tick",
20 "Passive", "ValueKey", "ValueDict", "ValueSet", "SignalKey", "SignalDict",
26 """Deterministic Unique IDentifier"""
29 self
.duid
= DUID
.__next
_uid
33 def _enum_shape(enum_type
):
34 min_value
= min(member
.value
for member
in enum_type
)
35 max_value
= max(member
.value
for member
in enum_type
)
36 if not isinstance(min_value
, int) or not isinstance(max_value
, int):
37 raise TypeError("Only enumerations with integer values can be converted to nMigen values")
38 signed
= min_value
< 0 or max_value
< 0
39 width
= max(bits_for(min_value
, signed
), bits_for(max_value
, signed
))
40 return (width
, signed
)
43 class Value(metaclass
=ABCMeta
):
46 """Converts ``obj`` to an nMigen value.
48 Booleans and integers are wrapped into a :class:`Const`. Enumerations whose members are
49 all integers are converted to a :class:`Const` with a shape that fits every member.
51 if isinstance(obj
, Value
):
53 elif isinstance(obj
, (bool, int)):
55 elif isinstance(obj
, Enum
):
56 return Const(obj
.value
, _enum_shape(type(obj
)))
58 raise TypeError("Object {!r} is not an nMigen value".format(obj
))
60 # TODO(nmigen-0.2): remove this
62 @deprecated("instead of `Value.wrap`, use `Value.cast`")
66 def __init__(self
, *, src_loc_at
=0):
68 self
.src_loc
= tracer
.get_src_loc(1 + src_loc_at
)
71 raise TypeError("Attempted to convert nMigen value to boolean")
74 return Operator("~", [self
])
76 return Operator("-", [self
])
78 def __add__(self
, other
):
79 return Operator("+", [self
, other
])
80 def __radd__(self
, other
):
81 return Operator("+", [other
, self
])
82 def __sub__(self
, other
):
83 return Operator("-", [self
, other
])
84 def __rsub__(self
, other
):
85 return Operator("-", [other
, self
])
87 def __mul__(self
, other
):
88 return Operator("*", [self
, other
])
89 def __rmul__(self
, other
):
90 return Operator("*", [other
, self
])
92 def __check_divisor(self
):
93 width
, signed
= self
.shape()
95 # Python's division semantics and Verilog's division semantics differ for negative
96 # divisors (Python uses div/mod, Verilog uses quo/rem); for now, avoid the issue
97 # completely by prohibiting such division operations.
98 raise NotImplementedError("Division by a signed value is not supported")
99 def __mod__(self
, other
):
100 other
= Value
.cast(other
)
101 other
.__check
_divisor
()
102 return Operator("%", [self
, other
])
103 def __rmod__(self
, other
):
104 self
.__check
_divisor
()
105 return Operator("%", [other
, self
])
106 def __floordiv__(self
, other
):
107 other
= Value
.cast(other
)
108 other
.__check
_divisor
()
109 return Operator("//", [self
, other
])
110 def __rfloordiv__(self
, other
):
111 self
.__check
_divisor
()
112 return Operator("//", [other
, self
])
114 def __lshift__(self
, other
):
115 return Operator("<<", [self
, other
])
116 def __rlshift__(self
, other
):
117 return Operator("<<", [other
, self
])
118 def __rshift__(self
, other
):
119 return Operator(">>", [self
, other
])
120 def __rrshift__(self
, other
):
121 return Operator(">>", [other
, self
])
122 def __and__(self
, other
):
123 return Operator("&", [self
, other
])
124 def __rand__(self
, other
):
125 return Operator("&", [other
, self
])
126 def __xor__(self
, other
):
127 return Operator("^", [self
, other
])
128 def __rxor__(self
, other
):
129 return Operator("^", [other
, self
])
130 def __or__(self
, other
):
131 return Operator("|", [self
, other
])
132 def __ror__(self
, other
):
133 return Operator("|", [other
, self
])
135 def __eq__(self
, other
):
136 return Operator("==", [self
, other
])
137 def __ne__(self
, other
):
138 return Operator("!=", [self
, other
])
139 def __lt__(self
, other
):
140 return Operator("<", [self
, other
])
141 def __le__(self
, other
):
142 return Operator("<=", [self
, other
])
143 def __gt__(self
, other
):
144 return Operator(">", [self
, other
])
145 def __ge__(self
, other
):
146 return Operator(">=", [self
, other
])
149 return self
.shape()[0]
151 def __getitem__(self
, key
):
153 if isinstance(key
, int):
154 if key
not in range(-n
, n
):
155 raise IndexError("Cannot index {} bits into {}-bit value".format(key
, n
))
158 return Slice(self
, key
, key
+ 1)
159 elif isinstance(key
, slice):
160 start
, stop
, step
= key
.indices(n
)
162 return Cat(self
[i
] for i
in range(start
, stop
, step
))
163 return Slice(self
, start
, stop
)
165 raise TypeError("Cannot index value with {}".format(repr(key
)))
168 """Conversion to boolean.
173 ``1`` if any bits are set, ``0`` otherwise.
175 return Operator("b", [self
])
178 """Check if any bits are ``1``.
183 ``1`` if any bits are set, ``0`` otherwise.
185 return Operator("r|", [self
])
188 """Check if all bits are ``1``.
193 ``1`` if all bits are set, ``0`` otherwise.
195 return Operator("r&", [self
])
198 """Compute pairwise exclusive-or of every bit.
203 ``1`` if an odd number of bits are set, ``0`` if an even number of bits are set.
205 return Operator("r^", [self
])
207 def implies(premise
, conclusion
):
213 ``0`` if ``premise`` is true and ``conclusion`` is not, ``1`` otherwise.
215 return ~premise | conclusion
217 # TODO(nmigen-0.2): move this to nmigen.compat and make it a deprecated extension
218 @deprecated("instead of `.part`, use `.bit_select`")
219 def part(self
, offset
, width
):
220 return Part(self
, offset
, width
, src_loc_at
=1)
222 def bit_select(self
, offset
, width
):
223 """Part-select with bit granularity.
225 Selects a constant width but variable offset part of a ``Value``, such that successive
226 parts overlap by all but 1 bit.
231 Index of first selected bit.
233 Number of selected bits.
238 Selected part of the ``Value``
240 return Part(self
, offset
, width
, stride
=1, src_loc_at
=1)
242 def word_select(self
, offset
, width
):
243 """Part-select with word granularity.
245 Selects a constant width but variable offset part of a ``Value``, such that successive
246 parts do not overlap.
251 Index of first selected word.
253 Number of selected bits.
258 Selected part of the ``Value``
260 return Part(self
, offset
, width
, stride
=width
, src_loc_at
=1)
262 def matches(self
, *patterns
):
265 Matches against a set of patterns, which may be integers or bit strings, recognizing
266 the same grammar as ``Case()``.
270 patterns : int or str
271 Patterns to match against.
276 ``1`` if any pattern matches the value, ``0`` otherwise.
279 for pattern
in patterns
:
280 if not isinstance(pattern
, (int, str, Enum
)):
281 raise SyntaxError("Match pattern must be an integer, a string, or an enumeration, "
284 if isinstance(pattern
, str) and any(bit
not in "01-" for bit
in pattern
):
285 raise SyntaxError("Match pattern '{}' must consist of 0, 1, and - (don't care) "
288 if isinstance(pattern
, str) and len(pattern
) != len(self
):
289 raise SyntaxError("Match pattern '{}' must have the same width as match value "
291 .format(pattern
, len(self
)))
292 if isinstance(pattern
, int) and bits_for(pattern
) > len(self
):
293 warnings
.warn("Match pattern '{:b}' is wider than match value "
294 "(which has width {}); comparison will never be true"
295 .format(pattern
, len(self
)),
296 SyntaxWarning, stacklevel
=3)
298 if isinstance(pattern
, str):
299 mask
= int(pattern
.replace("0", "1").replace("-", "0"), 2)
300 pattern
= int(pattern
.replace("-", "0"), 2)
301 matches
.append((self
& mask
) == pattern
)
302 elif isinstance(pattern
, int):
303 matches
.append(self
== pattern
)
304 elif isinstance(pattern
, Enum
):
305 matches
.append(self
== pattern
.value
)
310 elif len(matches
) == 1:
313 return Cat(*matches
).any()
321 Value to be assigned.
326 Assignment statement that can be used in combinatorial or synchronous context.
328 return Assign(self
, value
, src_loc_at
=1)
332 """Bit length and signedness of a value.
337 Number of bits required to store `v` or available in `v`, followed by
338 whether `v` has a sign bit (included in the bit count).
342 >>> Value.shape(Signal(8))
344 >>> Value.shape(C(0xaa))
349 def _lhs_signals(self
):
350 raise TypeError("Value {!r} cannot be used in assignments".format(self
))
353 def _rhs_signals(self
):
357 raise TypeError("Value {!r} cannot be evaluated as constant".format(self
))
364 """A constant, literal integer value.
369 shape : int or tuple or None
370 Either an integer ``width`` or a tuple ``(width, signed)`` specifying the number of bits
371 in this constant and whether it is signed (can represent negative values).
372 ``shape`` defaults to the minimum possible width and signedness of ``value``.
382 def normalize(value
, shape
):
383 width
, signed
= shape
384 mask
= (1 << width
) - 1
386 if signed
and value
>> (width
- 1):
390 def __init__(self
, value
, shape
=None):
391 # We deliberately do not call Value.__init__ here.
392 self
.value
= int(value
)
394 shape
= bits_for(self
.value
), self
.value
< 0
395 if isinstance(shape
, int):
396 shape
= shape
, self
.value
< 0
397 self
.width
, self
.signed
= shape
398 if not isinstance(self
.width
, int) or self
.width
< 0:
399 raise TypeError("Width must be a non-negative integer, not '{!r}'"
401 self
.value
= self
.normalize(self
.value
, shape
)
403 # TODO(nmigen-0.2): move this to nmigen.compat and make it a deprecated extension
405 @deprecated("instead of `const.nbits`, use `const.width`")
410 return self
.width
, self
.signed
412 def _rhs_signals(self
):
419 return "(const {}'{}d{})".format(self
.width
, "s" if self
.signed
else "", self
.value
)
422 C
= Const
# shorthand
425 class AnyValue(Value
, DUID
):
426 def __init__(self
, shape
, *, src_loc_at
=0):
427 super().__init
__(src_loc_at
=src_loc_at
)
428 if isinstance(shape
, int):
430 self
.width
, self
.signed
= shape
431 if not isinstance(self
.width
, int) or self
.width
< 0:
432 raise TypeError("Width must be a non-negative integer, not '{!r}'"
436 return self
.width
, self
.signed
438 def _rhs_signals(self
):
443 class AnyConst(AnyValue
):
445 return "(anyconst {}'{})".format(self
.nbits
, "s" if self
.signed
else "")
449 class AnySeq(AnyValue
):
451 return "(anyseq {}'{})".format(self
.nbits
, "s" if self
.signed
else "")
455 class Operator(Value
):
456 def __init__(self
, operator
, operands
, *, src_loc_at
=0):
457 super().__init
__(src_loc_at
=1 + src_loc_at
)
458 self
.operator
= operator
459 self
.operands
= [Value
.cast(op
) for op
in operands
]
461 # TODO(nmigen-0.2): move this to nmigen.compat and make it a deprecated extension
463 @deprecated("instead of `.op`, use `.operator`")
468 def _bitwise_binary_shape(a_shape
, b_shape
):
469 a_bits
, a_sign
= a_shape
470 b_bits
, b_sign
= b_shape
471 if not a_sign
and not b_sign
:
472 # both operands unsigned
473 return max(a_bits
, b_bits
), False
474 elif a_sign
and b_sign
:
475 # both operands signed
476 return max(a_bits
, b_bits
), True
477 elif not a_sign
and b_sign
:
478 # first operand unsigned (add sign bit), second operand signed
479 return max(a_bits
+ 1, b_bits
), True
481 # first signed, second operand unsigned (add sign bit)
482 return max(a_bits
, b_bits
+ 1), True
484 op_shapes
= list(map(lambda x
: x
.shape(), self
.operands
))
485 if len(op_shapes
) == 1:
486 (a_width
, a_signed
), = op_shapes
487 if self
.operator
in ("+", "~"):
488 return a_width
, a_signed
489 if self
.operator
== "-":
491 return a_width
+ 1, True
493 return a_width
, a_signed
494 if self
.operator
in ("b", "r|", "r&", "r^"):
496 elif len(op_shapes
) == 2:
497 (a_width
, a_signed
), (b_width
, b_signed
) = op_shapes
498 if self
.operator
== "+" or self
.operator
== "-":
499 width
, signed
= _bitwise_binary_shape(*op_shapes
)
500 return width
+ 1, signed
501 if self
.operator
== "*":
502 return a_width
+ b_width
, a_signed
or b_signed
503 if self
.operator
in ("//", "%"):
505 return a_width
, a_signed
506 if self
.operator
in ("<", "<=", "==", "!=", ">", ">="):
508 if self
.operator
in ("&", "^", "|"):
509 return _bitwise_binary_shape(*op_shapes
)
510 if self
.operator
== "<<":
512 extra
= 2 ** (b_width
- 1) - 1
514 extra
= 2 ** (b_width
) - 1
515 return a_width
+ extra
, a_signed
516 if self
.operator
== ">>":
518 extra
= 2 ** (b_width
- 1)
521 return a_width
+ extra
, a_signed
522 elif len(op_shapes
) == 3:
523 if self
.operator
== "m":
524 s_shape
, a_shape
, b_shape
= op_shapes
525 return _bitwise_binary_shape(a_shape
, b_shape
)
526 raise NotImplementedError("Operator {}/{} not implemented"
527 .format(self
.operator
, len(op_shapes
))) # :nocov:
529 def _rhs_signals(self
):
530 return union(op
._rhs
_signals
() for op
in self
.operands
)
533 return "({} {})".format(self
.operator
, " ".join(map(repr, self
.operands
)))
536 def Mux(sel
, val1
, val0
):
537 """Choose between two values.
550 Output ``Value``. If ``sel`` is asserted, the Mux returns ``val1``, else ``val0``.
552 sel
= Value
.cast(sel
)
555 return Operator("m", [sel
, val1
, val0
])
560 def __init__(self
, value
, start
, end
, *, src_loc_at
=0):
561 if not isinstance(start
, int):
562 raise TypeError("Slice start must be an integer, not '{!r}'".format(start
))
563 if not isinstance(end
, int):
564 raise TypeError("Slice end must be an integer, not '{!r}'".format(end
))
567 if start
not in range(-(n
+1), n
+1):
568 raise IndexError("Cannot start slice {} bits into {}-bit value".format(start
, n
))
571 if end
not in range(-(n
+1), n
+1):
572 raise IndexError("Cannot end slice {} bits into {}-bit value".format(end
, n
))
576 raise IndexError("Slice start {} must be less than slice end {}".format(start
, end
))
578 super().__init
__(src_loc_at
=src_loc_at
)
579 self
.value
= Value
.cast(value
)
584 return self
.end
- self
.start
, False
586 def _lhs_signals(self
):
587 return self
.value
._lhs
_signals
()
589 def _rhs_signals(self
):
590 return self
.value
._rhs
_signals
()
593 return "(slice {} {}:{})".format(repr(self
.value
), self
.start
, self
.end
)
598 def __init__(self
, value
, offset
, width
, stride
=1, *, src_loc_at
=0):
599 if not isinstance(width
, int) or width
< 0:
600 raise TypeError("Part width must be a non-negative integer, not '{!r}'".format(width
))
601 if not isinstance(stride
, int) or stride
<= 0:
602 raise TypeError("Part stride must be a positive integer, not '{!r}'".format(stride
))
604 super().__init
__(src_loc_at
=src_loc_at
)
606 self
.offset
= Value
.cast(offset
)
611 return self
.width
, False
613 def _lhs_signals(self
):
614 return self
.value
._lhs
_signals
()
616 def _rhs_signals(self
):
617 return self
.value
._rhs
_signals
() | self
.offset
._rhs
_signals
()
620 return "(part {} {} {} {})".format(repr(self
.value
), repr(self
.offset
),
621 self
.width
, self
.stride
)
626 """Concatenate values.
628 Form a compound ``Value`` from several smaller ones by concatenation.
629 The first argument occupies the lower bits of the result.
630 The return value can be used on either side of an assignment, that
631 is, the concatenated value can be used as an argument on the RHS or
632 as a target on the LHS. If it is used on the LHS, it must solely
633 consist of ``Signal`` s, slices of ``Signal`` s, and other concatenations
634 meeting these properties. The bit length of the return value is the sum of
635 the bit lengths of the arguments::
637 len(Cat(args)) == sum(len(arg) for arg in args)
641 *args : Values or iterables of Values, inout
642 ``Value`` s to be concatenated.
647 Resulting ``Value`` obtained by concatentation.
649 def __init__(self
, *args
, src_loc_at
=0):
650 super().__init
__(src_loc_at
=src_loc_at
)
651 self
.parts
= [Value
.cast(v
) for v
in flatten(args
)]
654 return sum(len(part
) for part
in self
.parts
), False
656 def _lhs_signals(self
):
657 return union((part
._lhs
_signals
() for part
in self
.parts
), start
=ValueSet())
659 def _rhs_signals(self
):
660 return union((part
._rhs
_signals
() for part
in self
.parts
), start
=ValueSet())
664 for part
in reversed(self
.parts
):
666 value |
= part
._as
_const
()
670 return "(cat {})".format(" ".join(map(repr, self
.parts
)))
677 An input value is replicated (repeated) several times
678 to be used on the RHS of assignments::
680 len(Repl(s, n)) == len(s) * n
685 Input value to be replicated.
687 Number of replications.
694 def __init__(self
, value
, count
, *, src_loc_at
=0):
695 if not isinstance(count
, int) or count
< 0:
696 raise TypeError("Replication count must be a non-negative integer, not '{!r}'"
699 super().__init
__(src_loc_at
=src_loc_at
)
700 self
.value
= Value
.cast(value
)
704 return len(self
.value
) * self
.count
, False
706 def _rhs_signals(self
):
707 return self
.value
._rhs
_signals
()
710 return "(repl {!r} {})".format(self
.value
, self
.count
)
714 class Signal(Value
, DUID
):
715 """A varying integer value.
719 shape : int or tuple or None
720 Either an integer ``width`` or a tuple ``(width, signed)`` specifying the number of bits
721 in this ``Signal`` and whether it is signed (can represent negative values).
722 ``shape`` defaults to 1-bit and non-signed.
724 Name hint for this signal. If ``None`` (default) the name is inferred from the variable
725 name this ``Signal`` is assigned to. Name collisions are automatically resolved by
726 prepending names of objects that contain this ``Signal`` and by appending integer
729 Reset (synchronous) or default (combinatorial) value.
730 When this ``Signal`` is assigned to in synchronous context and the corresponding clock
731 domain is reset, the ``Signal`` assumes the given value. When this ``Signal`` is unassigned
732 in combinatorial context (due to conditional assignments not being taken), the ``Signal``
733 assumes its ``reset`` value. Defaults to 0.
735 If ``True``, do not generate reset logic for this ``Signal`` in synchronous statements.
736 The ``reset`` value is only used as a combinatorial default or as the initial value.
737 Defaults to ``False``.
740 If ``shape`` is ``None``, the signal bit width and signedness are
741 determined by the integer range given by ``min`` (inclusive,
742 defaults to 0) and ``max`` (exclusive, defaults to 2).
744 Dictionary of synthesis attributes.
745 decoder : function or Enum
746 A function converting integer signal values to human-readable strings (e.g. FSM state
747 names). If an ``Enum`` subclass is passed, it is concisely decoded using format string
748 ``"{0.name:}/{0.value:}"``, or a number if the signal value is not a member of
761 def __init__(self
, shape
=None, *, name
=None, reset
=0, reset_less
=False, min=None, max=None,
762 attrs
=None, decoder
=None, src_loc_at
=0):
763 super().__init
__(src_loc_at
=src_loc_at
)
765 # TODO(nmigen-0.2): move this to nmigen.compat and make it a deprecated extension
766 if min is not None or max is not None:
767 warnings
.warn("instead of `Signal(min={min}, max={max})`, "
768 "use `Signal.range({min}, {max})`"
769 .format(min=min or 0, max=max or 2),
770 DeprecationWarning, stacklevel
=2 + src_loc_at
)
772 if name
is not None and not isinstance(name
, str):
773 raise TypeError("Name must be a string, not '{!r}'".format(name
))
774 self
.name
= name
or tracer
.get_var_name(depth
=2 + src_loc_at
, default
="$signal")
781 max -= 1 # make both bounds inclusive
783 raise ValueError("Lower bound {} should be less or equal to higher bound {}"
784 .format(min, max + 1))
785 self
.signed
= min < 0 or max < 0
789 self
.width
= builtins
.max(bits_for(min, self
.signed
),
790 bits_for(max, self
.signed
))
793 if not (min is None and max is None):
794 raise ValueError("Only one of bits/signedness or bounds may be specified")
795 if isinstance(shape
, int):
796 self
.width
, self
.signed
= shape
, False
798 self
.width
, self
.signed
= shape
800 if not isinstance(self
.width
, int) or self
.width
< 0:
801 raise TypeError("Width must be a non-negative integer, not '{!r}'".format(self
.width
))
803 reset_width
= bits_for(reset
, self
.signed
)
804 if reset
!= 0 and reset_width
> self
.width
:
805 warnings
.warn("Reset value {!r} requires {} bits to represent, but the signal "
807 .format(reset
, reset_width
, self
.width
),
808 SyntaxWarning, stacklevel
=2 + src_loc_at
)
810 self
.reset
= int(reset
)
811 self
.reset_less
= bool(reset_less
)
813 self
.attrs
= OrderedDict(() if attrs
is None else attrs
)
814 if isinstance(decoder
, type) and issubclass(decoder
, Enum
):
815 def enum_decoder(value
):
817 return "{0.name:}/{0.value:}".format(decoder(value
))
820 self
.decoder
= enum_decoder
822 self
.decoder
= decoder
825 def range(cls
, *args
, src_loc_at
=0, **kwargs
):
826 """Create Signal that can represent a given range.
828 The parameters to ``Signal.range`` are the same as for the built-in ``range`` function.
829 That is, for any given ``range(*args)``, ``Signal.range(*args)`` can represent any
830 ``x for x in range(*args)``.
832 value_range
= range(*args
)
833 if len(value_range
) > 0:
834 signed
= value_range
.start
< 0 or (value_range
.stop
- value_range
.step
) < 0
836 signed
= value_range
.start
< 0
837 width
= max(bits_for(value_range
.start
, signed
),
838 bits_for(value_range
.stop
- value_range
.step
, signed
))
839 return cls((width
, signed
), src_loc_at
=1 + src_loc_at
, **kwargs
)
842 def enum(cls
, enum_type
, *, src_loc_at
=0, **kwargs
):
843 """Create Signal that can represent a given enumeration.
847 enum : type (inheriting from :class:`enum.Enum`)
848 Enumeration to base this Signal on.
850 if not issubclass(enum_type
, Enum
):
851 raise TypeError("Type {!r} is not an enumeration")
852 return cls(_enum_shape(enum_type
), src_loc_at
=1 + src_loc_at
, decoder
=enum_type
, **kwargs
)
855 def like(cls
, other
, *, name
=None, name_suffix
=None, src_loc_at
=0, **kwargs
):
856 """Create Signal based on another.
861 Object to base this Signal on.
865 elif name_suffix
is not None:
866 new_name
= other
.name
+ str(name_suffix
)
868 new_name
= tracer
.get_var_name(depth
=2 + src_loc_at
, default
="$like")
869 kw
= dict(shape
=cls
.cast(other
).shape(), name
=new_name
)
870 if isinstance(other
, cls
):
871 kw
.update(reset
=other
.reset
, reset_less
=other
.reset_less
,
872 attrs
=other
.attrs
, decoder
=other
.decoder
)
874 return cls(**kw
, src_loc_at
=1 + src_loc_at
)
876 # TODO(nmigen-0.2): move this to nmigen.compat and make it a deprecated extension
878 @deprecated("instead of `signal.nbits`, use `signal.width`")
883 @deprecated("instead of `signal.nbits = x`, use `signal.width = x`")
884 def nbits(self
, value
):
888 return self
.width
, self
.signed
890 def _lhs_signals(self
):
891 return ValueSet((self
,))
893 def _rhs_signals(self
):
894 return ValueSet((self
,))
897 return "(sig {})".format(self
.name
)
901 class ClockSignal(Value
):
902 """Clock signal for a clock domain.
904 Any ``ClockSignal`` is equivalent to ``cd.clk`` for a clock domain with the corresponding name.
905 All of these signals ultimately refer to the same signal, but they can be manipulated
906 independently of the clock domain, even before the clock domain is created.
911 Clock domain to obtain a clock signal for. Defaults to ``"sync"``.
913 def __init__(self
, domain
="sync", *, src_loc_at
=0):
914 super().__init
__(src_loc_at
=src_loc_at
)
915 if not isinstance(domain
, str):
916 raise TypeError("Clock domain name must be a string, not '{!r}'".format(domain
))
918 raise ValueError("Domain '{}' does not have a clock".format(domain
))
924 def _lhs_signals(self
):
925 return ValueSet((self
,))
927 def _rhs_signals(self
):
928 raise NotImplementedError("ClockSignal must be lowered to a concrete signal") # :nocov:
931 return "(clk {})".format(self
.domain
)
935 class ResetSignal(Value
):
936 """Reset signal for a clock domain.
938 Any ``ResetSignal`` is equivalent to ``cd.rst`` for a clock domain with the corresponding name.
939 All of these signals ultimately refer to the same signal, but they can be manipulated
940 independently of the clock domain, even before the clock domain is created.
945 Clock domain to obtain a reset signal for. Defaults to ``"sync"``.
946 allow_reset_less : bool
947 If the clock domain is reset-less, act as a constant ``0`` instead of reporting an error.
949 def __init__(self
, domain
="sync", allow_reset_less
=False, *, src_loc_at
=0):
950 super().__init
__(src_loc_at
=src_loc_at
)
951 if not isinstance(domain
, str):
952 raise TypeError("Clock domain name must be a string, not '{!r}'".format(domain
))
954 raise ValueError("Domain '{}' does not have a reset".format(domain
))
956 self
.allow_reset_less
= allow_reset_less
961 def _lhs_signals(self
):
962 return ValueSet((self
,))
964 def _rhs_signals(self
):
965 raise NotImplementedError("ResetSignal must be lowered to a concrete signal") # :nocov:
968 return "(rst {})".format(self
.domain
)
971 class Array(MutableSequence
):
972 """Addressable multiplexer.
974 An array is similar to a ``list`` that can also be indexed by ``Value``s; indexing by an integer or a slice works the same as for Python lists, but indexing by a ``Value`` results
977 The array proxy can be used as an ordinary ``Value``, i.e. participate in calculations and
978 assignments, provided that all elements of the array are values. The array proxy also supports
979 attribute access and further indexing, each returning another array proxy; this means that
980 the results of indexing into arrays, arrays of records, and arrays of arrays can all
981 be used as first-class values.
983 It is an error to change an array or any of its elements after an array proxy was created.
984 Changing the array directly will raise an exception. However, it is not possible to detect
985 the elements being modified; if an element's attribute or element is modified after the proxy
986 for it has been created, the proxy will refer to stale data.
993 gpios = Array(Signal() for _ in range(10))
995 m.d.sync += gpios[bus.addr].eq(bus.w_data)
997 m.d.sync += bus.r_data.eq(gpios[bus.addr])
999 Multidimensional array::
1001 mult = Array(Array(x * y for y in range(10)) for x in range(10))
1002 a = Signal.range(10)
1003 b = Signal.range(10)
1005 m.d.comb += r.eq(mult[a][b])
1013 buses = Array(Record(layout) for busno in range(4))
1014 master = Record(layout)
1016 buses[sel].r_en.eq(master.r_en),
1017 master.r_data.eq(buses[sel].r_data),
1020 def __init__(self
, iterable
=()):
1021 self
._inner
= list(iterable
)
1022 self
._proxy
_at
= None
1023 self
._mutable
= True
1025 def __getitem__(self
, index
):
1026 if isinstance(index
, Value
):
1028 self
._proxy
_at
= tracer
.get_src_loc()
1029 self
._mutable
= False
1030 return ArrayProxy(self
, index
)
1032 return self
._inner
[index
]
1035 return len(self
._inner
)
1037 def _check_mutability(self
):
1038 if not self
._mutable
:
1039 raise ValueError("Array can no longer be mutated after it was indexed with a value "
1040 "at {}:{}".format(*self
._proxy
_at
))
1042 def __setitem__(self
, index
, value
):
1043 self
._check
_mutability
()
1044 self
._inner
[index
] = value
1046 def __delitem__(self
, index
):
1047 self
._check
_mutability
()
1048 del self
._inner
[index
]
1050 def insert(self
, index
, value
):
1051 self
._check
_mutability
()
1052 self
._inner
.insert(index
, value
)
1055 return "(array{} [{}])".format(" mutable" if self
._mutable
else "",
1056 ", ".join(map(repr, self
._inner
)))
1060 class ArrayProxy(Value
):
1061 def __init__(self
, elems
, index
, *, src_loc_at
=0):
1062 super().__init
__(src_loc_at
=1 + src_loc_at
)
1064 self
.index
= Value
.cast(index
)
1066 def __getattr__(self
, attr
):
1067 return ArrayProxy([getattr(elem
, attr
) for elem
in self
.elems
], self
.index
)
1069 def __getitem__(self
, index
):
1070 return ArrayProxy([ elem
[index
] for elem
in self
.elems
], self
.index
)
1072 def _iter_as_values(self
):
1073 return (Value
.cast(elem
) for elem
in self
.elems
)
1076 width
, signed
= 0, False
1077 for elem_width
, elem_signed
in (elem
.shape() for elem
in self
._iter
_as
_values
()):
1078 width
= max(width
, elem_width
+ elem_signed
)
1079 signed
= max(signed
, elem_signed
)
1080 return width
, signed
1082 def _lhs_signals(self
):
1083 signals
= union((elem
._lhs
_signals
() for elem
in self
._iter
_as
_values
()), start
=ValueSet())
1086 def _rhs_signals(self
):
1087 signals
= union((elem
._rhs
_signals
() for elem
in self
._iter
_as
_values
()), start
=ValueSet())
1088 return self
.index
._rhs
_signals
() | signals
1091 return "(proxy (array [{}]) {!r})".format(", ".join(map(repr, self
.elems
)), self
.index
)
1094 class UserValue(Value
):
1095 """Value with custom lowering.
1097 A ``UserValue`` is a value whose precise representation does not have to be immediately known,
1098 which is useful in certain metaprogramming scenarios. Instead of providing fixed semantics
1099 upfront, it is kept abstract for as long as possible, only being lowered to a concrete nMigen
1100 value when required.
1102 Note that the ``lower`` method will only be called once; this is necessary to ensure that
1103 nMigen's view of representation of all values stays internally consistent. If the class
1104 deriving from ``UserValue`` is mutable, then it must ensure that after ``lower`` is called,
1105 it is not mutated in a way that changes its representation.
1107 The following is an incomplete list of actions that, when applied to an ``UserValue`` directly
1108 or indirectly, will cause it to be lowered, provided as an illustrative reference:
1109 * Querying the shape using ``.shape()`` or ``len()``;
1110 * Creating a similarly shaped signal using ``Signal.like``;
1111 * Indexing or iterating through individual bits;
1112 * Adding an assignment to the value to a ``Module`` using ``m.d.<domain> +=``.
1114 def __init__(self
, *, src_loc_at
=0):
1115 super().__init
__(src_loc_at
=1 + src_loc_at
)
1116 self
.__lowered
= None
1120 """Conversion to a concrete representation."""
1123 def _lazy_lower(self
):
1124 if self
.__lowered
is None:
1125 self
.__lowered
= Value
.cast(self
.lower())
1126 return self
.__lowered
1129 return self
._lazy
_lower
().shape()
1131 def _lhs_signals(self
):
1132 return self
._lazy
_lower
()._lhs
_signals
()
1134 def _rhs_signals(self
):
1135 return self
._lazy
_lower
()._rhs
_signals
()
1139 class Sample(Value
):
1140 """Value from the past.
1142 A ``Sample`` of an expression is equal to the value of the expression ``clocks`` clock edges
1143 of the ``domain`` clock back. If that moment is before the beginning of time, it is equal
1144 to the value of the expression calculated as if each signal had its reset value.
1146 def __init__(self
, expr
, clocks
, domain
, *, src_loc_at
=0):
1147 super().__init
__(src_loc_at
=1 + src_loc_at
)
1148 self
.value
= Value
.cast(expr
)
1149 self
.clocks
= int(clocks
)
1150 self
.domain
= domain
1151 if not isinstance(self
.value
, (Const
, Signal
, ClockSignal
, ResetSignal
, Initial
)):
1152 raise TypeError("Sampled value must be a signal or a constant, not {!r}"
1153 .format(self
.value
))
1155 raise ValueError("Cannot sample a value {} cycles in the future"
1156 .format(-self
.clocks
))
1157 if not (self
.domain
is None or isinstance(self
.domain
, str)):
1158 raise TypeError("Domain name must be a string or None, not {!r}"
1159 .format(self
.domain
))
1162 return self
.value
.shape()
1164 def _rhs_signals(self
):
1165 return ValueSet((self
,))
1168 return "(sample {!r} @ {}[{}])".format(
1169 self
.value
, "<default>" if self
.domain
is None else self
.domain
, self
.clocks
)
1172 def Past(expr
, clocks
=1, domain
=None):
1173 return Sample(expr
, clocks
, domain
)
1176 def Stable(expr
, clocks
=0, domain
=None):
1177 return Sample(expr
, clocks
+ 1, domain
) == Sample(expr
, clocks
, domain
)
1180 def Rose(expr
, clocks
=0, domain
=None):
1181 return ~
Sample(expr
, clocks
+ 1, domain
) & Sample(expr
, clocks
, domain
)
1184 def Fell(expr
, clocks
=0, domain
=None):
1185 return Sample(expr
, clocks
+ 1, domain
) & ~
Sample(expr
, clocks
, domain
)
1189 class Initial(Value
):
1190 """Start indicator, for model checking.
1192 An ``Initial`` signal is ``1`` at the first cycle of model checking, and ``0`` at any other.
1194 def __init__(self
, *, src_loc_at
=0):
1195 super().__init
__(src_loc_at
=1 + src_loc_at
)
1200 def _rhs_signals(self
):
1201 return ValueSet((self
,))
1207 class _StatementList(list):
1209 return "({})".format(" ".join(map(repr, self
)))
1213 def __init__(self
, *, src_loc_at
=0):
1214 self
.src_loc
= tracer
.get_src_loc(1 + src_loc_at
)
1218 if isinstance(obj
, Iterable
):
1219 return _StatementList(sum((Statement
.wrap(e
) for e
in obj
), []))
1221 if isinstance(obj
, Statement
):
1222 return _StatementList([obj
])
1224 raise TypeError("Object '{!r}' is not an nMigen statement".format(obj
))
1228 class Assign(Statement
):
1229 def __init__(self
, lhs
, rhs
, *, src_loc_at
=0):
1230 super().__init
__(src_loc_at
=src_loc_at
)
1231 self
.lhs
= Value
.cast(lhs
)
1232 self
.rhs
= Value
.cast(rhs
)
1234 def _lhs_signals(self
):
1235 return self
.lhs
._lhs
_signals
()
1237 def _rhs_signals(self
):
1238 return self
.lhs
._rhs
_signals
() | self
.rhs
._rhs
_signals
()
1241 return "(eq {!r} {!r})".format(self
.lhs
, self
.rhs
)
1244 class Property(Statement
):
1245 def __init__(self
, test
, *, _check
=None, _en
=None, src_loc_at
=0):
1246 super().__init
__(src_loc_at
=src_loc_at
)
1247 self
.test
= Value
.cast(test
)
1248 self
._check
= _check
1250 if self
._check
is None:
1251 self
._check
= Signal(reset_less
=True, name
="${}$check".format(self
._kind
))
1252 self
._check
.src_loc
= self
.src_loc
1254 self
._en
= Signal(reset_less
=True, name
="${}$en".format(self
._kind
))
1255 self
._en
.src_loc
= self
.src_loc
1257 def _lhs_signals(self
):
1258 return ValueSet((self
._en
, self
._check
))
1260 def _rhs_signals(self
):
1261 return self
.test
._rhs
_signals
()
1264 return "({} {!r})".format(self
._kind
, self
.test
)
1268 class Assert(Property
):
1273 class Assume(Property
):
1278 class Cover(Property
):
1283 class Switch(Statement
):
1284 def __init__(self
, test
, cases
, *, src_loc
=None, src_loc_at
=0, case_src_locs
={}):
1286 super().__init
__(src_loc_at
=src_loc_at
)
1288 # Switch is a bit special in terms of location tracking because it is usually created
1289 # long after the control has left the statement that directly caused its creation.
1290 self
.src_loc
= src_loc
1291 # Switch is also a bit special in that its parts also have location information. It can't
1292 # be automatically traced, so whatever constructs a Switch may optionally provide it.
1293 self
.case_src_locs
= {}
1295 self
.test
= Value
.cast(test
)
1296 self
.cases
= OrderedDict()
1297 for orig_keys
, stmts
in cases
.items():
1298 # Map: None -> (); key -> (key,); (key...) -> (key...)
1302 if not isinstance(keys
, tuple):
1304 # Map: 2 -> "0010"; "0010" -> "0010"
1307 if isinstance(key
, str):
1309 elif isinstance(key
, int):
1310 key
= format(key
, "b").rjust(len(self
.test
), "0")
1311 elif isinstance(key
, Enum
):
1312 key
= format(key
.value
, "b").rjust(len(self
.test
), "0")
1314 raise TypeError("Object '{!r}' cannot be used as a switch key"
1316 assert len(key
) == len(self
.test
)
1317 new_keys
= (*new_keys
, key
)
1318 if not isinstance(stmts
, Iterable
):
1320 self
.cases
[new_keys
] = Statement
.wrap(stmts
)
1321 if orig_keys
in case_src_locs
:
1322 self
.case_src_locs
[new_keys
] = case_src_locs
[orig_keys
]
1324 def _lhs_signals(self
):
1325 signals
= union((s
._lhs
_signals
() for ss
in self
.cases
.values() for s
in ss
),
1329 def _rhs_signals(self
):
1330 signals
= union((s
._rhs
_signals
() for ss
in self
.cases
.values() for s
in ss
),
1332 return self
.test
._rhs
_signals
() | signals
1335 def case_repr(keys
, stmts
):
1336 stmts_repr
= " ".join(map(repr, stmts
))
1338 return "(default {})".format(stmts_repr
)
1339 elif len(keys
) == 1:
1340 return "(case {} {})".format(keys
[0], stmts_repr
)
1342 return "(case ({}) {})".format(" ".join(keys
), stmts_repr
)
1343 case_reprs
= [case_repr(keys
, stmts
) for keys
, stmts
in self
.cases
.items()]
1344 return "(switch {!r} {})".format(self
.test
, " ".join(case_reprs
))
1348 class Delay(Statement
):
1349 def __init__(self
, interval
=None, *, src_loc_at
=0):
1350 super().__init
__(src_loc_at
=src_loc_at
)
1351 self
.interval
= None if interval
is None else float(interval
)
1353 def _rhs_signals(self
):
1357 if self
.interval
is None:
1360 return "(delay {:.3}us)".format(self
.interval
* 1e6
)
1364 class Tick(Statement
):
1365 def __init__(self
, domain
="sync", *, src_loc_at
=0):
1366 super().__init
__(src_loc_at
=src_loc_at
)
1367 self
.domain
= str(domain
)
1369 def _rhs_signals(self
):
1373 return "(tick {})".format(self
.domain
)
1377 class Passive(Statement
):
1378 def __init__(self
, *, src_loc_at
=0):
1379 super().__init
__(src_loc_at
=src_loc_at
)
1381 def _rhs_signals(self
):
1388 class _MappedKeyCollection(metaclass
=ABCMeta
):
1390 def _map_key(self
, key
):
1394 def _unmap_key(self
, key
):
1398 class _MappedKeyDict(MutableMapping
, _MappedKeyCollection
):
1399 def __init__(self
, pairs
=()):
1400 self
._storage
= OrderedDict()
1401 for key
, value
in pairs
:
1404 def __getitem__(self
, key
):
1405 key
= None if key
is None else self
._map
_key
(key
)
1406 return self
._storage
[key
]
1408 def __setitem__(self
, key
, value
):
1409 key
= None if key
is None else self
._map
_key
(key
)
1410 self
._storage
[key
] = value
1412 def __delitem__(self
, key
):
1413 key
= None if key
is None else self
._map
_key
(key
)
1414 del self
._storage
[key
]
1417 for key
in self
._storage
:
1421 yield self
._unmap
_key
(key
)
1423 def __eq__(self
, other
):
1424 if not isinstance(other
, type(self
)):
1426 if len(self
) != len(other
):
1428 for ak
, bk
in zip(sorted(self
._storage
), sorted(other
._storage
)):
1431 if self
._storage
[ak
] != other
._storage
[bk
]:
1436 return len(self
._storage
)
1439 pairs
= ["({!r}, {!r})".format(k
, v
) for k
, v
in self
.items()]
1440 return "{}.{}([{}])".format(type(self
).__module
__, type(self
).__name
__,
1444 class _MappedKeySet(MutableSet
, _MappedKeyCollection
):
1445 def __init__(self
, elements
=()):
1446 self
._storage
= OrderedDict()
1447 for elem
in elements
:
1450 def add(self
, value
):
1451 self
._storage
[self
._map
_key
(value
)] = None
1453 def update(self
, values
):
1454 for value
in values
:
1457 def discard(self
, value
):
1459 del self
._storage
[self
._map
_key
(value
)]
1461 def __contains__(self
, value
):
1462 return self
._map
_key
(value
) in self
._storage
1465 for key
in [k
for k
in self
._storage
]:
1466 yield self
._unmap
_key
(key
)
1469 return len(self
._storage
)
1472 return "{}.{}({})".format(type(self
).__module
__, type(self
).__name
__,
1473 ", ".join(repr(x
) for x
in self
))
1477 def __init__(self
, value
):
1478 self
.value
= Value
.cast(value
)
1479 if isinstance(self
.value
, Const
):
1480 self
._hash
= hash(self
.value
.value
)
1481 elif isinstance(self
.value
, (Signal
, AnyValue
)):
1482 self
._hash
= hash(self
.value
.duid
)
1483 elif isinstance(self
.value
, (ClockSignal
, ResetSignal
)):
1484 self
._hash
= hash(self
.value
.domain
)
1485 elif isinstance(self
.value
, Operator
):
1486 self
._hash
= hash((self
.value
.operator
,
1487 tuple(ValueKey(o
) for o
in self
.value
.operands
)))
1488 elif isinstance(self
.value
, Slice
):
1489 self
._hash
= hash((ValueKey(self
.value
.value
), self
.value
.start
, self
.value
.end
))
1490 elif isinstance(self
.value
, Part
):
1491 self
._hash
= hash((ValueKey(self
.value
.value
), ValueKey(self
.value
.offset
),
1492 self
.value
.width
, self
.value
.stride
))
1493 elif isinstance(self
.value
, Cat
):
1494 self
._hash
= hash(tuple(ValueKey(o
) for o
in self
.value
.parts
))
1495 elif isinstance(self
.value
, ArrayProxy
):
1496 self
._hash
= hash((ValueKey(self
.value
.index
),
1497 tuple(ValueKey(e
) for e
in self
.value
._iter
_as
_values
())))
1498 elif isinstance(self
.value
, Sample
):
1499 self
._hash
= hash((ValueKey(self
.value
.value
), self
.value
.clocks
, self
.value
.domain
))
1500 elif isinstance(self
.value
, Initial
):
1503 raise TypeError("Object '{!r}' cannot be used as a key in value collections"
1504 .format(self
.value
))
1509 def __eq__(self
, other
):
1510 if type(other
) is not ValueKey
:
1512 if type(self
.value
) is not type(other
.value
):
1515 if isinstance(self
.value
, Const
):
1516 return self
.value
.value
== other
.value
.value
1517 elif isinstance(self
.value
, (Signal
, AnyValue
)):
1518 return self
.value
is other
.value
1519 elif isinstance(self
.value
, (ClockSignal
, ResetSignal
)):
1520 return self
.value
.domain
== other
.value
.domain
1521 elif isinstance(self
.value
, Operator
):
1522 return (self
.value
.operator
== other
.value
.operator
and
1523 len(self
.value
.operands
) == len(other
.value
.operands
) and
1524 all(ValueKey(a
) == ValueKey(b
)
1525 for a
, b
in zip(self
.value
.operands
, other
.value
.operands
)))
1526 elif isinstance(self
.value
, Slice
):
1527 return (ValueKey(self
.value
.value
) == ValueKey(other
.value
.value
) and
1528 self
.value
.start
== other
.value
.start
and
1529 self
.value
.end
== other
.value
.end
)
1530 elif isinstance(self
.value
, Part
):
1531 return (ValueKey(self
.value
.value
) == ValueKey(other
.value
.value
) and
1532 ValueKey(self
.value
.offset
) == ValueKey(other
.value
.offset
) and
1533 self
.value
.width
== other
.value
.width
and
1534 self
.value
.stride
== other
.value
.stride
)
1535 elif isinstance(self
.value
, Cat
):
1536 return all(ValueKey(a
) == ValueKey(b
)
1537 for a
, b
in zip(self
.value
.parts
, other
.value
.parts
))
1538 elif isinstance(self
.value
, ArrayProxy
):
1539 return (ValueKey(self
.value
.index
) == ValueKey(other
.value
.index
) and
1540 len(self
.value
.elems
) == len(other
.value
.elems
) and
1541 all(ValueKey(a
) == ValueKey(b
)
1542 for a
, b
in zip(self
.value
._iter
_as
_values
(),
1543 other
.value
._iter
_as
_values
())))
1544 elif isinstance(self
.value
, Sample
):
1545 return (ValueKey(self
.value
.value
) == ValueKey(other
.value
.value
) and
1546 self
.value
.clocks
== other
.value
.clocks
and
1547 self
.value
.domain
== self
.value
.domain
)
1548 elif isinstance(self
.value
, Initial
):
1551 raise TypeError("Object '{!r}' cannot be used as a key in value collections"
1552 .format(self
.value
))
1554 def __lt__(self
, other
):
1555 if not isinstance(other
, ValueKey
):
1557 if type(self
.value
) != type(other
.value
):
1560 if isinstance(self
.value
, Const
):
1561 return self
.value
< other
.value
1562 elif isinstance(self
.value
, (Signal
, AnyValue
)):
1563 return self
.value
.duid
< other
.value
.duid
1564 elif isinstance(self
.value
, Slice
):
1565 return (ValueKey(self
.value
.value
) < ValueKey(other
.value
.value
) and
1566 self
.value
.start
< other
.value
.start
and
1567 self
.value
.end
< other
.value
.end
)
1569 raise TypeError("Object '{!r}' cannot be used as a key in value collections")
1572 return "<{}.ValueKey {!r}>".format(__name__
, self
.value
)
1575 class ValueDict(_MappedKeyDict
):
1577 _unmap_key
= lambda self
, key
: key
.value
1580 class ValueSet(_MappedKeySet
):
1582 _unmap_key
= lambda self
, key
: key
.value
1586 def __init__(self
, signal
):
1587 self
.signal
= signal
1588 if type(signal
) is Signal
:
1589 self
._intern
= (0, signal
.duid
)
1590 elif type(signal
) is ClockSignal
:
1591 self
._intern
= (1, signal
.domain
)
1592 elif type(signal
) is ResetSignal
:
1593 self
._intern
= (2, signal
.domain
)
1595 raise TypeError("Object '{!r}' is not an nMigen signal".format(signal
))
1598 return hash(self
._intern
)
1600 def __eq__(self
, other
):
1601 if type(other
) is not SignalKey
:
1603 return self
._intern
== other
._intern
1605 def __lt__(self
, other
):
1606 if type(other
) is not SignalKey
:
1607 raise TypeError("Object '{!r}' cannot be compared to a SignalKey".format(signal
))
1608 return self
._intern
< other
._intern
1611 return "<{}.SignalKey {!r}>".format(__name__
, self
.signal
)
1614 class SignalDict(_MappedKeyDict
):
1615 _map_key
= SignalKey
1616 _unmap_key
= lambda self
, key
: key
.signal
1619 class SignalSet(_MappedKeySet
):
1620 _map_key
= SignalKey
1621 _unmap_key
= lambda self
, key
: key
.signal