Skip to content

Types

Static terms are the types, indices, shapes, and effect references of the core (family declarations). A vector's length index, for instance, constrains how many elements a value has, and the checker tracks that constraint through constructor applications and effectful computations. The module also renders static terms as text.

IndexSum represents canonical addition of Nat variables and a nonnegative constant. add_indices folds constants and nested sums; shift_index adds an offset or removes one already proved present in the constant part. Rigid identities survive both operations. The checked source form is nat_add(n, 1), described in the index reference.

solve_index_equation cancels affine terms only when the solution remains a representable nonnegative Nat expression. infer_index_extents solves exact shape equations, reports inconsistent or nonintegral evidence, and leaves underdetermined variables unbound. Neither helper guesses that unrelated axes coincide because their extents happen to agree.

types

Static terms for the Quivers Indexed Effect Core (QIEC).

The module intentionally models only the kernel's small static language. Didactic and Panproto check a first-order projection of its indexed-family declarations, while these frozen records retain the QIEC-specific distinction between uniform parameters and refinable indices.

UNIT module-attribute

UNIT = TypeApplication(constructor=TypeConstructorRef.builtin('Unit'))

The unit type, inhabited by None alone.

BOOL module-attribute

BOOL = TypeApplication(constructor=TypeConstructorRef.builtin('Bool'))

The Boolean type.

INT module-attribute

INT = TypeApplication(constructor=TypeConstructorRef.builtin('Int'))

The integer type.

REAL module-attribute

REAL = TypeApplication(constructor=TypeConstructorRef.builtin('Real'))

The real-number type.

STRING module-attribute

STRING = TypeApplication(constructor=TypeConstructorRef.builtin('String'))

The string type.

IndexTerm

A static index: a variable, a literal, a constructor application, or a shape.

TypeExpr

A type: a variable, an application, a function, an equality, a record, or a variant.

AxisType

AxisType = TypeExpr | UserIndexSort

What a named tensor axis ranges over: a finite type or a finite index sort.

StaticArgument

Anything a telescope binder may be instantiated at: a type, a row, an index, or an effect.

IndexVariable didactic-model

IndexVariable(*, name: str, sort: IndexSort = field(opaque=True, extras=OPAQUE_BY_VALUE), identity: StaticVariableId | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['index_variable'] = 'index_variable')

Bases: QiecModel

A variable standing for an index term.

PARAMETER DESCRIPTION
name

The variable's display name.

TYPE: str

sort

The closed index sort of the terms it stands for.

TYPE: IndexSort DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

identity

The rigid identity of a case branch's skolem, or None for a declaration binder matched by name.

TYPE: StaticVariableId | None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

tag

The serialization discriminator; always "index_variable".

TYPE: Literal['index_variable'] DEFAULT: 'index_variable'

IndexLiteral didactic-model

IndexLiteral(*, value: int | str, sort: IndexSort = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['index_literal'] = 'index_literal')

Bases: QiecModel

A closed index literal.

PARAMETER DESCRIPTION
value

A natural number for the nat sort, or a nullary constructor name for a user-defined index sort.

TYPE: int | str

sort

The sort the literal inhabits.

TYPE: IndexSort DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

tag

The serialization discriminator; always "index_literal".

TYPE: Literal['index_literal'] DEFAULT: 'index_literal'

IndexConstructor didactic-model

IndexConstructor(*, name: str, arguments: tuple[IndexTerm, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), sort: IndexSort = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['index_constructor'] = 'index_constructor')

Bases: QiecModel

A fully applied constructor of a user-defined index sort.

PARAMETER DESCRIPTION
name

The constructor's name, which must belong to sort.

TYPE: str

arguments

The constructor's index arguments, in order.

TYPE: tuple[IndexTerm, ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

sort

The sort the constructor builds.

TYPE: IndexSort DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

tag

The serialization discriminator; always "index_constructor".

TYPE: Literal['index_constructor'] DEFAULT: 'index_constructor'

IndexSum didactic-model

IndexSum(*, terms: tuple[IndexVariable, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), constant: int = 0, tag: Literal['index_sum'] = 'index_sum')

Bases: QiecModel

A canonical sum of natural-number variables and a constant.

PARAMETER DESCRIPTION
terms

Nat variables, sorted by nominal identity; repeated summands remain.

TYPE: tuple[IndexVariable, ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

constant

Nonnegative constant part. Use add_indices or shift_index to fold literals, flatten sums, and collapse zero or singleton expressions.

TYPE: int DEFAULT: 0

tag

Serialization discriminator, always "index_sum".

TYPE: str DEFAULT: 'index_sum'

sort property

sort: NatSort

The intrinsic natural-number sort of this sum.

RETURNS DESCRIPTION
NatSort

The closed Nat sort, independent of every summand's name.

ShapeIndex didactic-model

ShapeIndex(*, dimensions: tuple[IndexTerm, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['shape_index'] = 'shape_index')

Bases: QiecModel

A shape given by its dimensions.

PARAMETER DESCRIPTION
dimensions

One index term per dimension, outermost first.

TYPE: tuple[IndexTerm, ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

tag

The serialization discriminator; always "shape_index".

TYPE: Literal['shape_index'] DEFAULT: 'shape_index'

TypeVariable didactic-model

TypeVariable(*, name: str, kind: Kind = field(default=TYPE, opaque=True, extras=OPAQUE_BY_VALUE), identity: StaticVariableId | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['type_variable'] = 'type_variable')

Bases: QiecModel

A variable standing for a type or effect-kinded static argument.

PARAMETER DESCRIPTION
name

The variable's display name.

TYPE: str

kind

The kind of the arguments it stands for.

TYPE: Kind DEFAULT: field(default=TYPE, opaque=True, extras=OPAQUE_BY_VALUE)

identity

The rigid identity of a case branch's skolem, or None for a declaration binder matched by name.

TYPE: StaticVariableId | None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

tag

The serialization discriminator; always "type_variable".

TYPE: Literal['type_variable'] DEFAULT: 'type_variable'

TypeConstructorRef didactic-model

TypeConstructorRef(*, id: TypeId = field(opaque=True, extras=OPAQUE_BY_VALUE), name: str, telescope: Telescope = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A fully qualified type constructor and its kinding telescope.

PARAMETER DESCRIPTION
id

The constructor's stable identity, which alone determines equality.

TYPE: TypeId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

name

The constructor's display name.

TYPE: str

telescope

The binders the constructor's arguments instantiate, in order.

TYPE: Telescope DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

builtin classmethod

builtin(name: str) -> TypeConstructorRef

A constructor for one of the language's own types.

PARAMETER DESCRIPTION
name

The builtin's name.

TYPE: str

RETURNS DESCRIPTION
TypeConstructorRef

A nullary constructor whose identity derives from the builtin namespace, so Int means the same type in every module without being declared in any of them.

Source code in src/quivers/qiec/types.py
@classmethod
def builtin(cls, name: str) -> TypeConstructorRef:
    """A constructor for one of the language's own types.

    Parameters
    ----------
    name : str
        The builtin's name.

    Returns
    -------
    TypeConstructorRef
        A nullary constructor whose identity derives from the
        ``builtin`` namespace, so `Int` means the same type in every
        module without being declared in any of them.
    """
    return cls(id=TypeId.derive("builtin", name), name=name)

TypeApplication didactic-model

TypeApplication(*, constructor: TypeConstructorRef = field(opaque=True, extras=OPAQUE_BY_VALUE), arguments: tuple[StaticArgument, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['type_application'] = 'type_application')

Bases: QiecModel

A type constructor applied to static arguments.

PARAMETER DESCRIPTION
constructor

The constructor applied.

TYPE: TypeConstructorRef DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

arguments

The arguments instantiating the constructor's telescope, in order; empty for a nullary constructor.

TYPE: tuple[StaticArgument, ...] DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

tag

The serialization discriminator; always "type_application".

TYPE: Literal['type_application'] DEFAULT: 'type_application'

FunctionType didactic-model

FunctionType(*, parameter: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE), result: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE), effects: EffectRow = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['function_type'] = 'function_type')

Bases: QiecModel

The type of a function value, with the row its application performs.

A function value is a closure: building one performs nothing, and applying one runs its body, which may request the instances of effects. The value stratum stays first order in the sense that applying is a computation, never a value.

PARAMETER DESCRIPTION
parameter

The argument type.

TYPE: TypeExpr DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

result

The result type.

TYPE: TypeExpr DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

effects

The effect row an application of the function may perform; the empty row for a pure function.

TYPE: EffectRow DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

tag

The serialization discriminator; always "function_type".

TYPE: Literal['function_type'] DEFAULT: 'function_type'

EqualityType didactic-model

EqualityType(*, kind: Kind | IndexSort = field(opaque=True, extras=OPAQUE_BY_VALUE), left: StaticArgument = field(opaque=True, extras=OPAQUE_BY_VALUE), right: StaticArgument = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['equality_type'] = 'equality_type')

Bases: QiecModel

The proposition that two static arguments are equal.

PARAMETER DESCRIPTION
kind

The kind or index sort both sides inhabit.

TYPE: Kind | IndexSort DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

left

The left side of the equation.

TYPE: StaticArgument DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

right

The right side of the equation.

TYPE: StaticArgument DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

tag

The serialization discriminator; always "equality_type".

TYPE: Literal['equality_type'] DEFAULT: 'equality_type'

RowField didactic-model

RowField(*, label: str, type: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

One labelled entry of a row of types.

PARAMETER DESCRIPTION
label

The entry's label, unique within its row.

TYPE: str

type

The type the label carries: a field's type in a record, an alternative's payload type in a variant.

TYPE: TypeExpr DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

TypeRow didactic-model

TypeRow(*, fields: tuple[RowField, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), tail: TypeVariable | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['type_row'] = 'type_row')

Bases: QiecModel

A finite map from labels to types, closed or open in a row variable.

Labels are unique: a row is a set of labelled types, not a list with shadowing, so {a : Int | r} asserts that r has no a. Fields are sorted by label at construction, which makes equality insensitive to the order a row is written in and fixes the canonical field order every first-order encoding uses.

PARAMETER DESCRIPTION
fields

The explicit entries, in any order.

TYPE: tuple[RowField, ...] DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

tail

A variable of the data-row kind standing for further entries, or None for a closed row.

TYPE: TypeVariable | None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

tag

The serialization discriminator; always "type_row".

TYPE: Literal['type_row'] DEFAULT: 'type_row'

labels property

labels: tuple[str, ...]

The explicit labels, in canonical order.

RETURNS DESCRIPTION
tuple[str, ...]

The sorted labels of the explicit fields.

closed property

closed: bool

Whether the row has no tail.

RETURNS DESCRIPTION
bool

True for a closed row, whose labels are exactly its fields.

lookup

lookup(label: str) -> TypeExpr | None

The type an explicit label carries.

PARAMETER DESCRIPTION
label

The label to resolve.

TYPE: str

RETURNS DESCRIPTION
TypeExpr or None

The type, or None when no explicit field has the label. The tail is not consulted.

Source code in src/quivers/qiec/types.py
def lookup(self, label: str) -> TypeExpr | None:
    """The type an explicit label carries.

    Parameters
    ----------
    label : str
        The label to resolve.

    Returns
    -------
    TypeExpr or None
        The type, or None when no explicit field has the label. The
        tail is not consulted.
    """
    return next((field.type for field in self.fields if field.label == label), None)

position

position(label: str) -> int

The canonical position of an explicit label.

PARAMETER DESCRIPTION
label

The label to locate.

TYPE: str

RETURNS DESCRIPTION
int

Its zero-based position among the sorted explicit labels, which is its offset in a closed row's first-order encoding.

RAISES DESCRIPTION
KeyError

If no explicit field has the label.

Source code in src/quivers/qiec/types.py
def position(self, label: str) -> int:
    """The canonical position of an explicit label.

    Parameters
    ----------
    label : str
        The label to locate.

    Returns
    -------
    int
        Its zero-based position among the sorted explicit labels,
        which is its offset in a closed row's first-order encoding.

    Raises
    ------
    KeyError
        If no explicit field has the label.
    """
    try:
        return self.labels.index(label)
    except ValueError as error:
        raise KeyError(label) from error

RecordType didactic-model

RecordType(*, row: TypeRow = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['record_type'] = 'record_type')

Bases: QiecModel

The type of records whose fields are the entries of a row.

PARAMETER DESCRIPTION
row

The fields: one value of each labelled type.

TYPE: TypeRow DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

tag

The serialization discriminator; always "record_type".

TYPE: Literal['record_type'] DEFAULT: 'record_type'

VariantType didactic-model

VariantType(*, row: TypeRow = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['variant_type'] = 'variant_type')

Bases: QiecModel

The type of variants whose alternatives are the entries of a row.

PARAMETER DESCRIPTION
row

The alternatives: a value is one label with a payload of its type.

TYPE: TypeRow DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

tag

The serialization discriminator; always "variant_type".

TYPE: Literal['variant_type'] DEFAULT: 'variant_type'

AxisExtent didactic-model

AxisExtent(*, value: int | str, sort: IndexSort = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['axis_extent'] = 'axis_extent', axis: AxisType = field(opaque=True, extras=OPAQUE_BY_VALUE), label: str | None = None)

Bases: IndexLiteral

The extent of a tensor axis named by a finite type.

The inherited value gives the axis's cardinality and sort is always Nat. The dimension ranges over the elements of axis in their canonical order. Positional dimensions are plain literals and variables, which is the Fin n case. Because the name is part of the dimension, every computation on shapes (slicing, broadcasting, a comprehension's extent, a plate's size) carries it unchanged, and two tensors over different finite types of one cardinality have different types.

A record type is known by its fields, so the name an axis is written with, such as a declared record's, is kept as a display label: data and transpile targets name the axis by it. The label is not part of the type: two extents over one type are equal whatever their labels, and content hashes drop it.

PARAMETER DESCRIPTION
axis

The finite type or index sort the axis ranges over.

TYPE: AxisType DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

label

The name the axis is written with where it is used, or None for an axis written as a type expression.

TYPE: str | None DEFAULT: None

tag

The serialization discriminator; always "axis_extent".

TYPE: Literal['axis_extent'] DEFAULT: 'axis_extent'

EffectVariable didactic-model

EffectVariable(*, name: str, identity: StaticVariableId | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['effect_variable'] = 'effect_variable')

Bases: QiecModel

A variable standing for an effect interface application.

PARAMETER DESCRIPTION
name

The variable's display name.

TYPE: str

identity

The rigid identity of a case branch's skolem, or None for a declaration binder matched by name.

TYPE: StaticVariableId | None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

tag

The serialization discriminator; always "effect_variable".

TYPE: Literal['effect_variable'] DEFAULT: 'effect_variable'

EffectRef didactic-model

EffectRef(*, id: EffectId = field(opaque=True, extras=OPAQUE_BY_VALUE), name: str, arguments: tuple[StaticArgument, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['effect_ref'] = 'effect_ref')

Bases: QiecModel

One closed effect interface application.

PARAMETER DESCRIPTION
id

The stable identity of the interface declaration.

TYPE: EffectId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

name

The interface's display name.

TYPE: str

arguments

The arguments instantiating the interface's telescope, in order.

TYPE: tuple[StaticArgument, ...] DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

tag

The serialization discriminator; always "effect_ref".

TYPE: Literal['effect_ref'] DEFAULT: 'effect_ref'

add_indices

add_indices(*terms: IndexTerm) -> IndexTerm

Add Nat indices, folding constants and flattening nested sums.

PARAMETER DESCRIPTION
*terms

Natural-number indices. An empty sum denotes zero.

TYPE: IndexTerm DEFAULT: ()

RETURNS DESCRIPTION
IndexTerm

A canonical literal, variable, or IndexSum. Rigid identities survive.

RAISES DESCRIPTION
TypeError

If a term is not a Nat literal, Nat variable, or Nat sum.

Source code in src/quivers/qiec/types.py
def add_indices(*terms: IndexTerm) -> IndexTerm:
    """Add Nat indices, folding constants and flattening nested sums.

    Parameters
    ----------
    *terms : IndexTerm
        Natural-number indices. An empty sum denotes zero.

    Returns
    -------
    IndexTerm
        A canonical literal, variable, or `IndexSum`. Rigid identities survive.

    Raises
    ------
    TypeError
        If a term is not a Nat literal, Nat variable, or Nat sum.
    """
    variables = []
    constant = 0
    for term in terms:
        if isinstance(term, IndexSum):
            variables.extend(term.terms)
            constant += term.constant
        elif isinstance(term, IndexVariable) and term.sort == NAT:
            variables.append(term)
        elif (
            isinstance(term, IndexLiteral)
            and term.sort == NAT
            and not isinstance(term.value, bool)
        ):
            constant += int(term.value)
        else:
            raise TypeError("natural-number addition requires Nat indices")
    if not variables:
        return IndexLiteral(value=constant, sort=NAT)
    variables.sort(key=_summand_key)
    if len(variables) == 1 and constant == 0:
        return variables[0]
    return IndexSum(terms=tuple(variables), constant=constant)

shift_index

shift_index(term: IndexTerm, offset: int) -> IndexTerm

Shift a Nat extent, removing only a provably present constant part.

PARAMETER DESCRIPTION
term

A natural-number extent.

TYPE: IndexTerm

offset

Integer shift. A negative shift must be absorbed by a literal or the existing constant part of a sum; no unconstrained predecessor exists.

TYPE: int

RETURNS DESCRIPTION
IndexTerm

The canonical shifted extent, retaining every symbolic identity.

RAISES DESCRIPTION
TypeError

If the extent is not Nat or the offset is not an integer.

ValueError

If a negative shift cannot be proved nonnegative.

Source code in src/quivers/qiec/types.py
def shift_index(term: IndexTerm, offset: int) -> IndexTerm:
    """Shift a Nat extent, removing only a provably present constant part.

    Parameters
    ----------
    term : IndexTerm
        A natural-number extent.
    offset : int
        Integer shift. A negative shift must be absorbed by a literal or the
        existing constant part of a sum; no unconstrained predecessor exists.

    Returns
    -------
    IndexTerm
        The canonical shifted extent, retaining every symbolic identity.

    Raises
    ------
    TypeError
        If the extent is not Nat or the offset is not an integer.
    ValueError
        If a negative shift cannot be proved nonnegative.
    """
    if isinstance(offset, bool) or not isinstance(offset, int):
        raise TypeError("an index offset must be an integer")
    canonical = add_indices(term)
    if offset >= 0:
        return add_indices(canonical, IndexLiteral(value=offset, sort=NAT))
    if isinstance(canonical, IndexLiteral) and int(canonical.value) + offset >= 0:
        return IndexLiteral(value=int(canonical.value) + offset, sort=NAT)
    if isinstance(canonical, IndexSum) and canonical.constant + offset >= 0:
        return add_indices(
            *canonical.terms, IndexLiteral(value=canonical.constant + offset, sort=NAT)
        )
    raise ValueError("cannot remove an unproved natural-number extent offset")

product_type

product_type(*components: TypeExpr) -> TypeApplication

Construct the canonical finite-product type of the given arity.

PARAMETER DESCRIPTION
components

The component types, in order.

TYPE: TypeExpr DEFAULT: ()

RETURNS DESCRIPTION
TypeApplication

The product. Its constructor identity derives from the arity, so every two-component product in every module is the same type constructor and two products of different arity are different ones.

Source code in src/quivers/qiec/types.py
def product_type(*components: TypeExpr) -> TypeApplication:
    """Construct the canonical finite-product type of the given arity.

    Parameters
    ----------
    components : TypeExpr
        The component types, in order.

    Returns
    -------
    TypeApplication
        The product. Its constructor identity derives from the arity, so
        every two-component product in every module is the same type
        constructor and two products of different arity are different
        ones.
    """

    arity = len(components)
    constructor = TypeConstructorRef(
        id=TypeId.derive("builtin", "Product", arity),
        name=f"Product{arity}",
        telescope=tuple(
            TypeBinder(name=f"item{position}") for position in range(arity)
        ),
    )
    return TypeApplication(constructor=constructor, arguments=components)

static_kind

static_kind(term: StaticArgument) -> Kind

Return the outer kind of a static term.

Index sorts are deliberately not collapsed into Type: callers that validate an index binder compare the term's concrete sort separately.

PARAMETER DESCRIPTION
term

The static term to classify.

TYPE: StaticArgument

RETURNS DESCRIPTION
Kind

The term's kind.

RAISES DESCRIPTION
TypeError

If the term is an index, which carries a sort rather than a kind. Raising rather than returning a placeholder is what keeps a caller from comparing an index against a kind and finding them equal.

Source code in src/quivers/qiec/types.py
def static_kind(term: StaticArgument) -> Kind:
    """Return the outer kind of a static term.

    Index sorts are deliberately not collapsed into ``Type``: callers that
    validate an index binder compare the term's concrete ``sort`` separately.

    Parameters
    ----------
    term : StaticArgument
        The static term to classify.

    Returns
    -------
    Kind
        The term's kind.

    Raises
    ------
    TypeError
        If the term is an index, which carries a sort rather than a kind.
        Raising rather than returning a placeholder is what keeps a
        caller from comparing an index against a kind and finding them
        equal.
    """

    if isinstance(term, (EffectRef, EffectVariable)):
        return EFFECT
    if isinstance(term, TypeVariable):
        return term.kind
    if isinstance(term, TypeRow):
        return DATA_ROW
    if isinstance(
        term, (TypeApplication, FunctionType, EqualityType, RecordType, VariantType)
    ):
        return TYPE
    raise TypeError("index terms have a sort, not a QIEC kind")

index_sort

index_sort(term: IndexTerm) -> IndexSort

Return an index term's sort, checking shape dimensions.

PARAMETER DESCRIPTION
term

The index whose sort is wanted.

TYPE: IndexTerm

RETURNS DESCRIPTION
IndexSort

The term's sort. A shape reports its concrete rank, which is what lets a rank-polymorphic binder accept it while a binder of a fixed rank does not.

RAISES DESCRIPTION
TypeError

If a shape dimension is not of Nat sort. A dimension is a count, so admitting anything else would let a shape be indexed by a value that cannot be one.

Source code in src/quivers/qiec/types.py
def index_sort(term: IndexTerm) -> IndexSort:
    """Return an index term's sort, checking shape dimensions.

    Parameters
    ----------
    term : IndexTerm
        The index whose sort is wanted.

    Returns
    -------
    IndexSort
        The term's sort. A shape reports its concrete rank, which is what
        lets a rank-polymorphic binder accept it while a binder of a
        fixed rank does not.

    Raises
    ------
    TypeError
        If a shape dimension is not of `Nat` sort. A dimension is a
        count, so admitting anything else would let a shape be indexed by
        a value that cannot be one.
    """

    if isinstance(term, ShapeIndex):
        for dimension in term.dimensions:
            if index_sort(dimension) != NAT:
                raise TypeError("shape dimensions must have Nat sort")
        return ShapeSort(rank=len(term.dimensions))
    return term.sort

validate_static_argument

validate_static_argument(term: StaticArgument) -> None

Recursively validate one intrinsically kinded static argument.

PARAMETER DESCRIPTION
term

The static term to validate, together with everything nested in it.

TYPE: StaticArgument

RAISES DESCRIPTION
TypeError

If a term is of a class that cannot appear in a static position.

ValueError

If an application is ill-kinded, or an index constructor is applied at the wrong arity.

Source code in src/quivers/qiec/types.py
def validate_static_argument(term: StaticArgument) -> None:
    """Recursively validate one intrinsically kinded static argument.

    Parameters
    ----------
    term : StaticArgument
        The static term to validate, together with everything nested in
        it.

    Raises
    ------
    TypeError
        If a term is of a class that cannot appear in a static position.
    ValueError
        If an application is ill-kinded, or an index constructor is
        applied at the wrong arity.
    """
    if isinstance(term, TypeVariable | EffectVariable | IndexVariable | IndexLiteral):
        return
    if isinstance(term, TypeApplication):
        check_static_arguments(term.constructor.telescope, term.arguments)
        return
    if isinstance(term, FunctionType):
        validate_static_argument(term.parameter)
        validate_static_argument(term.result)
        if static_kind(term.parameter) != TYPE:
            raise TypeError("function parameter must have Type kind")
        if static_kind(term.result) != TYPE:
            raise TypeError("function result must have Type kind")
        for entry in term.effects.entries:
            validate_static_argument(entry.effect)
        return
    if isinstance(term, RecordType | VariantType):
        validate_static_argument(term.row)
        return
    if isinstance(term, TypeRow):
        for field in term.fields:
            validate_static_argument(field.type)
            if static_kind(field.type) != TYPE:
                raise TypeError(f"row label {field.label!r} must carry a type")
        return
    if isinstance(term, EqualityType):
        validate_static_argument(term.left)
        validate_static_argument(term.right)
        index_kinds = (NatSort, ShapeSort, ContextSort, UserIndexSort)
        index_nodes = (
            IndexVariable,
            IndexLiteral,
            IndexConstructor,
            IndexSum,
            ShapeIndex,
        )
        if isinstance(term.kind, index_kinds):
            if not isinstance(term.left, index_nodes) or not isinstance(
                term.right, index_nodes
            ):
                raise TypeError("index equality endpoints must be index terms")
            if not _sort_matches(term.kind, index_sort(term.left)) or not _sort_matches(
                term.kind, index_sort(term.right)
            ):
                raise TypeError("index equality endpoint has the wrong sort")
        elif (
            static_kind(term.left) != term.kind or static_kind(term.right) != term.kind
        ):
            raise TypeError("equality endpoint has the wrong kind")
        return
    if isinstance(term, EffectRef):
        for argument in term.arguments:
            validate_static_argument(argument)
        return
    if isinstance(term, IndexSum):
        for argument in term.terms:
            validate_static_argument(argument)
        return
    if isinstance(term, IndexConstructor):
        for argument in term.arguments:
            validate_static_argument(argument)
        index_sort(term)
        return
    if isinstance(term, ShapeIndex):
        index_sort(term)
        for dimension in term.dimensions:
            validate_static_argument(dimension)
        return
    raise TypeError(f"unknown static argument {term!r}")

check_static_arguments

check_static_arguments(telescope: Telescope, arguments: tuple[StaticArgument, ...]) -> tuple[tuple[tuple[str, TypeExpr | TypeRow], ...], tuple[tuple[str, IndexTerm], ...], tuple[tuple[str, EffectRef | EffectVariable], ...]]

Kind-check static arguments against a telescope and classify them.

PARAMETER DESCRIPTION
telescope

The binders the arguments instantiate, in order.

TYPE: Telescope

arguments

One argument per binder.

TYPE: tuple[StaticArgument, ...]

RETURNS DESCRIPTION
tuple[tuple[tuple[str, TypeExpr | TypeRow], ...], tuple[tuple[str, IndexTerm], ...], tuple[tuple[str, EffectRef | EffectVariable], ...]]

The type and row, index, and effect bindings the arguments make, each paired with its binder's name, in telescope order.

RAISES DESCRIPTION
TypeError

If the counts differ, an argument is of the wrong static class for its binder, or an argument is of the wrong kind or index sort.

ValueError

If a nested application is ill-kinded, or an index constructor is applied at the wrong arity.

Source code in src/quivers/qiec/types.py
def check_static_arguments(
    telescope: Telescope,
    arguments: tuple[StaticArgument, ...],
) -> tuple[
    tuple[tuple[str, TypeExpr | TypeRow], ...],
    tuple[tuple[str, IndexTerm], ...],
    tuple[tuple[str, EffectRef | EffectVariable], ...],
]:
    """Kind-check static arguments against a telescope and classify them.

    Parameters
    ----------
    telescope : Telescope
        The binders the arguments instantiate, in order.
    arguments : tuple[StaticArgument, ...]
        One argument per binder.

    Returns
    -------
    tuple[tuple[tuple[str, TypeExpr | TypeRow], ...], tuple[tuple[str, IndexTerm], ...], tuple[tuple[str, EffectRef | EffectVariable], ...]]
        The type and row, index, and effect bindings the arguments make,
        each paired with its binder's name, in telescope order.

    Raises
    ------
    TypeError
        If the counts differ, an argument is of the wrong static class
        for its binder, or an argument is of the wrong kind or index
        sort.
    ValueError
        If a nested application is ill-kinded, or an index constructor is
        applied at the wrong arity.
    """
    if len(telescope) != len(arguments):
        raise TypeError(
            f"expected {len(telescope)} static arguments, got {len(arguments)}"
        )

    types: list[tuple[str, TypeExpr | TypeRow]] = []
    indices: list[tuple[str, IndexTerm]] = []
    effects: list[tuple[str, EffectRef | EffectVariable]] = []
    for binder, argument in zip(telescope, arguments, strict=True):
        validate_static_argument(argument)
        if isinstance(binder, TypeBinder):
            if not isinstance(
                argument,
                (
                    TypeVariable,
                    TypeApplication,
                    FunctionType,
                    EqualityType,
                    RecordType,
                    VariantType,
                    TypeRow,
                ),
            ):
                raise TypeError(f"{binder.name!r} expects a type argument")
            if static_kind(argument) != binder.kind:
                raise TypeError(f"type argument for {binder.name!r} has wrong kind")
            types.append((binder.name, argument))
        elif isinstance(binder, IndexBinder):
            if not isinstance(
                argument,
                (IndexVariable, IndexConstructor, ShapeIndex),
            ) and not hasattr(argument, "sort"):
                raise TypeError(f"{binder.name!r} expects an index argument")
            actual_sort = index_sort(argument)  # type: ignore[arg-type]
            if not _sort_matches(binder.sort, actual_sort):
                raise TypeError(
                    f"index argument for {binder.name!r} has sort {actual_sort!r}, "
                    f"expected {binder.sort!r}"
                )
            indices.append((binder.name, argument))  # type: ignore[arg-type]
        elif isinstance(binder, EffectBinder):
            if not isinstance(argument, (EffectRef, EffectVariable)):
                raise TypeError(f"{binder.name!r} expects an effect argument")
            effects.append((binder.name, argument))
        else:  # pragma: no cover - closed binder union
            raise TypeError(f"unknown telescope binder {binder!r}")
    return tuple(types), tuple(indices), tuple(effects)

render_static

render_static(term: StaticArgument) -> str

Render a static term in the surface spelling.

PARAMETER DESCRIPTION
term

The type, index, or effect term to render.

TYPE: StaticArgument

RETURNS DESCRIPTION
str

A readable rendering: a constructor applied to its arguments in brackets, with shape arguments in parentheses after them; an arrow for a function type; an equality with ~; a shape as a bracketed dimension list; an index constructor as a call.

RAISES DESCRIPTION
TypeError

If the term is not a static term.

Source code in src/quivers/qiec/types.py
def render_static(term: StaticArgument) -> str:
    """Render a static term in the surface spelling.

    Parameters
    ----------
    term : StaticArgument
        The type, index, or effect term to render.

    Returns
    -------
    str
        A readable rendering: a constructor applied to its arguments in
        brackets, with shape arguments in parentheses after them; an
        arrow for a function type; an equality with ``~``; a shape as a
        bracketed dimension list; an index constructor as a call.

    Raises
    ------
    TypeError
        If the term is not a static term.
    """
    if isinstance(term, TypeVariable | EffectVariable | IndexVariable):
        return term.name
    if isinstance(term, AxisExtent):
        return render_axis(term.axis)
    if isinstance(term, IndexLiteral):
        return str(term.value)
    if isinstance(term, IndexSum):
        parts = [render_static(variable) for variable in term.terms]
        if term.constant:
            parts.append(str(term.constant))
        rendered = parts[0]
        for part in parts[1:]:
            rendered = f"nat_add({rendered}, {part})"
        return rendered
    if isinstance(term, IndexConstructor):
        if not term.arguments:
            return term.name
        inner = ", ".join(render_static(argument) for argument in term.arguments)
        return f"{term.name}({inner})"
    if isinstance(term, ShapeIndex):
        inner = ", ".join(render_static(dimension) for dimension in term.dimensions)
        return f"[{inner}]"
    if (
        isinstance(term, TypeApplication)
        and term.constructor.id == _TENSOR_ID
        and len(term.arguments) == 2
        and isinstance(term.arguments[1], ShapeIndex)
        and term.arguments[1].dimensions
    ):
        element = term.arguments[0]
        rendered = render_static(element)
        if isinstance(element, FunctionType | EqualityType):
            rendered = f"({rendered})"
        axes = ", ".join(
            _render_dimension(item) for item in term.arguments[1].dimensions
        )
        return f"{rendered}[{axes}]"
    if isinstance(term, TypeApplication | EffectRef):
        name = term.constructor.name if isinstance(term, TypeApplication) else term.name
        statics = [
            render_static(argument)
            for argument in term.arguments
            if not isinstance(argument, ShapeIndex)
        ]
        shapes = [
            render_static(argument)
            for argument in term.arguments
            if isinstance(argument, ShapeIndex)
        ]
        rendered = name
        if statics:
            rendered += f"[{', '.join(statics)}]"
        if shapes:
            rendered += f"({', '.join(shapes)})"
        return rendered
    if isinstance(term, FunctionType):
        parameter = render_static(term.parameter)
        if isinstance(term.parameter, FunctionType):
            parameter = f"({parameter})"
        rendered = f"{parameter} -> {render_static(term.result)}"
        if term.effects.entries or term.effects.tail is not None:
            rendered += " !{" + render_row_entries(term.effects) + "}"
        return rendered
    if isinstance(term, TypeRow):
        return render_row_fields(term, ", ")
    if isinstance(term, RecordType):
        return "{" + render_row_fields(term.row, ", ") + "}"
    if isinstance(term, VariantType):
        return "<" + render_row_fields(term.row, ", ") + ">"
    if isinstance(term, EqualityType):
        return f"{render_static(term.left)} ~ {render_static(term.right)}"
    raise TypeError(f"not a static term: {term!r}")

render_axis

render_axis(axis: AxisType) -> str

Render what a named axis ranges over, as a tensor type spells it.

PARAMETER DESCRIPTION
axis

A finite type or a finite index sort.

TYPE: AxisType

RETURNS DESCRIPTION
str

The sort's name, or the type's rendering; a product type renders with * between parenthesized components.

Source code in src/quivers/qiec/types.py
def render_axis(axis: AxisType) -> str:
    """Render what a named axis ranges over, as a tensor type spells it.

    Parameters
    ----------
    axis : AxisType
        A finite type or a finite index sort.

    Returns
    -------
    str
        The sort's name, or the type's rendering; a product type renders
        with ``*`` between parenthesized components.
    """
    if isinstance(axis, UserIndexSort):
        return axis.name
    if (
        isinstance(axis, TypeApplication)
        and axis.constructor.id
        == TypeId.derive("builtin", "Product", len(axis.arguments))
        and len(axis.arguments) >= 2
    ):
        return "(" + " * ".join(render_static(item) for item in axis.arguments) + ")"
    return render_static(axis)

render_row_entries

render_row_entries(row: EffectRow) -> str

Render an effect row's instances and tail without delimiters.

PARAMETER DESCRIPTION
row

The row to render.

TYPE: EffectRow

RETURNS DESCRIPTION
str

Each instance's stable identifier, then | tail for an open row.

Source code in src/quivers/qiec/types.py
def render_row_entries(row: EffectRow) -> str:
    """Render an effect row's instances and tail without delimiters.

    Parameters
    ----------
    row : EffectRow
        The row to render.

    Returns
    -------
    str
        Each instance's stable identifier, then ``| tail`` for an open row.
    """
    entries = ", ".join(str(entry.instance) for entry in row.entries)
    if row.tail is None:
        return entries
    return f"{entries} | {row.tail.name}" if entries else f"| {row.tail.name}"

render_row_fields

render_row_fields(row: TypeRow, separator: str) -> str

Render a row's entries and tail without delimiters.

PARAMETER DESCRIPTION
row

The row to render.

TYPE: TypeRow

separator

What separates two entries.

TYPE: str

RETURNS DESCRIPTION
str

label : type per entry in canonical order, then | tail for an open row; a Unit payload is written as the bare label.

Source code in src/quivers/qiec/types.py
def render_row_fields(row: TypeRow, separator: str) -> str:
    """Render a row's entries and tail without delimiters.

    Parameters
    ----------
    row : TypeRow
        The row to render.
    separator : str
        What separates two entries.

    Returns
    -------
    str
        ``label : type`` per entry in canonical order, then ``| tail`` for
        an open row; a ``Unit`` payload is written as the bare label.
    """
    entries = separator.join(
        field.label
        if field.type == UNIT
        else f"{field.label} : {render_static(field.type)}"
        for field in row.fields
    )
    if row.tail is None:
        return entries
    return f"{entries} | {row.tail.name}" if entries else f"| {row.tail.name}"

bind_effect_rows

bind_effect_rows(row_class: type[EffectRow]) -> None

Make the forward reference to the effect row resolvable.

The effect calculus imports this module, so the row a function type carries is named here by a forward reference, which :mod:quivers.qiec.effects resolves once it has defined the class.

PARAMETER DESCRIPTION
row_class

The effect-row record class.

TYPE: type[EffectRow]

Source code in src/quivers/qiec/types.py
def bind_effect_rows(row_class: type[EffectRow]) -> None:
    """Make the forward reference to the effect row resolvable.

    The effect calculus imports this module, so the row a function type
    carries is named here by a forward reference, which
    :mod:`quivers.qiec.effects` resolves once it has defined the class.

    Parameters
    ----------
    row_class : type[EffectRow]
        The effect-row record class.
    """
    globals()["EffectRow"] = row_class

index_arithmetic

Exact addition and cancellation for natural-number tensor extents.

The static language represents nonnegative affine expressions. These helpers never introduce subtraction whose result has no representable Nat proof.

solve_index_equation

solve_index_equation(left: IndexTerm, right: IndexTerm, unknown: IndexVariable) -> IndexTerm | None

Solve a Nat equality when cancellation leaves a nonnegative affine term.

PARAMETER DESCRIPTION
left

Natural-number terms equated by a checked shape relation.

TYPE: IndexTerm

right

Natural-number terms equated by a checked shape relation.

TYPE: IndexTerm

unknown

Nonrigid Nat variable to solve; every other variable remains symbolic.

TYPE: IndexVariable

RETURNS DESCRIPTION
IndexTerm or None

The exact solution, or None when it requires unproved subtraction, nonintegral coefficients, or does not determine this variable.

RAISES DESCRIPTION
TypeError

If an argument is not Nat, or the unknown is a rigid skolem.

Source code in src/quivers/qiec/index_arithmetic.py
def solve_index_equation(
    left: IndexTerm, right: IndexTerm, unknown: IndexVariable
) -> IndexTerm | None:
    """Solve a Nat equality when cancellation leaves a nonnegative affine term.

    Parameters
    ----------
    left, right : IndexTerm
        Natural-number terms equated by a checked shape relation.
    unknown : IndexVariable
        Nonrigid Nat variable to solve; every other variable remains symbolic.

    Returns
    -------
    IndexTerm or None
        The exact solution, or None when it requires unproved subtraction,
        nonintegral coefficients, or does not determine this variable.

    Raises
    ------
    TypeError
        If an argument is not Nat, or the unknown is a rigid skolem.
    """
    if unknown.sort != NAT or unknown.identity is not None:
        raise TypeError("only a nonrigid Nat variable may be solved")
    coefficients, constant = _coefficients(left)
    other, right_constant = _coefficients(right)
    coefficients.subtract(other)
    constant -= right_constant
    divisor = coefficients.pop(unknown, 0)
    if not divisor:
        return None
    numerator = -constant
    if numerator % divisor or numerator // divisor < 0:
        return None
    terms: list[IndexTerm] = [IndexLiteral(value=numerator // divisor, sort=NAT)]
    for variable, coefficient in coefficients.items():
        numerator = -coefficient
        if numerator % divisor or numerator // divisor < 0:
            return None
        terms.extend([variable] * (numerator // divisor))
    return add_indices(*terms)

infer_index_extents

infer_index_extents(equations: Sequence[tuple[IndexTerm, int]], given: Mapping[str, int] | None = None) -> dict[str, int]

Infer extents forced by exact affine shape equations.

PARAMETER DESCRIPTION
equations

A checked Nat dimension and the observed integer axis length.

TYPE: Sequence[tuple[IndexTerm, int]]

given

Previously fixed nonnegative integer extents.

TYPE: Mapping[str, int] or None DEFAULT: None

RETURNS DESCRIPTION
dict[str, int]

Supplied and uniquely determined extents. Underdetermined variables remain absent; no equal-size or free-variable heuristic is applied.

RAISES DESCRIPTION
TypeError

If evidence is not an integer, a term is not Nat, or a rigid variable is used as a named extent.

ValueError

If evidence is negative, equations disagree, or a forced solution is negative or nonintegral.

Source code in src/quivers/qiec/index_arithmetic.py
def infer_index_extents(
    equations: Sequence[tuple[IndexTerm, int]],
    given: Mapping[str, int] | None = None,
) -> dict[str, int]:
    """Infer extents forced by exact affine shape equations.

    Parameters
    ----------
    equations : Sequence[tuple[IndexTerm, int]]
        A checked Nat dimension and the observed integer axis length.
    given : Mapping[str, int] or None
        Previously fixed nonnegative integer extents.

    Returns
    -------
    dict[str, int]
        Supplied and uniquely determined extents. Underdetermined variables
        remain absent; no equal-size or free-variable heuristic is applied.

    Raises
    ------
    TypeError
        If evidence is not an integer, a term is not Nat, or a rigid variable
        is used as a named extent.
    ValueError
        If evidence is negative, equations disagree, or a forced solution is
        negative or nonintegral.
    """
    known = dict(given or {})
    for name, value in known.items():
        if isinstance(value, bool) or not isinstance(value, int):
            raise TypeError(f"extent {name!r} must be an integer")
        if value < 0:
            raise ValueError(f"extent {name!r} must be nonnegative")
    forms = []
    names: set[str] = set()
    for term, extent in equations:
        if isinstance(extent, bool) or not isinstance(extent, int):
            raise TypeError("observed shape extents must be integers")
        if extent < 0:
            raise ValueError("observed shape extents must be nonnegative")
        coefficients, constant = _coefficients(term)
        row = Counter()
        for variable, coefficient in coefficients.items():
            if variable.identity is not None:
                raise TypeError("a rigid index cannot be inferred by its display name")
            if variable.name in known:
                constant += coefficient * known[variable.name]
            else:
                row[variable.name] += coefficient
                names.add(variable.name)
        residual = extent - constant
        if residual < 0:
            raise ValueError(
                f"natural-number shape equation for {render_static(term)} has no nonnegative solution"
            )
        forms.append((row, residual))
        if residual == 0:
            # A sum of nonnegative terms can vanish only term by term.
            forms.extend((Counter({name: 1}), 0) for name in row)
    # Preserve the common one-variable path as linear-time integer checks.
    # Coupled rows then enter the same exact solver with these values fixed.
    for form, residual in forms:
        if len(form) != 1:
            continue
        name, coefficient = next(iter(form.items()))
        if residual % coefficient:
            raise ValueError(f"extent {name!r} has no nonnegative integer solution")
        value = residual // coefficient
        if name in known and known[name] != value:
            raise ValueError(f"inconsistent natural-number shape equations for {name}")
        known[name] = value
    columns = sorted(names - known.keys())
    forms = [
        (
            form,
            residual
            - sum(
                coefficient * known[name]
                for name, coefficient in form.items()
                if name in known
            ),
        )
        for form, residual in forms
    ]
    if not columns:
        if any(value for _, value in forms):
            raise ValueError(
                "inconsistent natural-number shape equations for closed dimensions"
            )
        return known
    rows = [
        [*(Fraction(form[name]) for name in columns), Fraction(value)]
        for form, value in forms
    ]
    pivots = []
    next_row = 0
    for column in range(len(columns)):
        pivot = next((i for i in range(next_row, len(rows)) if rows[i][column]), None)
        if pivot is None:
            continue
        rows[next_row], rows[pivot] = rows[pivot], rows[next_row]
        scale = rows[next_row][column]
        rows[next_row] = [value / scale for value in rows[next_row]]
        for i in range(len(rows)):
            if i != next_row and rows[i][column]:
                scale = rows[i][column]
                rows[i] = [
                    value - scale * basis
                    for value, basis in zip(rows[i], rows[next_row], strict=True)
                ]
        pivots.append((next_row, column))
        next_row += 1
    if any(not any(row[:-1]) and row[-1] for row in rows):
        raise ValueError(
            f"inconsistent natural-number shape equations for {', '.join(columns) or 'closed dimensions'}"
        )
    for row_index, column in pivots:
        row = rows[row_index]
        if any(value for j, value in enumerate(row[:-1]) if j != column):
            continue
        value = row[-1]
        if value.denominator != 1 or value < 0:
            raise ValueError(
                f"extent {columns[column]!r} has no nonnegative integer solution"
            )
        known[columns[column]] = int(value)
    return known