System design

Interfaces

Define clear component contracts and connect reusable hardware.

An interface defines the part of a component that other components can rely on. It can describe callable operations, signals exchanged between endpoints, or both. A consumer can then depend on that contract while the implementation changes behind it. Composition supplies the concrete components and connects them into a working design.

A shared type establishes compatible operations and fields, but the contract also needs behavioural rules: when data is available, when a transfer occurs, and what happens while an endpoint waits. This page develops two examples: a scheduled byte source and a ready/valid byte stream. You can download the complete InterfacesDemo project, including its construction code and six runnable tests.

Define a component contract

Begin with the operations a caller actually needs. A byte reader needs to know whether a source has data and whether a read succeeded. It need not know whether that source is a buffer, a fixed value, or a test fixture:

livt
interface IByteSource
{
    fn HasData() bool
    fn TryRead(value: out byte) bool
}

In this contract, HasData() reports availability without consuming a byte. TryRead returns true and supplies a byte when it succeeds. When it returns false, it sets the output to zero; callers use the boolean to distinguish failure from a valid zero byte. The signature defines the result types and direction, while these additional rules define their meaning.

The functions have no empty context brackets, so calls are scheduled operations. Their results become available on completion; the interface does not promise a fixed number of cycles. An availability check is not a reservation for a later read. The reader below uses TryRead’s completed result directly, avoiding a separate check followed by a read. Sharing a source among concurrent clients would additionally require an access or arbitration contract.

Implement and use an interface

A component implements an interface with : and supplies the required functions with override. The following source holds one byte. Its first successful read consumes that byte, and later reads report that no data remains:

livt
component OneByteSource : IByteSource
{
    stored: byte
    available: bool

    new(value: byte)
    {
        stored = value
        available = true
    }

    override fn HasData() bool { return available }

    override fn TryRead(value: out byte) bool
    {
        if (available) {
            value = stored
            available = false
            return true
        }
        else {
            value = 0x00
            return false
        }
    }
}

The interface exposes the operations; stored and available remain implementation details. Construction and processes belong to concrete components. Required function signatures must match the contract, including parameter directions and result types. The override declaration identifies the function that fulfils that requirement.

Read through the shared contract

The reader receives an existing source through its constructor and keeps an interface-typed reference. It returns the received byte or a caller-supplied fallback:

livt
component ByteReader
{
    source: IByteSource

    new(source: IByteSource) { this.source = source }

    public fn ReadOr(fallback: byte) byte
    {
        var value: byte
        if (source.TryRead(value)) {
            return value
        }
        else {
            return fallback
        }
    }
}

Nothing in ReadOr depends on OneByteSource. The same reader works with a ConstantByteSource that supplies its configured byte repeatedly, or an EmptyByteSource that always reports no data. This is useful substitutability: implementations can differ while their externally visible behaviour remains consistent with the contract.

Assemble components

A parent component chooses which concrete implementations to construct and how they connect. Here ByteApplication owns a one-byte source and a reader stage. The stage constructs its own ByteReader and passes the existing source to it:

livt
component ByteApplication
{
    source: OneByteSource
    stage: ReaderStage

    new()
    {
        source = new OneByteSource(0x41)
        stage = new ReaderStage(source)
    }

    public fn ReadOr(fallback: byte) byte {
        return stage.ReadOr(fallback)
    }
}
owned components and a borrowed byte-source reference
Construction creates the owned components. Passing the source through the stage lets the reader use the same existing source.

Distinguish ownership from a borrowed reference

The new OneByteSource(0x41) expression constructs a component. Passing source to ReaderStage does not create another source or copy its stored byte. The stage forwards the reference, and the reader’s source: IByteSource field refers to that same hardware. Reading through the reader therefore consumes the byte held by the original instance.

Use construction for the components a parent owns and compatible existing references for dependencies supplied from outside. Livt has no built-in null value. If an optional feature should produce no data, supply a real implementation with that behaviour, such as EmptyByteSource. This keeps the dependency usable through the same contract.

Extend a contract when the role requires it

An interface can extend another interface to add operations or fields for a more specific role. A component implementing that specialised interface can be used where its parent interface is expected, but a parent-typed reference exposes only the parent contract. Keep those relationships shallow enough that the required operations and signals remain easy to find.

Inheritance expresses a shared role; composition expresses which hardware a design contains. They work together here: the reader accepts the shared source contract, and its parent selects a concrete source. See Building Blocks for component construction and ownership.

Apply dependency inversion

If ByteReader constructed OneByteSource directly, its reading behaviour would be tied to that one source. Depending on IByteSource instead places a stable contract between the high-level behaviour and its implementations. The reader depends on the contract, each source implements it, and the application chooses which source becomes part of the design. This is the dependency inversion principle.

Inversion here describes the direction of a design dependency. It is unrelated to flip, active-low signals, or reversing an interface's signal directions.

ByteReader depending on IByteSource while ByteApplication selects and injects OneByteSource
The composition root selects the implementation. The reader and source meet through one hardware contract.

Inject an existing component through construction

The existing new(source: IByteSource) constructor is constructor dependency injection. ByteApplication is the composition root: it owns the concrete source, constructs it once, and supplies that same instance to the reader through ReaderStage. The receiving field is a borrowed structural reference. It does not copy the component or allocate another source.

The connection is fixed as the hardware design is compiled. Livt does not generate a runtime service container, lookup mechanism, dynamic dispatch, or implementation-selection multiplexer. The selected source still contributes its real logic, state, timing, reset behaviour, and resource use.

Select owned hardware with a generic type

A generic type parameter can expose the implementation choice when a reusable component should own and construct the dependency itself. The interface bound states the required contract, while the constructor bound states how the selected component must be constructed:

livt
component ByteApplication<S: IByteSource & new(byte) = OneByteSource>
{
    source: S
    reader: ByteReader

    new(value: byte)
    {
        source = new S(value)
        reader = new ByteReader(source)
    }
}

ByteApplication<OneByteSource> is specialised during compilation, and new S(value) becomes construction of the selected concrete source. This is also static dependency injection, but it differs from constructor injection in ownership: the generic application constructs the selected dependency, whereas a constructor parameter supplies an instance that already exists.

FormUse it whenOwnership
Constructor injectionThe composition root must configure, connect, or share an existing componentThe composition root owns it; the receiver borrows it
Generic type injectionA reusable component should expose a compile-time implementation choiceThe generic component can construct it when its bound includes new(...)

Dependency inversion is useful only when the contract captures meaningful substitutability. In hardware, that includes more than matching function names and types: implementations must also satisfy the expected latency, throughput, acceptance, backpressure, concurrency, ownership, and clock-domain rules. Keep important selections visible in the composition root so readers can see which hardware policies the design uses.

Connect a signal interface

For communication defined at clock edges, an interface can group the signals of a protocol. This byte stream is declared from the consumer’s perspective: valid and data arrive at the consumer, and ready travels back to the producer. The example uses boolean control signals and a byte payload:

livt
interface IByteStream
{
    valid: in bool
    data: in byte
    ready: out bool
}

Choose one endpoint perspective

Read each direction relative to the component providing this interface. The consumer receives input signals and drives its output signal. A producer connected from the opposite side drives the consumer’s inputs and observes its output:

SignalConsumer perspectiveProducer role
valid: in boolRead whether a byte is offeredDrive whether data is valid
data: in byteRead the offered byteDrive the payload
ready: out boolDrive whether a byte can be acceptedRead whether the consumer is ready

For this protocol, a transfer occurs on a shared clock edge when valid and ready are both true. While valid is true and ready is false, the producer keeps valid asserted and data stable. Once a byte is accepted, it may present the next byte. These are the example’s protocol rules; the field names alone do not enforce them or create buffering.

Implement the signal endpoint

Directed fields declared by an implemented interface are available on the component automatically. StreamConsumer therefore uses valid, data, and ready without redeclaring them. Its accept input controls readiness. The combinational process calculates acceptance from the current signals, and the clocked process records accepted bytes:

livt
component StreamConsumer : IByteStream
{
    public accept: in bool
    public accepted: out int
    public last: out byte
    transfer: bool
    currentData: byte

    process Evaluate[]() {
        this.ready = this.accept
        transfer = this.valid && this.ready
        currentData = this.data
    }

    process Consume() {
        state Tick {
            if (transfer) {
                this.last = currentData
                this.accepted++
            }
            goto Tick
        }
    }
}

The transfer and currentData fields carry the combinational decision and payload into the recurring clocked step. On an accepted transfer, the consumer records last and increments accepted. When readiness is withdrawn, it stops accepting bytes. Keeping the combinational decision separate from the clocked update makes the edge contract visible; see Execution Models for these two process forms.

byte-stream interface and consumer implementation in VS Code
The implementation uses the interface’s directed fields and keeps acceptance logic separate from clocked updates.

Connect the opposite endpoint

The producer needs the opposite orientation of IByteStream. A flip constructor parameter gives it that view: it can drive valid and data and read ready. The interface declaration remains in the consumer’s perspective.

livt
component StreamProducer
{
    stream: IByteStream
    index: int

    new(stream: flip IByteStream) { this.stream = stream }

    process Drive[]() {
        stream.valid = true
        stream.data = index as byte
    }

    process Advance() {
        state Tick {
            if (stream.ready) {
                index = (index + 1) % 256
            }
            goto Tick
        }
    }
}

This producer continually offers a byte, beginning at zero. It advances its value only when the consumer is ready, wrapping after 255. Because valid is always true in this example, ready alone identifies an accepted transfer in Advance. A producer that sometimes withdraws valid must advance only when both signals indicate a transfer.

producer and consumer signal directions with a flipped binding
Data and valid travel toward the consumer; ready returns toward the producer. Flip establishes the opposite endpoint view at construction.

Flip changes the orientation of the constructor binding; it is not a runtime action or a function-parameter modifier. Keep the view consistent rather than reversing individual field declarations to make an assignment compile. A write to an input from the wrong side is rejected by validation:

invalid write to an interface input in VS Code
An endpoint that receives data cannot drive that input. Check the chosen perspective and constructor binding.

Forward the connection through a parent

A parent can pass a dependency to a child without inspecting its contents. ReaderStage does this with the ordinary byte-source contract:

livt
component ReaderStage
{
    reader: ByteReader

    new(source: IByteSource) { reader = new ByteReader(source) }

    public fn ReadOr(fallback: byte) byte {
        return reader.ReadOr(fallback)
    }
}

The stage owns the reader, while the source is supplied from outside and remains the same instance. Its public ReadOr delegates a scheduled operation to the reader; forwarding the constructor reference does not make that function call combinational or remove its completion protocol.

For a signal endpoint, retain the flipped orientation when forwarding it to a producer child:

livt
component ProducerStage
{
    producer: StreamProducer

    new(stream: flip IByteStream) {
        producer = new StreamProducer(stream)
    }
}

The downloaded StreamLink constructs StreamConsumer and passes it to ProducerStage, which constructs the producer. This creates the signal connection through two levels of ownership. Passing a bundle through a constructor adds no queue or protocol transformation by itself. It also does not establish a clock-domain crossing: define the required crossing and synchronised access explicitly, as described in Contexts.

Test the contract

A small implementation lets a test exercise a consumer without constructing an entire subsystem. The empty source supplies a predictable unavailable-data case while still satisfying the same interface:

livt
component EmptyByteSource : IByteSource
{
    override fn HasData() bool { return false }
    override fn TryRead(value: out byte) bool {
        value = 0x00
        return false
    }
}

The example tests the same ByteReader with a repeated constant source, a source consumed after one read, and an empty source. It checks both successful results and fallback behaviour, and separately verifies the output value returned on an unsuccessful read. A construction test also reads through ByteApplication and ReaderStage to confirm that the forwarded reference reaches the intended source.

Check acceptance and backpressure

Signal tests must check the protocol, not just the final value. With accept false, the test samples the offered byte and accepted count, advances time, and verifies that the producer still presents the same valid byte without a new acceptance:

livt
var held: byte
var before: int
state {
    held = link.data
    before = link.accepted
    assert link.valid == true
    assert link.ready == false
}
state {}
state {
    assert link.data == held
    assert link.valid == true
    assert link.accepted == before
}

The remaining tests check acceptance on consecutive eligible edges and the received byte order. They also interrupt an active stream, verify stability while it is stalled, then re-enable acceptance and check that the stream continues correctly. The tests use explicit observation states and allow setup signals to settle before sampling. See Testing for edge-sensitive observations and useful diagnostics.

Extract the InterfacesDemo project, open its folder in Visual Studio Code, and run InterfacesTest from Livt Tests or Test Explorer. All six tests should pass. The source tests use separate consumable fixtures so that one check does not depend on another leaving data unread.

six passing interface contract tests in VS Code
The tests cover interchangeable providers, unavailable data, forwarded references, accepted transfers, and backpressure.

Keep interfaces focused

Expose the operations and signals that define the role, and leave private counters, storage layout, and helper functions inside the implementation. A smaller contract is easier to implement, document, and replace. When several implementations share an interface, their timing, reset, and failure behaviour still need to meet the caller’s expectations.

Choose a scheduled operation when the caller can wait for a completed result. Choose a signal protocol when acceptance and response must be defined at clock edges. A single design can use both, but the relationship between them should be explicit. Likewise, sharing a type or forwarding a reference does not provide arbitration, buffering, or synchronisation automatically.

Document the chosen endpoint perspective, the transfer condition, behaviour while waiting, and reset expectations alongside the interface. Keep one intended driver for each signal and verify the cases where progress stops and resumes. Use Register Interfaces when exposing a hardware contract to software.