Language reference
Warning
This reference is a work in progress and is seriously incomplete!
While the wording below states that anything not described in this document isn’t covered by the backwards compatibility guarantee, this should be ignored until the document is complete and this warning is removed.
This reference describes the Python classes that underlie the Amaranth language’s syntax. It assumes familiarity with the language guide.
Backwards compatibility
As part of the Amaranth backwards compatibility guarantee, any behaviors described in this document will not change from a version to another without at least one version including a warning about the impending change. Any nontrivial change to these behaviors must also go through the public review as a part of the Amaranth Request for Comments process.
Conversely, any behavior not documented here is subject to change at any time with or without notice, and any names under the amaranth.hdl module that are not explicitly included in this document, even if they do not begin with an underscore, are internal to the implementation of the language.
Importing syntax
There are two ways to import the Amaranth syntax into a Python file: by importing the prelude or by importing individual names from the amaranth.hdl module. Since the prelude is kept small and rarely extended to avoid breaking downstream code that uses a glob import, there are some names that are only exported from the amaranth.hdl module. The following three snippets are equivalent:
from amaranth import *
m = Module()
import amaranth as am
m = am.Module()
from amaranth.hdl import Module
m = Module()
The prelude exports exactly the following names:
ConstC()Mux()Cat()ArraySignalClockSignalResetSignalFormatPrintAssert()ModuleClockDomainElaboratableFragmentInstanceMemoryDomainRenamerResetInserterEnableInserter
Source locations
Many functions and methods in Amaranth take the src_loc_at=0 keyword argument. These language constructs may inspect the call stack to determine the file and line of its call site, which will be used to annotate generated code when a netlist is generated or to improve diagnostic messages.
Some call sites are not relevant for an Amaranth designer; e.g. when an Amaranth language construct is called from a user-defined utility function, the source location of the call site within this utility function is usually not interesting to the designer. In these cases, one or more levels of function calls can be removed from consideration using the src_loc_at argument as follows (using Shape.cast() to demonstrate the concept):
def my_shape_cast(obj, *, src_loc_at=0):
... # additionally process `obj`...
return Shape.cast(obj, src_loc_at=1 + src_loc_at)
The number 1 corresponds to the number of call stack frames that should be skipped.
Shapes
See also the introduction to shapes and casting from shape-like objects in the language guide.
- class amaranth.hdl.Shape(width=1, signed=False)
Bit width and signedness of a
Value.A
Shapecan be obtained by:constructing with explicit bit width and signedness;
using the
signed()andunsigned()aliases if the signedness is known upfront;casting from a variety of objects using the
cast()method.
- Parameters:
width (int) – The number of bits in the representation of a value. This includes the sign bit for signed values. Cannot be zero if the value is signed.
signed (bool) – Whether the value is signed. Signed values use the two’s complement representation.
- static cast(obj, *, src_loc_at=0)
Cast
objto a shape.Many shape-like objects can be cast to a shape:
a
Shape, where the result is itself;an
int, where the result isunsigned(obj);a
range, where the result has minimal width required to represent all elements of the range, and is signed if any element of the range is signed;an
enum.Enumwhose members are all constant-castable orenum.IntEnum, where the result is wide enough to represent any member of the enumeration, and is signed if any member of the enumeration is signed;a
ShapeCastableobject, where the result is obtained by repeatedly callingobj.as_shape().
- Raises:
RecursionError – If
objis aShapeCastableobject that casts to itself.
- __repr__()
Python code that creates this shape.
Returns
f"signed({self.width})"orf"unsigned({self.width})".
- amaranth.hdl.unsigned(width)
Returns
Shape(width, signed=False).
- amaranth.hdl.signed(width)
Returns
Shape(width, signed=True).
- class amaranth.hdl.ShapeCastable
Interface class for objects that can be cast to a
Shape.Shapes of values in the Amaranth language are specified using shape-like objects. Inheriting a class from
ShapeCastableand implementing all of the methods described below adds instances of that class to the list of shape-like objects recognized by theShape.cast()method. This is a part of the mechanism for seamlessly extending the Amaranth language in third-party code.To illustrate their purpose, consider constructing a signal from a shape-castable object
shape_castable:value_like = Signal(shape_castable, init=initializer)
The code above is equivalent to:
value_like = shape_castable(Signal( shape_castable.as_shape(), init=shape_castable.const(initializer) ))
Note that the
shape_castable(x)syntax performsshape_castable.__call__(x).Tip
The source code of the
amaranth.lib.datamodule can be used as a reference for implementing a fully featured shape-castable object.- as_shape()
Convert
selfto a shape-like object.This method is called by the Amaranth language to convert
selfto a concreteShape. It will usually return aShapeobject, but it may also return another shape-like object to delegate its functionality.This method must be idempotent: when called twice on the same object, the result must be exactly the same.
This method may also be called by code that is not a part of the Amaranth language.
- Return type:
Any other object recognized by
Shape.cast().- Raises:
Exception – When the conversion cannot be done. This exception must be propagated by callers (except when checking whether an object is shape-castable or not), either directly or as a cause of another exception.
- const(obj)
Convert a constant initializer
objto its value representation.This method is called by the Amaranth language to convert
obj, which may be an arbitrary Python object, to a concrete value-like object. The objectobjwill usually be a Python literal that can conveniently represent a constant value whose shape is described byself. While not constrained here, the result will usually be an instance of the return type of__call__().For any
obj, the following condition must hold:Shape.cast(self) == Const.cast(self.const(obj)).shape()
This method may also be called by code that is not a part of the Amaranth language.
- Return type:
A value-like object that is constant-castable.
- Raises:
Exception – When the conversion cannot be done. This exception must be propagated by callers, either directly or as a cause of another exception. While not constrained here, usually the exception class will be
TypeErrororValueError.
- from_bits(raw)
Lift a bit pattern to a higher-level representation.
This method is called by the Amaranth language to lift
raw, which is anint, to a higher-level representation, which may be any object accepted byconst(). Most importantly, the simulator calls this method when the value of a shape-castable object is retrieved.For any valid bit pattern
raw, the following condition must hold:Const.cast(self.const(self.from_bits(raw))).value == raw
While
const()will usually return an Amaranth value or a custom value-castable object that is convenient to use while constructing the design, this method will usually return a Python object that is convenient to use while simulating the design. While not constrained here, these objects should have the same type whenever feasible.This method may also be called by code that is not a part of the Amaranth language.
- Return type:
unspecified type
- Raises:
Exception – When the bit pattern isn’t valid. This exception must be propagated by callers, either directly or as a cause of another exception. While not constrained here, usually the exception class will be
ValueError.
- __call__(obj)
Lift a value-like object to a higher-level representation.
This method is called by the Amaranth language to lift
obj, which may be any value-like object whose shape equalsShape.cast(self), to a higher-level representation, which may be any value-like object with the same shape. While not constrained here, usually aShapeCastableimplementation will be paired with aValueCastableimplementation, and this method will return an instance of the latter.If
objis not as described above, this interface does not constrain the behavior of this method. This may be used to implement another call-based protocol at the same time.For any compliant
obj, the following condition must hold:Value.cast(self(obj)) == Value.cast(obj)
This method may also be called by code that is not a part of the Amaranth language.
- Return type:
- format(obj, spec)
Format a value.
This method is called by the Amaranth language to implement formatting for custom shapes. Whenever
"{obj:spec}"is encountered byFormat, andobjhas a custom shape that has aformat()method,obj.shape().format(obj, "spec")is called, and the format specifier is replaced with the result.The default
format()implementation is:def format(self, obj, spec): return Format(f"{{:{spec}}}", Value.cast(obj))
- Return type:
Format
- class amaranth.hdl.ShapeLike
Abstract class representing all objects that can be cast to a
Shape.issubclass(cls, ShapeLike)returnsTruefor:ShapeCastableand its subclasses;intand its subclasses;rangeand its subclasses;enum.EnumMetaand its subclasses;ShapeLikeitself.
isinstance(obj, ShapeLike)returnsTruefor:Shapeinstances;ShapeCastableinstances;non-negative
intvalues;rangeinstances;enum.Enumsubclasses where all values are value-like objects.
This class cannot be instantiated or subclassed. It can only be used for checking types of objects.
Values
See also the introduction to values and casting from value-like objects in the language guide.
- class amaranth.hdl.Value(*, src_loc_at=0)
Abstract representation of a bit pattern computed in a circuit.
The Amaranth language gives Python code the ability to create a circuit netlist by manipulating objects representing the computations within that circuit. The
Valueclass represents the bit pattern of a constant, or of a circuit input or output, or within a storage element; or the result of an arithmetic, logical, or bit container operation.Operations on this class interpret this bit pattern either as an integer, which can be signed or unsigned depending on the value’s
shape(), or as a bit container. In either case, the semantics of operations that implement Python’s syntax, like+(also known as__add__()), are identical to the corresponding operation on a Pythonint(or on a Python sequence container). The bitwise inversion~(also known as__invert__()) is the sole exception to this rule.Data that is not conveniently representable by a single integer or a bit container can be represented by wrapping a
Valuein aValueCastablesubclass that provides domain-specific operations. It is possible to extend Amaranth in third-party code using value-castable objects, and the Amaranth standard library provides several built-in ones:amaranth.lib.enumclasses are a drop-in replacement for the standard Pythonenumclasses that can be defined with an Amaranth shape;amaranth.lib.dataclasses allow defining complex data structures such as structures and unions.
Operations on
Valueinstances return anotherValueinstance. Unless the exact type and value of the result is explicitly specified below, it should be considered opaque, and may change without notice between Amaranth releases as long as the semantics remains the same.Note
In each of the descriptions below, you will see a line similar to:
Return type:
Value,unsigned(1), assignableThe first part (
Value) indicates that the returned object’s type is a subclass ofValue. The second part (unsigned(1)) describes the shape of that value. The third part, if present, indicates that the value is assignable ifselfis assignable.- static cast(obj)
Cast
objto an Amaranth value.Many value-like objects can be cast to a value:
a
Valueinstance, where the result is itself;an
enum.IntEnuminstance, or aenum.Enuminstance whose members are all integers, where the result is aConst(obj, enum_shape)whereenum_shapeis a shape that can represent every member of the enumeration;a
ValueCastableinstance, where the result is obtained by repeatedly callingobj.as_value().
- Raises:
RecursionError – If
objis aValueCastableobject that casts to itself.
- abstract shape()
Shape of
self.- Return type:
- as_unsigned()
Reinterpretation as an unsigned value.
- Return type:
Value,unsigned(len(self)), assignable
- as_signed()
Reinterpretation as a signed value.
- Return type:
Value,signed(len(self)), assignable- Raises:
ValueError – If
len(self) == 0.
- __bool__()
Forbidden conversion to boolean.
Python uses this operator for its built-in semantics, e.g.
if, and requires it to return abool. Since this is not possible for Amaranth values, this operator always raises an exception.- Raises:
TypeError – Always.
- bool()
Conversion to boolean.
Returns the same value as
any(), but should be used whereselfis semantically a number.- Return type:
Value,unsigned(1)
- __add__(other)
Addition,
self + other.- Returns:
Value,unsigned(max(self.width(), other.width()) + 1)– If bothselfandotherare unsigned.Value,signed(max(self.width() + 1, other.width()) + 1)– Ifselfis unsigned andotheris signed.Value,signed(max(self.width(), other.width() + 1) + 1)– Ifselfis signed andotheris unsigned.Value,signed(max(self.width(), other.width()) + 1)– If bothselfandotherare unsigned.
- __sub__(other)
Subtraction,
self - other.- Returns:
Value,signed(max(self.width(), other.width()) + 1)– If bothselfandotherare unsigned.Value,signed(max(self.width() + 1, other.width()) + 1)– Ifselfis unsigned andotheris signed.Value,signed(max(self.width(), other.width() + 1) + 1)– Ifselfis signed andotheris unsigned.Value,signed(max(self.width(), other.width()) + 1)– If bothselfandotherare unsigned.
- Return type:
- __mul__(other)
Multiplication,
self * other.
- __floordiv__(other)
Flooring division,
self // other.If
otheris zero, the result of this operation is zero.
- __rfloordiv__(other)
Flooring division,
other // self(reflected).If
selfis zero, the result of this operation is zero.Like
__floordiv__(), with operands swapped.
- __mod__(other)
Flooring modulo or remainder,
self % other.If
otheris zero, the result of this operation is zero.- Return type:
Value,other.shape()
- __rmod__(other)
Flooring modulo or remainder,
other % self(reflected).Like
__mod__(), with operands swapped.
- __invert__()
Bitwise NOT,
~self.The shape of the result is the same as the shape of
self, even for unsigned values.Warning
In Python,
~0equals-1. In Amaranth,~C(0)equalsC(1). This is the only case where an Amaranth operator deviates from the Python operator with the same name.This deviation is necessary because Python does not allow overriding the logical
and,or, andnotoperators. Amaranth uses&,|, and~instead; if it wasn’t the case that~C(0) == C(1), that would have been impossible.- Return type:
Value,self.shape()
- __and__(other)
Bitwise AND,
self & other.- Returns:
Value,unsigned(max(self.width(), other.width()))– If bothselfandotherare unsigned.Value,signed(max(self.width() + 1, other.width()))– Ifselfis unsigned andotheris signed.Value,signed(max(self.width(), other.width() + 1))– Ifselfis signed andotheris unsigned.Value,signed(max(self.width(), other.width()))– If bothselfandotherare unsigned.
- __or__(other)
Bitwise OR,
self | other.- Returns:
Value,unsigned(max(self.width(), other.width()))– If bothselfandotherare unsigned.Value,signed(max(self.width() + 1, other.width()))– Ifselfis unsigned andotheris signed.Value,signed(max(self.width(), other.width() + 1))– Ifselfis signed andotheris unsigned.Value,signed(max(self.width(), other.width()))– If bothselfandotherare unsigned.
- any()
Reduction OR; is any bit
1?Performs the same operation as
bool(), but should be used whereselfis semantically a bit sequence.- Return type:
Value,unsigned(1)
- __xor__(other)
Bitwise XOR,
self ^ other.- Returns:
Value,unsigned(max(self.width(), other.width()))– If bothselfandotherare unsigned.Value,signed(max(self.width() + 1, other.width()))– Ifselfis unsigned andotheris signed.Value,signed(max(self.width(), other.width() + 1))– Ifselfis signed andotheris unsigned.Value,signed(max(self.width(), other.width()))– If bothselfandotherare unsigned.
- __lshift__(other)
Left shift by variable amount,
self << other.
- __rlshift__(other)
Left shift by variable amount,
other << self.Like
__lshift__(), with operands swapped.
- shift_left(amount)
Left shift by constant amount.
If
amount < 0, performs the same operation asself.shift_right(-amount).
- rotate_left(amount)
Left rotate by constant amount.
If
amount < 0, performs the same operation asself.rotate_right(-amount).- Return type:
Value,unsigned(len(self)), assignable
- __rshift__(other)
Right shift by variable amount,
self >> other.
- __rrshift__(other)
Right shift by variable amount,
other >> self.Like
__rshift__(), with operands swapped.
- shift_right(amount)
Right shift by constant amount.
If
amount < 0, performs the same operation asself.shift_left(-amount).
- rotate_right(amount)
Right rotate by constant amount.
If
amount < 0, performs the same operation asself.rotate_left(-amount).- Return type:
Value,unsigned(len(self)), assignable
- __getitem__(key)
Bit slicing.
Selects a constant-width, constant-offset part of
self. All three slicing syntaxes (self[i],self[i:j], andself[i:j:k]) as well as negative indices are supported. Like with other Python containers, out-of-bounds indices are trimmed to the bounds ofself.To select a variable-offset part of
self, usebit_select()orword_select()instead.- Returns:
Value,unsigned(1), assignable – Ifkeyis anint.Value,unsigned(j - i), assignable – Ifkeyis a slicei:jwhereiandjareints.Value,unsigned(len(range(*slice(i, j, k).indices(len(self))))), assignable – Ifkeyis a slicei:j:kwherei,j, andkareints.
- __contains__(other)
Forbidden membership test operator.
Python requires this operator to return a
bool. Since this is not possible for Amaranth values, this operator always raises an exception.To check membership in a set of constant integer values, use
matches()instead.- Raises:
TypeError – Always.
- bit_select(offset, width)
Part-select with bit granularity.
Selects a constant width, variable offset part of
self, where parts with successive offsets overlap bywidth - 1bits. Bits above the most significant bit ofselfmay be selected; they are equal to zero ifselfis unsigned, toself[-1]ifselfis signed, and assigning to them does nothing.When
offsetis a constant integer andoffset + width <= len(self), this operation is equivalent toself[offset:offset + width].- Parameters:
offset (value-like) – Index of the first selected bit.
width (
int) – Amount of bits to select.
- Return type:
Value,unsigned(width), assignable- Raises:
- word_select(offset, width)
Part-select with word granularity.
Selects a constant width, variable offset part of
self, where parts with successive offsets are adjacent but do not overlap. Bits above the most significant bit ofselfmay be selected; they are equal to zero ifselfis unsigned, toself[-1]ifselfis signed, and assigning to them does nothing.When
offsetis a constant integer andwidth:(offset + 1) * width <= len(self), this operation is equivalent toself[offset * width:(offset + 1) * width].- Parameters:
offset (value-like) – Index of the first selected word.
width (
int) – Amount of bits to select.
- Return type:
Value,unsigned(width), assignable- Raises:
- replicate(count)
Replication.
Equivalent to
Cat(self for _ in range(count)), but not assignable.
- matches(*patterns)
Pattern matching.
Matches against a set of patterns, recognizing the same grammar as
with m.Case(). The pattern syntax is described in the language guide.Each of the
patternsmay be astror a constant-castable object.- Return type:
Value,unsigned(1)- Raises:
SyntaxError – If a pattern has invalid syntax.
- eq(value, *, src_loc_at=0)
-
Once it is placed in a domain, an assignment changes the bit pattern of
selfto equalvalue. If the bit width ofvalueis less than that ofself, it is zero-extended (for unsignedvalues) or sign-extended (for signedvalues). If the bit width ofvalueis greater than that ofself, it is truncated.- Return type:
Statement
- __hash__ = None
Forbidden hashing.
Python objects are hashable if they provide a
__hash__method that returns anintand an__eq__method that returns abool. Amaranth values define__eq__()to return aValue, which precludes them from being hashable.To use a
Valueas a key in adict, use the following pattern:value = Signal() assoc = {} assoc[id(value)] = value, "a signal" _, info = assoc[id(value)] assert info == "a signal"
- __format__(format_desc)
Forbidden formatting.
Since normal Python formatting (f-strings and
str.format) must immediately return a string, it is unsuitable for formatting Amaranth values. To format a value at simulation time, useFormatinstead. If you really want to dump the AST at elaboration time, usereprinstead (for instance, viaf"{value!r}").
- class amaranth.hdl.ValueCastable
Interface class for objects that can be cast to a
Value.Computations in the Amaranth language are described by combining value-like objects. Inheriting a class from
ValueCastableand implementing all of the methods described below adds instances of that class to the list of value-like objects recognized by theValue.cast()method. This is a part of the mechanism for seamlessly extending the Amaranth language in third-party code.Note
All methods and operators defined by the
Valueclass will implicitly cast aValueCastableobject to aValue, with the exception of arithmetic operators, which will prefer calling a reflected arithmetic operation on theValueCastableargument if it defines one.For example, if
value_castableimplements__radd__, thenC(1) + value_castablewill performvalue_castable.__radd__(C(1)), and otherwise it will performC(1).__add__(value_castable.as_value()).- as_value()
Convert
selfto a value-like object.This method is called by the Amaranth language to convert
selfto a concreteValue. It will usually return aValueobject, but it may also return another value-like object to delegate its functionality.This method must be idempotent: when called twice on the same object, the result must be exactly the same.
This method may also be called by code that is not a part of the Amaranth language.
- Return type:
Any other object recognized by
Value.cast().- Raises:
Exception – When the conversion cannot be done. This exception must be propagated by callers, either directly or as a cause of another exception. It is recommended that, in cases where this method raises an exception, the
shape()method also raises an exception.
- shape()
Compute the shape of
self.This method is not called by the Amaranth language itself; whenever it needs to discover the shape of a value-castable object, it calls
self.as_value().shape(). However, that method must return aShape, andValueCastablesubclasses may have a richer representation of their shape provided by an instance of aShapeCastablesubclass. This method may return such a representation.This method must be idempotent: when called twice on the same object, the result must be exactly the same.
The following condition must hold:
Shape.cast(self.shape()) == Value.cast(self).shape()
- Return type:
A shape-like object.
- Raises:
Exception – When the conversion cannot be done. This exception must be propagated by callers, either directly or as a cause of another exception. It is recommended that, in cases where this method raises an exception, the
as_value()method also raises an exception.
- class amaranth.hdl.ValueLike
Abstract class representing all objects that can be cast to a
Value.issubclass(cls, ValueLike)returnsTruefor:ValueCastableand its subclasses;enum.Enumsubclasses where all values are value-like;ValueLikeitself.
isinstance(obj, ValueLike)returns the same value asissubclass(type(obj), ValueLike).This class cannot be instantiated or subclassed. It can only be used for checking types of objects.
Note
It is possible to define an enumeration with a member that is value-like but not constant-castable, meaning that
issubclass(BadEnum, ValueLike)returnsTrue, butValue.cast(BadEnum.MEMBER)raises an exception.The
amaranth.lib.enummodule prevents such enumerations from being defined when the shape is specified explicitly. Usingamaranth.lib.enumand specifying the shape ensures that all of your enumeration members are constant-castable and fit in the provided shape.