Skip to content

Substitution

Substitution replaces variables with terms without capture: a free name in the replacement must not be bound by an inner binder. Telescope instantiation applies the same rule to dependent parameters, where replacing one index can change the types of later arguments.

substitution

Capture-free substitution and telescope instantiation for QIEC.

StaticSubstitution didactic-model

StaticSubstitution(*, types: tuple[tuple[str, TypeExpr | TypeRow], ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), indices: tuple[tuple[str, IndexTerm], ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), effects: tuple[tuple[str, EffectRef | EffectVariable], ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), rigid: tuple[tuple[StaticVariableId, StaticArgument], ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), effect_rows: RowSubstitution = field(default=RowSubstitution(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A deterministic substitution split by static namespace.

PARAMETER DESCRIPTION
types

Bindings from type-variable names to types, and from row-variable names to rows.

TYPE: tuple[tuple[str, TypeExpr | TypeRow], ...] DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

indices

Bindings from index-variable names to index terms.

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

effects

Bindings from effect-variable names to interface applications or other effect variables.

TYPE: tuple[tuple[str, EffectRef | EffectVariable], ...] DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

rigid

Bindings by stable identity. The evaluator supplies these when a selected case branch reveals actual constructor arguments. Declaration instantiations leave this empty.

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

effect_rows

Bindings for the open tails of effect rows, which a call makes when a function argument's row instantiates the row of a function-typed parameter.

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

at_identity

at_identity(identity: StaticVariableId) -> StaticArgument | None

Look up the runtime argument of a rigid variable.

PARAMETER DESCRIPTION
identity

The stable identity bound by a checked case branch.

TYPE: StaticVariableId

RETURNS DESCRIPTION
StaticArgument or None

The selected static argument, if this substitution binds it.

Source code in src/quivers/qiec/substitution.py
def at_identity(self, identity: StaticVariableId) -> StaticArgument | None:
    """Look up the runtime argument of a rigid variable.

    Parameters
    ----------
    identity
        The stable identity bound by a checked case branch.

    Returns
    -------
    StaticArgument or None
        The selected static argument, if this substitution binds it.
    """
    return next((value for key, value in self.rigid if key == identity), None)

type

type(name: str) -> TypeExpr | TypeRow | None

What a type or row binder of this name is bound to.

PARAMETER DESCRIPTION
name

The binder name.

TYPE: str

RETURNS DESCRIPTION
TypeExpr or TypeRow or None

The bound type or row, or None when this substitution says nothing about the name, in which case the variable stands.

Source code in src/quivers/qiec/substitution.py
def type(self, name: str) -> TypeExpr | TypeRow | None:
    """What a type or row binder of this name is bound to.

    Parameters
    ----------
    name : str
        The binder name.

    Returns
    -------
    TypeExpr or TypeRow or None
        The bound type or row, or None when this substitution says
        nothing about the name, in which case the variable stands.
    """
    return next((value for key, value in self.types if key == name), None)

index

index(name: str) -> IndexTerm | None

What an index binder of this name is bound to.

PARAMETER DESCRIPTION
name

The binder name.

TYPE: str

RETURNS DESCRIPTION
IndexTerm or None

The bound index, or None when the name is unbound here.

Source code in src/quivers/qiec/substitution.py
def index(self, name: str) -> IndexTerm | None:
    """What an index binder of this name is bound to.

    Parameters
    ----------
    name : str
        The binder name.

    Returns
    -------
    IndexTerm or None
        The bound index, or None when the name is unbound here.
    """
    return next((value for key, value in self.indices if key == name), None)

effect

effect(name: str) -> EffectRef | EffectVariable | None

What an effect binder of this name is bound to.

PARAMETER DESCRIPTION
name

The binder name.

TYPE: str

RETURNS DESCRIPTION
EffectRef or EffectVariable or None

The bound interface application or effect variable, or None when the name is unbound here.

Source code in src/quivers/qiec/substitution.py
def effect(self, name: str) -> EffectRef | EffectVariable | None:
    """What an effect binder of this name is bound to.

    Parameters
    ----------
    name : str
        The binder name.

    Returns
    -------
    EffectRef or EffectVariable or None
        The bound interface application or effect variable, or None
        when the name is unbound here.
    """
    return next((value for key, value in self.effects if key == name), None)

instantiate_telescope

instantiate_telescope(telescope: Telescope, arguments: tuple[StaticArgument, ...]) -> StaticSubstitution

Kind-check static arguments and construct their substitution.

PARAMETER DESCRIPTION
telescope

The binders to instantiate, in order. Later binders may depend on earlier ones, so the arguments are checked left to right with the substitution built so far already applied.

TYPE: Telescope

arguments

One argument per binder.

TYPE: tuple[StaticArgument, ...]

RETURNS DESCRIPTION
StaticSubstitution

The substitution carrying each binder to its argument.

RAISES DESCRIPTION
TypeError

If an argument is of the wrong static class for its binder.

ValueError

If the counts differ, or an argument is of the wrong kind or index sort.

Source code in src/quivers/qiec/substitution.py
def instantiate_telescope(
    telescope: Telescope,
    arguments: tuple[StaticArgument, ...],
) -> StaticSubstitution:
    """Kind-check static arguments and construct their substitution.

    Parameters
    ----------
    telescope : Telescope
        The binders to instantiate, in order. Later binders may depend on
        earlier ones, so the arguments are checked left to right with the
        substitution built so far already applied.
    arguments : tuple[StaticArgument, ...]
        One argument per binder.

    Returns
    -------
    StaticSubstitution
        The substitution carrying each binder to its argument.

    Raises
    ------
    TypeError
        If an argument is of the wrong static class for its binder.
    ValueError
        If the counts differ, or an argument is of the wrong kind or
        index sort.
    """
    types, indices, effects = check_static_arguments(telescope, arguments)
    return StaticSubstitution(types=types, indices=indices, effects=effects)

substitute_index

substitute_index(term: IndexTerm, substitution: StaticSubstitution) -> IndexTerm

Substitute into an index term.

PARAMETER DESCRIPTION
term

The index to rewrite.

TYPE: IndexTerm

substitution

The bindings to apply.

TYPE: StaticSubstitution

RETURNS DESCRIPTION
IndexTerm

The rewritten index. A branch variable can only be substituted by its rigid identity, independently of its displayed name.

Source code in src/quivers/qiec/substitution.py
def substitute_index(term: IndexTerm, substitution: StaticSubstitution) -> IndexTerm:
    """Substitute into an index term.

    Parameters
    ----------
    term : IndexTerm
        The index to rewrite.
    substitution : StaticSubstitution
        The bindings to apply.

    Returns
    -------
    IndexTerm
        The rewritten index. A branch variable can only be substituted
        by its rigid identity, independently of its displayed name.
    """
    if isinstance(term, IndexVariable):
        if term.identity is None:
            return substitution.index(term.name) or term
        return cast(IndexTerm | None, substitution.at_identity(term.identity)) or term
    if isinstance(term, IndexSum):
        from quivers.qiec.kinds import NAT
        from quivers.qiec.types import IndexLiteral

        return add_indices(
            *(substitute_index(argument, substitution) for argument in term.terms),
            IndexLiteral(value=term.constant, sort=NAT),
        )
    if isinstance(term, IndexConstructor):
        return IndexConstructor(
            name=term.name,
            arguments=tuple(
                substitute_index(arg, substitution) for arg in term.arguments
            ),
            sort=term.sort,
        )
    if isinstance(term, ShapeIndex):
        return ShapeIndex(
            dimensions=tuple(
                substitute_index(dimension, substitution)
                for dimension in term.dimensions
            )
        )
    return term

substitute_effect

substitute_effect(effect: EffectRef, substitution: StaticSubstitution) -> EffectRef

Substitute into an interface application's static arguments.

PARAMETER DESCRIPTION
effect

The application to rewrite.

TYPE: EffectRef

substitution

The bindings to apply.

TYPE: StaticSubstitution

RETURNS DESCRIPTION
EffectRef

The application with its arguments rewritten. The declaration's identity and name are unchanged, since substitution instantiates an interface rather than selecting a different one.

Source code in src/quivers/qiec/substitution.py
def substitute_effect(effect: EffectRef, substitution: StaticSubstitution) -> EffectRef:
    """Substitute into an interface application's static arguments.

    Parameters
    ----------
    effect : EffectRef
        The application to rewrite.
    substitution : StaticSubstitution
        The bindings to apply.

    Returns
    -------
    EffectRef
        The application with its arguments rewritten. The declaration's
        identity and name are unchanged, since substitution instantiates
        an interface rather than selecting a different one.
    """
    return EffectRef(
        id=effect.id,
        name=effect.name,
        arguments=tuple(
            substitute_static(arg, substitution) for arg in effect.arguments
        ),
    )

substitute_plate

substitute_plate(plate: PlateShape, substitution: StaticSubstitution) -> PlateShape

Substitute static variables in a plate's axis sizes.

PARAMETER DESCRIPTION
plate

The plate.

TYPE: PlateShape

substitution

The static substitution.

TYPE: StaticSubstitution

RETURNS DESCRIPTION
PlateShape

The plate with every axis size substituted.

Source code in src/quivers/qiec/substitution.py
def substitute_plate(plate: PlateShape, substitution: StaticSubstitution) -> PlateShape:
    """Substitute static variables in a plate's axis sizes.

    Parameters
    ----------
    plate : PlateShape
        The plate.
    substitution : StaticSubstitution
        The static substitution.

    Returns
    -------
    PlateShape
        The plate with every axis size substituted.
    """
    return PlateShape(
        batch=tuple(
            PlateAxis(name=axis.name, size=substitute_index(axis.size, substitution))
            for axis in plate.batch
        ),
        event=tuple(
            PlateAxis(name=axis.name, size=substitute_index(axis.size, substitution))
            for axis in plate.event
        ),
    )

substitute_type

substitute_type(type_: TypeExpr, substitution: StaticSubstitution) -> TypeExpr

Substitute into a type expression.

PARAMETER DESCRIPTION
type_

The type to rewrite.

TYPE: TypeExpr

substitution

The bindings to apply.

TYPE: StaticSubstitution

RETURNS DESCRIPTION
TypeExpr

The rewritten type. Only an identity binding can replace a rigid type variable.

RAISES DESCRIPTION
TypeError

If the expression is of an unknown class.

Source code in src/quivers/qiec/substitution.py
def substitute_type(type_: TypeExpr, substitution: StaticSubstitution) -> TypeExpr:
    """Substitute into a type expression.

    Parameters
    ----------
    type_ : TypeExpr
        The type to rewrite.
    substitution : StaticSubstitution
        The bindings to apply.

    Returns
    -------
    TypeExpr
        The rewritten type. Only an identity binding can replace a rigid
        type variable.

    Raises
    ------
    TypeError
        If the expression is of an unknown class.
    """
    if isinstance(type_, TypeVariable) and type_.identity is None:
        bound = substitution.type(type_.name)
        if isinstance(bound, TypeRow):
            raise TypeError(f"row variable {type_.name!r} stands where a type is")
        return bound or type_
    if isinstance(type_, TypeVariable):
        return cast(TypeExpr | None, substitution.at_identity(type_.identity)) or type_
    if isinstance(type_, TypeApplication):
        return TypeApplication(
            constructor=type_.constructor,
            arguments=tuple(
                substitute_static(arg, substitution) for arg in type_.arguments
            ),
        )
    if isinstance(type_, FunctionType):
        return FunctionType(
            parameter=substitute_type(type_.parameter, substitution),
            result=substitute_type(type_.result, substitution),
            effects=substitute_row(type_.effects, substitution),
        )
    if isinstance(type_, RecordType):
        return RecordType(row=substitute_type_row(type_.row, substitution))
    if isinstance(type_, VariantType):
        return VariantType(row=substitute_type_row(type_.row, substitution))
    if isinstance(type_, EqualityType):
        return EqualityType(
            kind=type_.kind,
            left=substitute_static(type_.left, substitution),
            right=substitute_static(type_.right, substitution),
        )
    raise TypeError(f"unknown type term {type_!r}")

substitute_type_row

substitute_type_row(row: TypeRow, substitution: StaticSubstitution) -> TypeRow

Substitute into a row's types and instantiate its tail.

PARAMETER DESCRIPTION
row

The row to rewrite.

TYPE: TypeRow

substitution

The bindings to apply. A binding for the tail's name replaces the tail by the entries and tail of the row it is bound to.

TYPE: StaticSubstitution

RETURNS DESCRIPTION
TypeRow

The rewritten row.

RAISES DESCRIPTION
TypeError

If the tail is bound to something other than a row.

ValueError

If the tail's instantiation repeats a label the row names, which the row's well-formedness says its tail lacks.

Source code in src/quivers/qiec/substitution.py
def substitute_type_row(row: TypeRow, substitution: StaticSubstitution) -> TypeRow:
    """Substitute into a row's types and instantiate its tail.

    Parameters
    ----------
    row : TypeRow
        The row to rewrite.
    substitution : StaticSubstitution
        The bindings to apply. A binding for the tail's name replaces the
        tail by the entries and tail of the row it is bound to.

    Returns
    -------
    TypeRow
        The rewritten row.

    Raises
    ------
    TypeError
        If the tail is bound to something other than a row.
    ValueError
        If the tail's instantiation repeats a label the row names, which
        the row's well-formedness says its tail lacks.
    """
    fields = tuple(
        RowField(label=field.label, type=substitute_type(field.type, substitution))
        for field in row.fields
    )
    tail = row.tail
    if tail is None:
        return TypeRow(fields=fields)
    bound = (
        substitution.type(tail.name)
        if tail.identity is None
        else substitution.at_identity(tail.identity)
    )
    if bound is None:
        return TypeRow(fields=fields, tail=tail)
    if isinstance(bound, TypeVariable):
        return TypeRow(fields=fields, tail=bound)
    if not isinstance(bound, TypeRow):
        raise TypeError(f"row variable {tail.name!r} is bound to a non-row")
    return TypeRow(fields=(*fields, *bound.fields), tail=bound.tail)

substitute_predicate

substitute_predicate(predicate: RowPredicate, substitution: StaticSubstitution) -> RowPredicate

Substitute into the rows a row predicate relates.

PARAMETER DESCRIPTION
predicate

The predicate.

TYPE: RowPredicate

substitution

The bindings to apply.

TYPE: StaticSubstitution

RETURNS DESCRIPTION
RowPredicate

The predicate over the substituted rows.

Source code in src/quivers/qiec/substitution.py
def substitute_predicate(
    predicate: RowPredicate, substitution: StaticSubstitution
) -> RowPredicate:
    """Substitute into the rows a row predicate relates.

    Parameters
    ----------
    predicate : RowPredicate
        The predicate.
    substitution : StaticSubstitution
        The bindings to apply.

    Returns
    -------
    RowPredicate
        The predicate over the substituted rows.
    """
    if isinstance(predicate, RowContainment):
        return RowContainment(
            smaller=substitute_type_row(predicate.smaller, substitution),
            larger=substitute_type_row(predicate.larger, substitution),
        )
    return RowCombination(
        left=substitute_type_row(predicate.left, substitution),
        right=substitute_type_row(predicate.right, substitution),
        result=substitute_type_row(predicate.result, substitution),
    )

match_function_rows

match_function_rows(expected: tuple[TypeExpr, ...], actual: tuple[TypeExpr, ...]) -> RowSubstitution

The effect-row instantiation function arguments make at a call.

A parameter of type A -> B !{e | r} given a function whose row is {e, s} instantiates r to {s}, so a higher-order computation performs the row of the function it is given.

PARAMETER DESCRIPTION
expected

The callee's parameter types, at the call's static arguments.

TYPE: tuple[TypeExpr, ...]

actual

The arguments' types.

TYPE: tuple[TypeExpr, ...]

RETURNS DESCRIPTION
RowSubstitution

A binding for each open tail of a function-typed parameter whose argument determines it; empty when there is none.

Source code in src/quivers/qiec/substitution.py
def match_function_rows(
    expected: tuple[TypeExpr, ...], actual: tuple[TypeExpr, ...]
) -> RowSubstitution:
    """The effect-row instantiation function arguments make at a call.

    A parameter of type ``A -> B !{e | r}`` given a function whose row
    is ``{e, s}`` instantiates ``r`` to ``{s}``, so a higher-order
    computation performs the row of the function it is given.

    Parameters
    ----------
    expected : tuple[TypeExpr, ...]
        The callee's parameter types, at the call's static arguments.
    actual : tuple[TypeExpr, ...]
        The arguments' types.

    Returns
    -------
    RowSubstitution
        A binding for each open tail of a function-typed parameter whose
        argument determines it; empty when there is none.
    """
    bindings: dict[RowVariableId, EffectRow] = {}
    for parameter, argument in zip(expected, actual, strict=True):
        _match_rows_in(parameter, argument, bindings)
    return RowSubstitution(bindings=tuple(bindings.items()))

substitute_static

substitute_static(term: StaticArgument, substitution: StaticSubstitution) -> StaticArgument

Substitute into a static argument of any namespace.

PARAMETER DESCRIPTION
term

A type, index, or effect argument.

TYPE: StaticArgument

substitution

The bindings to apply.

TYPE: StaticSubstitution

RETURNS DESCRIPTION
StaticArgument

The rewritten argument, dispatched to the namespace it belongs to.

RAISES DESCRIPTION
TypeError

If the term is of an unknown class.

Source code in src/quivers/qiec/substitution.py
def substitute_static(
    term: StaticArgument,
    substitution: StaticSubstitution,
) -> StaticArgument:
    """Substitute into a static argument of any namespace.

    Parameters
    ----------
    term : StaticArgument
        A type, index, or effect argument.
    substitution : StaticSubstitution
        The bindings to apply.

    Returns
    -------
    StaticArgument
        The rewritten argument, dispatched to the namespace it belongs
        to.

    Raises
    ------
    TypeError
        If the term is of an unknown class.
    """
    if isinstance(term, EffectVariable) and term.identity is None:
        return substitution.effect(term.name) or term
    if isinstance(term, EffectVariable):
        return substitution.at_identity(term.identity) or term
    if isinstance(term, EffectRef):
        return substitute_effect(term, substitution)
    if isinstance(term, TypeRow):
        return substitute_type_row(term, substitution)
    if isinstance(term, (IndexVariable, IndexConstructor, ShapeIndex)) or hasattr(
        term, "sort"
    ):
        return substitute_index(term, substitution)  # type: ignore[arg-type]
    return substitute_type(term, substitution)  # type: ignore[arg-type]

substitute_row

substitute_row(row: EffectRow, substitution: StaticSubstitution) -> EffectRow

Substitute into every interface application in an effect row.

PARAMETER DESCRIPTION
row

The row to rewrite.

TYPE: EffectRow

substitution

The bindings to apply.

TYPE: StaticSubstitution

RETURNS DESCRIPTION
EffectRow

The row with each entry's interface rewritten and, when the substitution binds the open tail in its effect rows, the tail resolved. Instance identities are untouched.

Source code in src/quivers/qiec/substitution.py
def substitute_row(row: EffectRow, substitution: StaticSubstitution) -> EffectRow:
    """Substitute into every interface application in an effect row.

    Parameters
    ----------
    row : EffectRow
        The row to rewrite.
    substitution : StaticSubstitution
        The bindings to apply.

    Returns
    -------
    EffectRow
        The row with each entry's interface rewritten and, when the
        substitution binds the open tail in its effect rows, the tail
        resolved. Instance identities are untouched.
    """
    rewritten = EffectRow(
        entries=tuple(
            RowEntry(
                instance=entry.instance,
                effect=substitute_effect(entry.effect, substitution),
            )
            for entry in row.entries
        ),
        tail=row.tail,
    )
    if not substitution.effect_rows.bindings:
        return rewritten
    return substitution.effect_rows.apply(rewritten)

instantiate_operation

instantiate_operation(operation: OperationDef, arguments: tuple[StaticArgument, ...], outer: StaticSubstitution = StaticSubstitution()) -> tuple[tuple[TypeExpr, ...], TypeExpr]

Instantiate an operation's signature at a request site.

PARAMETER DESCRIPTION
operation

The declared operation.

TYPE: OperationDef

arguments

Static arguments for the operation's own telescope.

TYPE: tuple[StaticArgument, ...]

outer

Bindings already in force from the interface's telescope. These come first, so an operation binder of the same name shadows the interface's, which is the scoping a reader expects.

TYPE: StaticSubstitution DEFAULT: StaticSubstitution()

RETURNS DESCRIPTION
tuple[tuple[TypeExpr, ...], TypeExpr]

The instantiated parameter types and result type.

RAISES DESCRIPTION
TypeError

If an argument is of the wrong static class for its binder.

ValueError

If the argument count is wrong, or an argument is ill-kinded.

Source code in src/quivers/qiec/substitution.py
def instantiate_operation(
    operation: OperationDef,
    arguments: tuple[StaticArgument, ...],
    outer: StaticSubstitution = StaticSubstitution(),
) -> tuple[tuple[TypeExpr, ...], TypeExpr]:
    """Instantiate an operation's signature at a request site.

    Parameters
    ----------
    operation : OperationDef
        The declared operation.
    arguments : tuple[StaticArgument, ...]
        Static arguments for the operation's own telescope.
    outer : StaticSubstitution
        Bindings already in force from the interface's telescope. These
        come first, so an operation binder of the same name shadows the
        interface's, which is the scoping a reader expects.

    Returns
    -------
    tuple[tuple[TypeExpr, ...], TypeExpr]
        The instantiated parameter types and result type.

    Raises
    ------
    TypeError
        If an argument is of the wrong static class for its binder.
    ValueError
        If the argument count is wrong, or an argument is ill-kinded.
    """
    local = instantiate_telescope(operation.telescope, arguments)
    substitution = StaticSubstitution(
        types=(*outer.types, *local.types),
        indices=(*outer.indices, *local.indices),
        effects=(*outer.effects, *local.effects),
    )
    parameter_types = tuple(
        substitute_type(argument.type, substitution) for argument in operation.arguments
    )
    return parameter_types, substitute_type(operation.result_type, substitution)

substitute_evidence

substitute_evidence(evidence: EqualityEvidence, substitution: StaticSubstitution) -> EqualityEvidence

Substitute into the equality an evidence term states.

PARAMETER DESCRIPTION
evidence

The evidence to rewrite.

TYPE: EqualityEvidence

substitution

The static bindings to apply.

TYPE: StaticSubstitution

RETURNS DESCRIPTION
EqualityEvidence

Evidence of the same class stating the substituted equality. A branch given keeps its identity, since substituting into what it proves does not make it a different piece of evidence.

RAISES DESCRIPTION
TypeError

If the evidence is of an unknown class.

Source code in src/quivers/qiec/substitution.py
def substitute_evidence(
    evidence: EqualityEvidence,
    substitution: StaticSubstitution,
) -> EqualityEvidence:
    """Substitute into the equality an evidence term states.

    Parameters
    ----------
    evidence : EqualityEvidence
        The evidence to rewrite.
    substitution : StaticSubstitution
        The static bindings to apply.

    Returns
    -------
    EqualityEvidence
        Evidence of the same class stating the substituted equality. A
        branch given keeps its identity, since substituting into what it
        proves does not make it a different piece of evidence.

    Raises
    ------
    TypeError
        If the evidence is of an unknown class.
    """
    equality = EqualityType(
        kind=evidence.equality.kind,
        left=substitute_static(evidence.equality.left, substitution),
        right=substitute_static(evidence.equality.right, substitution),
    )
    if isinstance(evidence, Reflexivity):
        return Reflexivity(equality=equality)
    if isinstance(evidence, BranchGiven):
        return BranchGiven(id=evidence.id, equality=equality)
    raise TypeError(f"unknown equality evidence {evidence!r}")

substitute_value

substitute_value(value: Value, substitution: StaticSubstitution) -> Value

Substitute static arguments throughout a value term.

PARAMETER DESCRIPTION
value

The value to rewrite.

TYPE: Value

substitution

The static bindings to apply.

TYPE: StaticSubstitution

RETURNS DESCRIPTION
Value

The value with every type, index, and effect position substituted. Value-level structure is untouched: this rewrites the static layer, not the data.

RAISES DESCRIPTION
TypeError

If the value is of an unknown class.

Source code in src/quivers/qiec/substitution.py
def substitute_value(value: Value, substitution: StaticSubstitution) -> Value:
    """Substitute static arguments throughout a value term.

    Parameters
    ----------
    value : Value
        The value to rewrite.
    substitution : StaticSubstitution
        The static bindings to apply.

    Returns
    -------
    Value
        The value with every type, index, and effect position
        substituted. Value-level structure is untouched: this rewrites
        the static layer, not the data.

    Raises
    ------
    TypeError
        If the value is of an unknown class.
    """
    if isinstance(value, Var):
        return Var(
            local=Local(
                name=value.local.name,
                type=substitute_type(value.local.type, substitution),
            )
        )
    if isinstance(value, LiteralValue):
        return LiteralValue(
            value=value.value, type=substitute_type(value.type, substitution)
        )
    if isinstance(value, ConstructorValue):
        return ConstructorValue(
            constructor=value.constructor,
            static_arguments=tuple(
                substitute_static(argument, substitution)
                for argument in value.static_arguments
            ),
            fields=tuple(
                substitute_value(field, substitution) for field in value.fields
            ),
            result_type=substitute_type(value.result_type, substitution),
        )
    if isinstance(value, EvidenceValue):
        return EvidenceValue(evidence=substitute_evidence(value.evidence, substitution))
    if isinstance(value, AttachmentRef):
        return AttachmentRef(
            attachment=value.attachment, type=substitute_type(value.type, substitution)
        )
    if isinstance(value, TransportValue):
        return TransportValue(
            evidence=substitute_evidence(value.evidence, substitution),
            value=substitute_value(value.value, substitution),
            target_type=substitute_type(value.target_type, substitution),
        )
    if isinstance(value, PrimitiveApplication):
        return PrimitiveApplication(
            primitive=value.primitive,
            name=value.name,
            arguments=tuple(
                substitute_value(item, substitution) for item in value.arguments
            ),
            result_type=substitute_type(value.result_type, substitution),
            origin=value.origin,
        )
    if isinstance(value, TupleValue):
        return TupleValue(
            items=tuple(substitute_value(item, substitution) for item in value.items),
            result_type=substitute_type(value.result_type, substitution),
        )
    if isinstance(value, TensorValue):
        return TensorValue(
            items=tuple(substitute_value(item, substitution) for item in value.items),
            result_type=substitute_type(value.result_type, substitution),
        )
    if isinstance(value, Projection):
        return Projection(
            value=substitute_value(value.value, substitution),
            position=value.position,
            result_type=substitute_type(value.result_type, substitution),
        )
    if isinstance(value, DistributionValue):
        return DistributionValue(
            family=value.family,
            name=value.name,
            arguments=tuple(
                (name, substitute_value(argument, substitution))
                for name, argument in value.arguments
            ),
            result_type=substitute_type(value.result_type, substitution),
            origin=value.origin,
            plate=substitute_plate(value.plate, substitution),
        )
    if isinstance(value, Gather):
        return Gather(
            value=substitute_value(value.value, substitution),
            index=substitute_value(value.index, substitution),
            result_type=substitute_type(value.result_type, substitution),
        )
    if isinstance(value, WeightSum):
        return WeightSum(value=substitute_value(value.value, substitution))
    if isinstance(value, SegmentSum):
        return SegmentSum(
            value=substitute_value(value.value, substitution),
            index=substitute_value(value.index, substitution),
            groups=substitute_index(value.groups, substitution),
            result_type=substitute_type(value.result_type, substitution),
        )
    if isinstance(value, KernelMatrix):
        return KernelMatrix(
            inputs=substitute_value(value.inputs, substitution),
            kernel=value.kernel,
            length_scale=value.length_scale,
            jitter=value.jitter,
            result_type=substitute_type(value.result_type, substitution),
        )
    if isinstance(value, AffineMap):
        return AffineMap(
            weight=substitute_value(value.weight, substitution),
            bias=substitute_value(value.bias, substitution),
            sources=tuple(
                substitute_value(item, substitution) for item in value.sources
            ),
            row_offset=value.row_offset,
            rows=value.rows,
            transform=value.transform,
            result_type=substitute_type(value.result_type, substitution),
        )
    if isinstance(value, TableMap):
        return TableMap(
            table=substitute_value(value.table, substitution),
            index=substitute_value(value.index, substitution),
            row_offset=value.row_offset,
            rows=value.rows,
            transform=value.transform,
            result_type=substitute_type(value.result_type, substitution),
        )
    if isinstance(value, DirectedTreeLogPartition):
        return DirectedTreeLogPartition(
            scores=substitute_value(value.scores, substitution),
            root=substitute_value(value.root, substitution),
            mask=substitute_value(value.mask, substitution),
            origin=value.origin,
        )
    if isinstance(value, DppLogProb):
        return DppLogProb(
            features=substitute_value(value.features, substitution),
            membership=substitute_value(value.membership, substitution),
            origin=value.origin,
        )
    if isinstance(value, Reduction):
        return Reduction(
            operator=value.operator,
            value=substitute_value(value.value, substitution),
            result_type=substitute_type(value.result_type, substitution),
        )
    if isinstance(value, Rowwise):
        return Rowwise(
            operator=value.operator,
            value=substitute_value(value.value, substitution),
            result_type=substitute_type(value.result_type, substitution),
        )
    if isinstance(value, CholeskyFactor):
        return CholeskyFactor(
            value=substitute_value(value.value, substitution),
            result_type=substitute_type(value.result_type, substitution),
        )
    if isinstance(value, Comprehension):
        return Comprehension(
            binder=Local(
                name=value.binder.name,
                type=substitute_type(value.binder.type, substitution),
            ),
            extent=substitute_index(value.extent, substitution),
            body=substitute_value(value.body, substitution),
            result_type=substitute_type(value.result_type, substitution),
        )
    if isinstance(value, LetValue):
        return LetValue(
            bindings=tuple(
                LetBinding(
                    binder=Local(
                        name=binding.binder.name,
                        type=substitute_type(binding.binder.type, substitution),
                    ),
                    value=substitute_value(binding.value, substitution),
                )
                for binding in value.bindings
            ),
            body=substitute_value(value.body, substitution),
            result_type=substitute_type(value.result_type, substitution),
        )
    if isinstance(value, ConditionalValue):
        return ConditionalValue(
            condition=substitute_value(value.condition, substitution),
            then=substitute_value(value.then, substitution),
            otherwise=substitute_value(value.otherwise, substitution),
            result_type=substitute_type(value.result_type, substitution),
        )
    if isinstance(value, LogMass):
        return LogMass(
            sampleable=substitute_value(value.sampleable, substitution),
            origin=value.origin,
            batch=tuple(
                PlateAxis(
                    name=axis.name, size=substitute_index(axis.size, substitution)
                )
                for axis in value.batch
            ),
        )
    if isinstance(value, LogDensity):
        return LogDensity(
            sampleable=substitute_value(value.sampleable, substitution),
            value=substitute_value(value.value, substitution),
            origin=value.origin,
            batch=tuple(
                PlateAxis(
                    name=axis.name, size=substitute_index(axis.size, substitution)
                )
                for axis in value.batch
            ),
        )
    if isinstance(value, ParameterName):
        return value
    if isinstance(value, SiteValue):
        return SiteValue(
            label=value.label,
            result_type=substitute_type(value.result_type, substitution),
        )
    if isinstance(value, RecordValue):
        return RecordValue(
            fields=tuple(
                RecordFieldValue(
                    label=field.label, value=substitute_value(field.value, substitution)
                )
                for field in value.fields
            ),
            result_type=substitute_type(value.result_type, substitution),
        )
    if isinstance(value, FieldProjection):
        return FieldProjection(
            record=substitute_value(value.record, substitution),
            label=value.label,
            result_type=substitute_type(value.result_type, substitution),
        )
    if isinstance(value, RecordRestriction):
        return RecordRestriction(
            record=substitute_value(value.record, substitution),
            result_type=substitute_type(value.result_type, substitution),
        )
    if isinstance(value, RecordConcat):
        return RecordConcat(
            left=substitute_value(value.left, substitution),
            right=substitute_value(value.right, substitution),
            result_type=substitute_type(value.result_type, substitution),
        )
    if isinstance(value, VariantInjection):
        return VariantInjection(
            label=value.label,
            payload=substitute_value(value.payload, substitution),
            result_type=substitute_type(value.result_type, substitution),
        )
    if isinstance(value, VariantEmbed):
        return VariantEmbed(
            variant=substitute_value(value.variant, substitution),
            result_type=substitute_type(value.result_type, substitution),
        )
    if isinstance(value, Lambda):
        return substitute_lambda(value, substitution)
    if isinstance(value, HoleValue):
        return value.with_(type=substitute_type(value.type, substitution))
    raise TypeError(f"unknown value term {value!r}")

substitute_local

substitute_local(local: Local, substitution: StaticSubstitution) -> Local

Substitute into a local's type.

PARAMETER DESCRIPTION
local

The binder.

TYPE: Local

substitution

The static bindings to apply.

TYPE: StaticSubstitution

RETURNS DESCRIPTION
Local

The binder at its substituted type.

Source code in src/quivers/qiec/substitution.py
def substitute_local(local: Local, substitution: StaticSubstitution) -> Local:
    """Substitute into a local's type.

    Parameters
    ----------
    local : Local
        The binder.
    substitution : StaticSubstitution
        The static bindings to apply.

    Returns
    -------
    Local
        The binder at its substituted type.
    """
    return Local(name=local.name, type=substitute_type(local.type, substitution))

substitute_lambda

substitute_lambda(function: Lambda, substitution: StaticSubstitution) -> Lambda

Substitute static arguments throughout a function value.

PARAMETER DESCRIPTION
function

The function.

TYPE: Lambda

substitution

The static bindings to apply.

TYPE: StaticSubstitution

RETURNS DESCRIPTION
Lambda

The function with its parameter, body, and type substituted; its code identity and origin are unchanged.

Source code in src/quivers/qiec/substitution.py
def substitute_lambda(function: Lambda, substitution: StaticSubstitution) -> Lambda:
    """Substitute static arguments throughout a function value.

    Parameters
    ----------
    function : Lambda
        The function.
    substitution : StaticSubstitution
        The static bindings to apply.

    Returns
    -------
    Lambda
        The function with its parameter, body, and type substituted; its
        code identity and origin are unchanged.
    """
    return Lambda(
        code=function.code,
        name=function.name,
        parameter=substitute_local(function.parameter, substitution),
        body=substitute_computation(function.body, substitution),
        result_type=substitute_type(function.result_type, substitution),
        origin=function.origin,
    )

substitute_request

substitute_request(request: EffectRequest, substitution: StaticSubstitution) -> EffectRequest

Substitute static arguments throughout an effect request.

PARAMETER DESCRIPTION
request

The request to rewrite.

TYPE: EffectRequest

substitution

The static bindings to apply.

TYPE: StaticSubstitution

RETURNS DESCRIPTION
EffectRequest

The request against the substituted interface application, with its own static and value arguments and result type rewritten. The instance, the operation, and the site are identities and do not move.

Source code in src/quivers/qiec/substitution.py
def substitute_request(
    request: EffectRequest,
    substitution: StaticSubstitution,
) -> EffectRequest:
    """Substitute static arguments throughout an effect request.

    Parameters
    ----------
    request : EffectRequest
        The request to rewrite.
    substitution : StaticSubstitution
        The static bindings to apply.

    Returns
    -------
    EffectRequest
        The request against the substituted interface application, with
        its own static and value arguments and result type rewritten. The
        instance, the operation, and the site are identities and do not
        move.
    """
    return EffectRequest(
        instance=request.instance,
        effect=substitute_effect(request.effect, substitution),
        operation=request.operation,
        static_arguments=tuple(
            substitute_static(argument, substitution)
            for argument in request.static_arguments
        ),
        arguments=tuple(
            substitute_value(argument, substitution) for argument in request.arguments
        ),
        result_type=substitute_type(request.result_type, substitution),
        origin=request.origin,
    )

substitute_computation

substitute_computation(computation: Computation, substitution: StaticSubstitution) -> Computation

Substitute static arguments throughout a computation.

Declaration parameters are replaced by name. Constructor skolems carry derived StaticVariableIds, so substituting for a declaration binder cannot capture a branch variable with the same name. The evaluator can additionally replace the selected branch's skolems by identity. That substitution leaves other branches' binders and the named binders of case motives in scope.

PARAMETER DESCRIPTION
computation

The computation to rewrite.

TYPE: Computation

substitution

The static bindings to apply.

TYPE: StaticSubstitution

RETURNS DESCRIPTION
Computation

The computation with every static position substituted. Identities are preserved throughout: a call still names the same callee, a handle the same handler, and an allocation the same instance. An empty substitution returns the immutable graph itself.

RAISES DESCRIPTION
TypeError

If the computation, or a term nested in it, is of an unknown class.

Source code in src/quivers/qiec/substitution.py
def substitute_computation(
    computation: Computation,
    substitution: StaticSubstitution,
) -> Computation:
    """Substitute static arguments throughout a computation.

    Declaration parameters are replaced by name. Constructor skolems
    carry derived `StaticVariableId`s, so substituting for a declaration
    binder cannot capture a branch variable with the same name. The
    evaluator can additionally replace the selected branch's skolems by
    identity. That substitution leaves other branches' binders and the
    named binders of case motives in scope.

    Parameters
    ----------
    computation : Computation
        The computation to rewrite.
    substitution : StaticSubstitution
        The static bindings to apply.

    Returns
    -------
    Computation
        The computation with every static position substituted.
        Identities are preserved throughout: a call still names the same
        callee, a handle the same handler, and an allocation the same
        instance. An empty substitution returns the immutable graph itself.

    Raises
    ------
    TypeError
        If the computation, or a term nested in it, is of an unknown
        class.
    """
    if (
        isinstance(
            computation,
            Return
            | Bind
            | Perform
            | Handle
            | Case
            | Call
            | ApplyPure
            | CallAddress
            | HandlerReturnAddress
            | InstanceAddress
            | WithTraceAddresses
            | Resume
            | NewInstance
            | If
            | Apply
            | VariantCase
            | VariantSplit
            | LetRec
            | Mask,
        )
        and not substitution.types
        and not substitution.indices
        and not substitution.effects
        and not substitution.rigid
        and not substitution.effect_rows.bindings
    ):
        return computation
    if isinstance(computation, Return):
        return Return(value=substitute_value(computation.value, substitution))
    if isinstance(computation, Bind):
        return Bind(
            binder=Local(
                name=computation.binder.name,
                type=substitute_type(computation.binder.type, substitution),
            ),
            first=substitute_computation(computation.first, substitution),
            then=substitute_computation(computation.then, substitution),
        )
    if isinstance(computation, Perform):
        return Perform(request=substitute_request(computation.request, substitution))
    if isinstance(computation, Handle):
        return Handle(
            instance=computation.instance,
            handler=computation.handler,
            computation=substitute_computation(computation.computation, substitution),
            static_arguments=tuple(
                substitute_static(argument, substitution)
                for argument in computation.static_arguments
            ),
            arguments=tuple(
                substitute_value(argument, substitution)
                for argument in computation.arguments
            ),
        )
    if isinstance(computation, Case):
        return Case(
            scrutinee=substitute_value(computation.scrutinee, substitution),
            motive=CaseMotive(
                indices=computation.motive.indices,
                result_type=substitute_type(
                    computation.motive.result_type, substitution
                ),
            ),
            branches=tuple(
                CaseBranch(
                    constructor=branch.constructor,
                    static_arguments=tuple(
                        substitute_static(argument, substitution)
                        for argument in branch.static_arguments
                    ),
                    fields=tuple(
                        Local(
                            name=field.name,
                            type=substitute_type(field.type, substitution),
                        )
                        for field in branch.fields
                    ),
                    body=substitute_computation(branch.body, substitution),
                    scope=branch.scope,
                )
                for branch in computation.branches
            ),
        )
    if isinstance(computation, If):
        return If(
            condition=substitute_value(computation.condition, substitution),
            then=substitute_computation(computation.then, substitution),
            otherwise=substitute_computation(computation.otherwise, substitution),
        )
    if isinstance(computation, Call):
        return Call(
            callee=computation.callee,
            name=computation.name,
            static_arguments=tuple(
                substitute_static(argument, substitution)
                for argument in computation.static_arguments
            ),
            arguments=tuple(
                substitute_value(argument, substitution)
                for argument in computation.arguments
            ),
            result_type=substitute_type(computation.result_type, substitution),
            effects=substitute_row(computation.effects, substitution),
            origin=computation.origin,
        )
    if isinstance(computation, ApplyPure):
        return computation.with_(
            arguments=tuple(
                substitute_value(argument, substitution)
                for argument in computation.arguments
            ),
            result_type=substitute_type(computation.result_type, substitution),
        )
    if isinstance(computation, CallAddress | InstanceAddress | HandlerReturnAddress):
        return computation
    if isinstance(computation, WithTraceAddresses):
        return computation.with_(
            body=substitute_computation(computation.body, substitution)
        )
    if isinstance(computation, Resume):
        return Resume(
            value=substitute_value(computation.value, substitution),
            origin=computation.origin,
            arguments=tuple(
                substitute_value(argument, substitution)
                for argument in computation.arguments
            ),
        )
    if isinstance(computation, Mask):
        return Mask(
            instance=computation.instance,
            body=substitute_computation(computation.body, substitution),
        )
    if isinstance(computation, NewInstance):
        return NewInstance(
            instance=computation.instance,
            effect=substitute_effect(computation.effect, substitution),
            body=substitute_computation(computation.body, substitution),
            origin=computation.origin,
        )
    if isinstance(computation, Apply):
        return Apply(
            function=substitute_value(computation.function, substitution),
            argument=substitute_value(computation.argument, substitution),
            result_type=substitute_type(computation.result_type, substitution),
            effects=substitute_row(computation.effects, substitution),
            origin=computation.origin,
        )
    if isinstance(computation, VariantCase):
        return VariantCase(
            scrutinee=substitute_value(computation.scrutinee, substitution),
            branches=tuple(
                VariantBranch(
                    label=branch.label,
                    binder=substitute_local(branch.binder, substitution),
                    body=substitute_computation(branch.body, substitution),
                )
                for branch in computation.branches
            ),
            result_type=substitute_type(computation.result_type, substitution),
        )
    if isinstance(computation, VariantSplit):
        return VariantSplit(
            scrutinee=substitute_value(computation.scrutinee, substitution),
            left=_substitute_rest(computation.left, substitution),
            right=_substitute_rest(computation.right, substitution),
            result_type=substitute_type(computation.result_type, substitution),
        )
    if isinstance(computation, LetRec):
        return LetRec(
            bindings=tuple(
                RecursiveBinding(
                    binder=substitute_local(binding.binder, substitution),
                    function=substitute_lambda(binding.function, substitution),
                )
                for binding in computation.bindings
            ),
            body=substitute_computation(computation.body, substitution),
        )
    raise TypeError(f"unknown computation term {computation!r}")