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=())

Addressable multiplexer.

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 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, value)

S.insert(index, value) – insert value before index

class torii.hdl.ast.Cat(*args: Value | int | Enum | ValueCastable, 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 of Signal s, slices of Signal 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

shape() Shape

Bit width and signedness of a value.

Returns:

See Shape.

Return type:

Shape

Examples

>>> Signal(8).shape()
Shape(width = 8, signed = False)
>>> Const(0xaa).shape()
Shape(width = 8, signed = False)
class torii.hdl.ast.ClockSignal(domain='sync', *, src_loc_at=0)

Clock signal for a clock domain.

Any ClockSignal is equivalent to cd.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'.

shape()

Bit width and signedness of a value.

Returns:

See Shape.

Return type:

Shape

Examples

>>> Signal(8).shape()
Shape(width = 8, signed = False)
>>> Const(0xaa).shape()
Shape(width = 8, signed = False)
class torii.hdl.ast.Const(value, shape=None, src_loc_at: int = 0, **kwargs)

A constant, literal integer value.

Parameters:
  • value (int)

  • shape (int or tuple or None) – Either an integer width or a tuple (width, signed) specifying the number of bits in this constant and whether it is signed (can represent negative values). shape defaults to the minimum possible width and signedness of value.

Variables:
static cast(obj)

Converts obj to an Torii constant.

First, obj is converted to a value using Value.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.

shape() Shape

Bit width and signedness of a value.

Returns:

See Shape.

Return type:

Shape

Examples

>>> Signal(8).shape()
Shape(width = 8, signed = False)
>>> Const(0xaa).shape()
Shape(width = 8, signed = False)
class torii.hdl.ast.Initial(*, src_loc_at=0)

Start indicator, for model checking.

An Initial signal is 1 at the first cycle of model checking, and 0 at any other.

shape()

Bit width and signedness of a value.

Returns:

See Shape.

Return type:

Shape

Examples

>>> Signal(8).shape()
Shape(width = 8, signed = False)
>>> Const(0xaa).shape()
Shape(width = 8, signed = False)
torii.hdl.ast.Mux(sel: Value, val1: Value, val0: Value) Operator

Choose between two values.

Parameters:
  • sel (Value, in) – Selector.

  • val1 (Value, in)

  • val0 (Value, in) – Input values.

Returns:

Output Value. If sel is asserted, the Mux returns val1, else val0.

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 to cd.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:
  • domain (str) – Clock domain to obtain a reset signal for. Defaults to 'sync'.

  • allow_reset_less (bool) – If the clock domain is reset-less, act as a constant 0 instead of reporting an error.

shape() Shape

Bit width and signedness of a value.

Returns:

See Shape.

Return type:

Shape

Examples

>>> Signal(8).shape()
Shape(width = 8, signed = False)
>>> Const(0xaa).shape()
Shape(width = 8, signed = False)
class torii.hdl.ast.Sample(expr, clocks, domain, *, src_loc_at=0)

Value from the past.

A Sample of an expression is equal to the value of the expression clocks clock edges of the domain 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.

shape()

Bit width and signedness of a value.

Returns:

See Shape.

Return type:

Shape

Examples

>>> Signal(8).shape()
Shape(width = 8, signed = False)
>>> Const(0xaa).shape()
Shape(width = 8, signed = False)
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() and unsigned();

  • 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 or 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.

Parameters:
  • width (int) – The number of bits in the representation, including the sign bit (if any).

  • signed (bool) – If False, the value is unsigned. If True, the value is signed two’s complement.

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 a Shape when it is used in a context where a Shape 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) returns True for:

  • Shape

  • ShapeCastable and its subclasses

  • int and its subclasses

  • range and its subclasses

  • enum.EnumMeta and its subclasses

  • ShapeLike itself

isinstance(obj, ShapeLike) returns True for:

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=None, *, name=None, reset=None, reset_less=False, attrs=None, decoder=None, src_loc_at=0)

A varying integer value.

Parameters:
  • shape (Shape-castable object or None) – Specification for the number of bits in this Signal and its signedness (whether it can represent negative values). See Shape.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 this Signal 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, the Signal assumes the given value. When this Signal is unassigned in combinatorial context (due to conditional assignments not being taken), the Signal assumes its reset value. Defaults to 0.

  • reset_less (bool) – If True, do not generate reset logic for this Signal in synchronous statements. The reset value is only used as a combinatorial default or as the initial value. Defaults to False.

  • 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:
static like(other, *, name=None, name_suffix=None, src_loc_at=0, **kwargs)

Create Signal based on another.

Parameters:

other (Value) – Object to base this Signal on.

shape()

Bit width and signedness of a value.

Returns:

See Shape.

Return type:

Shape

Examples

>>> Signal(8).shape()
Shape(width = 8, signed = False)
>>> Const(0xaa).shape()
Shape(width = 8, signed = False)
class torii.hdl.ast.SignalDict(pairs=())
class torii.hdl.ast.SignalSet(elements=())
torii.hdl.ast.signed(width: int) Shape

Shorthand for Shape(width, signed = True).

torii.hdl.ast.unsigned(width: int) Shape

Shorthand for Shape(width, signed = False).

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 a Value when it is used in a context where a Value` 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 Torii Value. 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 the as_value() method with the lowermethod() decorator, which ensures that all calls to as_value() return the same Value representation. If the class deriving from ValueCastable 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 to as_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 of ValueCastable subclasses. This is to ensure that Torii’s view of representation of all values stays internally consistent.

class torii.hdl.ast.ValueDict(pairs=())
class torii.hdl.ast.ValueSet(elements=())