Abstract Syntax Tree
Warning
The Torii API reference is a work in progress and we are actively working on improving it, however it may be deficient or missing in places.
- class torii.hdl.ast.Array(iterable: Sequence[Value] = ())
Addressable multiplexer.
An array is similar to a
list
that can also be indexed byValue``s; indexing by an integer or a slice works the same as for Python lists, but indexing by a ``Value
results in a proxy.The array proxy can be used as an ordinary
Value
, i.e. participate in calculations and assignments, provided that all elements of the array are values. The array proxy also supports attribute access and further indexing, each returning another array proxy; this means that the results of indexing into arrays, arrays of records, and arrays of arrays can all be used as first-class values.It is an error to change an array or any of its elements after an array proxy was created. Changing the array directly will raise an exception. However, it is not possible to detect the elements being modified; if an element’s attribute or element is modified after the proxy for it has been created, the proxy will refer to stale data.
Examples
Simple array:
gpios = Array(Signal() for _ in range(10)) with m.If(bus.we): m.d.sync += gpios[bus.addr].eq(bus.w_data) with m.Else(): m.d.sync += bus.r_data.eq(gpios[bus.addr])
Multidimensional array:
mult = Array(Array(x * y for y in range(10)) for x in range(10)) a = Signal.range(10) b = Signal.range(10) r = Signal(8) m.d.comb += r.eq(mult[a][b])
Array of records:
layout = [ ("r_data", 16), ("r_en", 1), ] buses = Array(Record(layout) for busno in range(4)) master = Record(layout) m.d.comb += [ buses[sel].r_en.eq(master.r_en), master.r_data.eq(buses[sel].r_data), ]
- insert(index: SupportsIndex, value: Value) None
S.insert(index, value) – insert value before index
- class torii.hdl.ast.Cat(*args: ValueCastT | Iterable[ValueCastT], src_loc_at: int = 0)
Concatenate values.
Form a compound
Value
from several smaller ones by concatenation. The first argument occupies the lower bits of the result. The return value can be used on either side of an assignment, that is, the concatenated value can be used as an argument on the RHS or as a target on the LHS. If it is used on the LHS, it must solely consist ofSignal
s, slices ofSignal
s, and other concatenations meeting these properties. The bit length of the return value is the sum of the bit lengths of the arguments:len(Cat(args)) == sum(len(arg) for arg in args)
- Parameters:
*args (Values or iterables of Values, inout) –
Value
s to be concatenated.- Returns:
Resulting
Value
obtained by concatenation.- Return type:
Value, inout
- class torii.hdl.ast.ClockSignal(domain: str = 'sync', *, src_loc_at: int = 0)
Clock signal for a clock domain.
Any
ClockSignal
is equivalent tocd.clk
for a clock domain with the corresponding name. All of these signals ultimately refer to the same signal, but they can be manipulated independently of the clock domain, even before the clock domain is created.- Parameters:
domain (str) – Clock domain to obtain a clock signal for. Defaults to
'sync'
.
- class torii.hdl.ast.Const(value: int, shape: Shape | int | range | type | ShapeCastable | None = None, src_loc_at: int = 0, **kwargs)
A constant, literal integer value.
- Parameters:
- Variables:
- static cast(obj: Value | int | bool | EnumMeta | ValueCastable | ValueLike) Const
Converts
obj
to an Torii constant.First,
obj
is converted to a value usingValue.cast()
. If it is a constant, it is returned. If it is a constant-castable expression, it is evaluated and returned. Otherwise, :exn:`TypeError` is raised.
- class torii.hdl.ast.Initial(*, src_loc_at: int = 0)
Start indicator, for model checking.
An
Initial
signal is1
at the first cycle of model checking, and0
at any other.
- torii.hdl.ast.Mux(sel: Value | int | bool | EnumMeta | ValueCastable | ValueLike, val1: Value | int | bool | EnumMeta | ValueCastable | ValueLike, val0: Value | int | bool | EnumMeta | ValueCastable | ValueLike) Operator
Choose between two values.
- Parameters:
sel (Value, in) – Selector.
val1 (Value, in)
val0 (Value, in) – Input values.
- Returns:
Output
Value
. Ifsel
is asserted, the Mux returnsval1
, elseval0
.- Return type:
Value, out
- class torii.hdl.ast.ResetSignal(domain: str = 'sync', allow_reset_less: bool = False, *, src_loc_at: int = 0)
Reset signal for a clock domain.
Any
ResetSignal
is equivalent tocd.rst
for a clock domain with the corresponding name. All of these signals ultimately refer to the same signal, but they can be manipulated independently of the clock domain, even before the clock domain is created.- Parameters:
- class torii.hdl.ast.Sample(expr: Value | int | bool | EnumMeta | ValueCastable | ValueLike, clocks: int, domain: str | None, *, src_loc_at: int = 0)
Value from the past.
A
Sample
of an expression is equal to the value of the expressionclocks
clock edges of thedomain
clock back. If that moment is before the beginning of time, it is equal to the value of the expression calculated as if each signal had its reset value.
- class torii.hdl.ast.Shape(width: int = 1, signed: bool = False)
Bit width and signedness of a value.
A
Shape
can be constructed using:explicit bit width and signedness;
aliases
signed()
andunsigned()
;casting from a variety of objects.
A
Shape
can be cast from:an integer, where the integer specifies the bit width;
- a range, where the result is wide enough to represent any element of the range, and is
signed if any element of the range is signed;
- an
Enum
with all integer members orIntEnum
, where the result is wide enough to represent any member of the enumeration, and is signed if any member of the enumeration is signed.
- an
- class torii.hdl.ast.ShapeCastable
Interface of user-defined objects that can be cast to :class:`Shape`s.
An object deriving from
ShapeCastable
is automatically converted to aShape
when it is used in a context where aShape
is expected. Such objects can contain a richer description of the shape than what is supported by the core Torii language, yet still be transparently used with it.
- class torii.hdl.ast.ShapeLike(*args, **kwargs)
An abstract class representing all objects that can be cast to a
Shape
.issubclass(cls, ShapeLike)
returnsTrue
for:ShapeCastable
and its subclassesint
and its subclassesrange
and its subclassesenum.EnumMeta
and its subclassesShapeLike
itself
isinstance(obj, ShapeLike)
returnsTrue
for:Shape
instancesShapeCastable
instancesnon-negative
int
valuesrange
instancesenum.Enum
subclasses where all values are value-like
This class is only usable for the above checks — no instances and no (non-virtual) subclasses can be created.
- class torii.hdl.ast.Signal(shape: ShapeCastT | None = None, *, name: str | None = None, reset: int | EnumMeta | None = None, reset_less: bool = False, attrs: dict[str, int | str | bool] | None = None, decoder: Callable[[int], str] | type[Enum] | None = None, src_loc_at: int = 0)
A varying integer value.
- Parameters:
shape (
Shape
-castable object or None) – Specification for the number of bits in thisSignal
and its signedness (whether it can represent negative values). SeeShape.cast
for details. If not specified,shape
defaults to 1-bit and non-signed.name (str) – Name hint for this signal. If
None
(default) the name is inferred from the variable name thisSignal
is assigned to.reset (int or integral Enum) – Reset (synchronous) or default (combinatorial) value. When this
Signal
is assigned to in synchronous context and the corresponding clock domain is reset, theSignal
assumes the given value. When thisSignal
is unassigned in combinatorial context (due to conditional assignments not being taken), theSignal
assumes itsreset
value. Defaults to 0.reset_less (bool) – If
True
, do not generate reset logic for thisSignal
in synchronous statements. Thereset
value is only used as a combinatorial default or as the initial value. Defaults toFalse
.attrs (dict) – Dictionary of synthesis attributes.
decoder (function or Enum) – A function converting integer signal values to human-readable strings (e.g. FSM state names). If an
Enum
subclass is passed, it is concisely decoded using format string"{0.name:}/{0.value:}"
, or a number if the signal value is not a member of the enumeration.
- Variables:
- class torii.hdl.ast.SignalDict(pairs: tuple[tuple[Key, Val], ...] = ())
Mapping of Signal objects to arbitrary value types
- class torii.hdl.ast.SignalKey(signal: Signal | ClockSignal | ResetSignal)
Allow aliasing of the same internal signal in a design from multiple object instances.
This allows you to map them as the same key in the resolution collections.
Doing so allows for multiple instances of, say, a
ClockSignal
with the same domain to refer internally to the same signal upon design flatting.Meaning that wherever there is a
ClockSignal('sync')
they all refer to the same internal signal ID.
- class torii.hdl.ast.ValueCastable
Interface of user-defined objects that can be cast to
Value
s.An object deriving from
ValueCastable`
is automatically converted to aValue
when it is used in a context where aValue`
is expected. Such objects can implement different or richer semantics than what is supported by the core Torii language, yet still be transparently used with it as long as the final underlying representation is a single ToriiValue
. These objects also need not commit to a specific representation until they are converted to a concrete Torii value.Note that it is necessary to ensure that Torii’s view of representation of all values stays internally consistent. The class deriving from
ValueCastable`
must decorate theas_value()
method with thelowermethod()
decorator, which ensures that all calls toas_value()
return the sameValue
representation. If the class deriving fromValueCastable
is mutable, it is up to the user to ensure that it is not mutated in a way that changes its representation after the first call toas_value()
.- static lowermethod(func)
Decorator to memoize lowering methods.
Ensures the decorated method is called only once, with subsequent method calls returning the object returned by the first first method call.
This decorator is required to decorate the
as_value
method ofValueCastable
subclasses. This is to ensure that Torii’s view of representation of all values stays internally consistent.