Skip to content

Evaluator

The reference machine is the library's small-step interpreter for Quivers Indexed Effect Core (QIEC), a CEK machine that applies one rule at a time. Each step shows how a request is handled, how a value is returned, and which continuation resumes, so the machine fixes how a well-typed computation runs (Reynolds, 1972).

evaluator

Small-step reference evaluator for the Quivers Indexed Effect Core.

The evaluator is deliberately an interpreter, not an optimized execution engine. It gives Return, Bind, Perform, and Handle one operational meaning against which lowerings and backend runtimes can be tested. Core terms remain serializable: host values and executable handler clauses live only in :class:RuntimeAttachments and are addressed by stable QIEC IDs.

Every number the machine computes is a tensor of the run's quivers.qiec.numbers.NumberDomain, so a value keeps the gradient of everything it was computed from, through calls, recursion and handler clauses; a number is read as a host value only where a branch, an index into structured values, or an item key needs a discrete one.

Handlers are lexical and deep. A resumption reinstalls the matched handler and every inner continuation frame, whereas a handler clause is evaluated only in the outer context. This distinction is easiest to make explicit with the CEK machine below: handling an operation splits the continuation at its matching handler boundary.

RuntimeValidator

RuntimeValidator = Callable[[object], bool | None]

A predicate a host value must pass to inhabit a QIEC type.

It returns False to reject the value; True or None accepts it.

OperationClause

OperationClause = Callable[['RuntimeRequest', 'Resumption', 'ClauseContext'], object]

A host implementation of one handler operation clause.

It receives the request, the delimited continuation, and the clause's runtime services, and returns the clause's answer, a :class:Forward, or a :class:TailResume.

ReturnClause

ReturnClause = Callable[[object, 'ClauseContext'], object]

A host implementation of a handler's return clause.

It receives the handled computation's final value and the clause's runtime services, and returns the handler's answer.

ResponseHook

ResponseHook = Callable[[object], object]

A callback applied to the reply a forwarded request receives.

It returns the value the resumed computation receives in place of the reply.

EvaluationTraceHook

EvaluationTraceHook = Callable[[str, Mapping[str, object]], None]

A callback receiving each evaluator event's name and detail mapping.

EvaluationError

Bases: RuntimeError

Base class for failures at the typed-core/runtime boundary.

MissingAttachmentError

Bases: EvaluationError

A stable runtime reference has no value or handler attachment.

RuntimeTypeMismatch

Bases: EvaluationError

A host result failed the validator for its QIEC result type.

FuelExhaustedError

FuelExhaustedError(steps: int)

Bases: EvaluationError

The step budget ran out before the computation finished.

General recursion is allowed to diverge, so a budget is the only way a caller can bound a run. Exhaustion is reported as an ordinary evaluation failure rather than a host recursion error, which the machine's explicit stack never raises.

PARAMETER DESCRIPTION
steps

The budget that was exhausted; kept on the error as steps.

TYPE: int

Source code in src/quivers/qiec/evaluator.py
def __init__(self, steps: int) -> None:
    super().__init__(f"QIEC evaluation exceeded its budget of {steps} steps")
    self.steps = steps

UnknownComputationError

Bases: EvaluationError

A call names a computation the evaluator was not given a body for.

UnhandledEffectError

UnhandledEffectError(request: EffectRequest)

Bases: EvaluationError

No enclosing lexical handler accepts an effect request.

PARAMETER DESCRIPTION
request

The request nothing handled; kept on the error as request.

TYPE: EffectRequest

Source code in src/quivers/qiec/evaluator.py
def __init__(self, request: EffectRequest) -> None:
    super().__init__(
        "unhandled QIEC operation "
        f"{request.operation} on instance {request.instance}"
    )
    self.request = request

InvalidHandlerError

Bases: EvaluationError

A runtime handler contradicts its checked structural signature.

HandlerManifest didactic-model

HandlerManifest(*, definitions: Mapping[HandlerId, HandlerDef] = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

Immutable checked handler definitions accepted by an evaluator.

Construct this from a :class:KernelRegistry after its declarations have passed kernel registration. Runtime clause objects are then accepted only when their complete structural definitions equal the manifest entry, not merely when their stable IDs collide.

PARAMETER DESCRIPTION
definitions

The checked handler definitions by identity.

TYPE: Mapping[HandlerId, HandlerDef] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

from_registry classmethod

from_registry(registry: KernelRegistry) -> HandlerManifest

Build a manifest from a checked registry.

PARAMETER DESCRIPTION
registry

A registry whose handlers have already been checked.

TYPE: KernelRegistry

RETURNS DESCRIPTION
HandlerManifest

A manifest over those handlers.

Source code in src/quivers/qiec/evaluator.py
@classmethod
def from_registry(cls, registry: KernelRegistry) -> HandlerManifest:
    """Build a manifest from a checked registry.

    Parameters
    ----------
    registry : KernelRegistry
        A registry whose handlers have already been checked.

    Returns
    -------
    HandlerManifest
        A manifest over those handlers.
    """
    return cls(definitions=registry.handlers)

ResumptionUsageError

Bases: EvaluationError

A handler clause used its resumption outside the declared grade.

NonDuplicableContinuationError

Bases: ResumptionUsageError

An unrestricted clause captured state that cannot safely be copied.

RuntimeConstructor didactic-model

RuntimeConstructor(*, constructor: ConstructorId = field(opaque=True, extras=OPAQUE_BY_VALUE), static_arguments: tuple[StaticArgument, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), fields: tuple[HeldValue, ...] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), result_type: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

Erased runtime representation of a checked constructor value.

Constructor metadata, scalar fields, tuples, nested models, and tensors of integers or truth values compare by value. Real tensors and live host objects retain identity, so a gradient is never merged.

PARAMETER DESCRIPTION
constructor

The constructor's stable identity.

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

static_arguments

The constructor's telescope instantiation, as evaluated static data.

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

fields

The evaluated field values, in declaration order.

TYPE: tuple[HeldValue, ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

result_type

The family type the value inhabits.

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

RuntimeRecord didactic-model

RuntimeRecord(*, labels: tuple[str, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), values: tuple[HeldValue, ...] = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: QiecModel

Erased runtime representation of a record value.

PARAMETER DESCRIPTION
labels

The field labels, in canonical order.

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

values

The field values, aligned with labels.

TYPE: tuple[HeldValue, ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

field

field(label: str) -> HeldValue

The value of one field.

PARAMETER DESCRIPTION
label

The field's label.

TYPE: str

RETURNS DESCRIPTION
HeldValue

Its value.

RAISES DESCRIPTION
EvaluationError

If the record has no such field.

Source code in src/quivers/qiec/evaluator.py
def field(self, label: str) -> HeldValue:
    """The value of one field.

    Parameters
    ----------
    label : str
        The field's label.

    Returns
    -------
    HeldValue
        Its value.

    Raises
    ------
    EvaluationError
        If the record has no such field.
    """
    try:
        return self.values[self.labels.index(label)]
    except ValueError as error:
        raise EvaluationError(f"a record has no field {label!r}") from error

RuntimeVariant didactic-model

RuntimeVariant(*, label: str, payload: HeldValue = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: QiecModel

Erased runtime representation of a variant value.

PARAMETER DESCRIPTION
label

The alternative.

TYPE: str

payload

The value the alternative carries.

TYPE: HeldValue DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

RuntimeClosure didactic-model

RuntimeClosure(*, function: Lambda = field(opaque=True, extras=OPAQUE_BY_VALUE), environment: Mapping[Local, HeldValue] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), group: tuple[RecursiveBinding, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A function value: its code and the bindings it captured.

PARAMETER DESCRIPTION
function

The function's code.

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

environment

The bindings in scope where the function was built.

TYPE: Mapping[Local, HeldValue] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

group

The local definitions the function belongs to, which its body sees as closures over the same environment; empty for a function that is not locally recursive.

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

bindings

bindings() -> Scope[Local, HeldValue]

The bindings the function's body runs under, before its argument.

RETURNS DESCRIPTION
Scope[Local, HeldValue]

The captured environment, with each definition of the group bound to its closure.

Source code in src/quivers/qiec/evaluator.py
def bindings(self) -> Scope[Local, HeldValue]:
    """The bindings the function's body runs under, before its argument.

    Returns
    -------
    Scope[Local, HeldValue]
        The captured environment, with each definition of the group
        bound to its closure.
    """
    scope: Scope[Local, HeldValue] = Scope.of(self.environment)
    return scope.extend(
        (
            binding.binder,
            RuntimeClosure(
                function=binding.function,
                environment=self.environment,
                group=self.group,
            ),
        )
        for binding in self.group
    )

HoleClosure didactic-model

HoleClosure(*, hole: HoleValue = field(opaque=True, extras=OPAQUE_BY_VALUE), environment: Mapping[Local, HeldValue] = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: QiecModel

A typed hole as the machine holds it: the hole and its bindings.

Evaluating a hole builds its closure instead of a value. The closure flows wherever a value may flow without being inspected (into a binding, a field, an argument, a result); a step that must inspect it stops the run with an indeterminate result. Filling the hole evaluates the filling under environment, the bindings in scope where the hole was reached, so a filling may mention the locals the hole could see.

PARAMETER DESCRIPTION
hole

The hole term reached.

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

environment

The bindings in scope where it was reached.

TYPE: Mapping[Local, HeldValue] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

AttachmentBinding didactic-model

AttachmentBinding(*, value: HeldValue = field(opaque=True, extras=OPAQUE_BY_IDENTITY), type: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE), validator: RuntimeValidator = field(opaque=True, extras=OPAQUE_BY_IDENTITY), duplicable: bool = False)

Bases: QiecModel

One host value attached to an otherwise serializable core term.

The value and validator retain identity; its checked type compares by value.

duplicable is a semantic assertion about the host value, not merely a promise that copy.copy happens to work. Multi-shot resumptions reject captured attachment values unless this bit was supplied explicitly.

PARAMETER DESCRIPTION
value

The host value.

TYPE: HeldValue DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

type

The type the value inhabits.

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

validator

The predicate that checks a host value against type.

TYPE: RuntimeValidator DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

duplicable

Whether an unrestricted resumption may capture the value.

TYPE: bool DEFAULT: False

RuntimeClause didactic-model

RuntimeClause(*, invoke: OperationClause = field(opaque=True, extras=OPAQUE_BY_IDENTITY), result_validator: RuntimeValidator = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: QiecModel

Executable operation clause and validator for the resumed value.

Both executable callables retain identity.

PARAMETER DESCRIPTION
invoke

The clause body, called with the request, its resumption, and a clause context.

TYPE: OperationClause DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

result_validator

The predicate every value resumed through this clause must pass.

TYPE: RuntimeValidator DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

RuntimeHandler didactic-model

RuntimeHandler(*, definition: HandlerDef = field(opaque=True, extras=OPAQUE_BY_VALUE), clauses: Mapping[OperationId, RuntimeClause] = field(opaque=True, extras=OPAQUE_BY_VALUE), return_clause: ReturnClause = field(default=_identity_return, opaque=True, extras=OPAQUE_BY_IDENTITY), input_validator: RuntimeValidator = field(default=_accept, opaque=True, extras=OPAQUE_BY_IDENTITY), output_validator: RuntimeValidator = field(default=_accept, opaque=True, extras=OPAQUE_BY_IDENTITY), duplicable_context: bool = False, mutable_context: bool = False, fork_context: Callable[['RuntimeHandler'], 'RuntimeHandler'] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), context_factory: Callable[[], 'RuntimeHandler'] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), on_enter: Callable[[], None] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), on_exit: Callable[[], None] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), on_drop: Callable[[], None] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: QiecModel

Executable attachment for a structural :class:HandlerDef.

The checked definition contains coverage, grades, input/output types, and introduced effects. This attachment contains only process-local code and state. It is never serialized as QIEC.

Definitions and clause maps compare by value. Executable callbacks retain identity, and each installation creates its own mutable state.

PARAMETER DESCRIPTION
definition

The checked declaration this attachment implements.

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

clauses

One runtime clause per covered operation, by identity.

TYPE: Mapping[OperationId, RuntimeClause] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

return_clause

How the handler answers the computation's return; the identity return by default.

TYPE: ReturnClause DEFAULT: field(default=_identity_return, opaque=True, extras=OPAQUE_BY_IDENTITY)

input_validator

The predicate the handled computation's result must pass.

TYPE: RuntimeValidator DEFAULT: field(default=_accept, opaque=True, extras=OPAQUE_BY_IDENTITY)

output_validator

The predicate the handler's answer must pass.

TYPE: RuntimeValidator DEFAULT: field(default=_accept, opaque=True, extras=OPAQUE_BY_IDENTITY)

duplicable_context

Whether an unrestricted resumption may capture an installation of this handler.

TYPE: bool DEFAULT: False

mutable_context

Whether an installation carries state; such a handler needs a context_factory so installations do not share it.

TYPE: bool DEFAULT: False

fork_context

Builds an independent copy of an installation for another shot; required when the context is both mutable and duplicable.

TYPE: Callable[['RuntimeHandler'], 'RuntimeHandler'] | None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

context_factory

Builds a fresh installation each time the handler is installed.

TYPE: Callable[[], 'RuntimeHandler'] | None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

on_enter

Called when an installation is entered.

TYPE: Callable[[], None] | None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

on_exit

Called once when the handled computation completes.

TYPE: Callable[[], None] | None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

on_drop

Called once when the handled computation is abandoned instead; exclusive with on_exit.

TYPE: Callable[[], None] | None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

RuntimeAttachments didactic-model

RuntimeAttachments(*, values: dict[AttachmentId, AttachmentBinding] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), handlers: dict[HandlerId, RuntimeHandler] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY), numbers: NumberDomain = field(default_factory=default), distributions: DistributionBackend = field(default_factory=distribution_backend, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: QiecModel

Process-local values and handlers keyed by stable core identifiers.

Each record owns fresh mutable tables whose identities survive updates. It also fixes what the invocation's numbers are and what samples and scores its distributions, so every provider attached to it and every clause running in it read the same.

PARAMETER DESCRIPTION
values

Attached host values by attachment identity.

TYPE: dict[AttachmentId, AttachmentBinding] DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY)

handlers

Runtime handlers by handler identity.

TYPE: dict[HandlerId, RuntimeHandler] DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY)

numbers

The dtype and device of the invocation's numbers; torch's default floating dtype on the CPU unless given.

TYPE: NumberDomain DEFAULT: field(default_factory=default)

distributions

The backend that samples and scores the invocation's distributions; the installed backend unless given.

TYPE: DistributionBackend DEFAULT: field(default_factory=distribution_backend, opaque=True, extras=OPAQUE_BY_IDENTITY)

bind_value

bind_value(attachment: AttachmentId, value: object, type: TypeExpr, *, validator: RuntimeValidator = _accept, duplicable: bool = False) -> AttachmentRef

Attach a host value and return its stable core reference.

PARAMETER DESCRIPTION
attachment

The identity the core term refers to the value by.

TYPE: AttachmentId

value

The host value.

TYPE: object

type

The type the core ascribes to it.

TYPE: TypeExpr

validator

Checks the value really inhabits that type. The default accepts anything, for a value the static check already settles.

TYPE: RuntimeValidator DEFAULT: _accept

duplicable

Whether the value may be copied. This is an assertion about the value, not a guess: a multi-shot resumption capturing a non-duplicable attachment is refused, because copying it would give two continuations a shared mutable thing.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
AttachmentRef

The core reference to use in a term.

RAISES DESCRIPTION
InvalidHandlerError

If the identity is already bound to a different value, type, validator, or duplicability. Rebinding is refused rather than overwriting, since a term already built would silently start meaning something else.

RuntimeValidationError

If the validator rejects the value.

Source code in src/quivers/qiec/evaluator.py
def bind_value(
    self,
    attachment: AttachmentId,
    value: object,
    type: TypeExpr,
    *,
    validator: RuntimeValidator = _accept,
    duplicable: bool = False,
) -> AttachmentRef:
    """Attach a host value and return its stable core reference.

    Parameters
    ----------
    attachment : AttachmentId
        The identity the core term refers to the value by.
    value : object
        The host value.
    type : TypeExpr
        The type the core ascribes to it.
    validator : RuntimeValidator
        Checks the value really inhabits that type. The default
        accepts anything, for a value the static check already
        settles.
    duplicable : bool
        Whether the value may be copied. This is an assertion about
        the value, not a guess: a multi-shot resumption capturing a
        non-duplicable attachment is refused, because copying it
        would give two continuations a shared mutable thing.

    Returns
    -------
    AttachmentRef
        The core reference to use in a term.

    Raises
    ------
    InvalidHandlerError
        If the identity is already bound to a different value, type,
        validator, or duplicability. Rebinding is refused rather than
        overwriting, since a term already built would silently start
        meaning something else.
    RuntimeValidationError
        If the validator rejects the value.
    """
    _validate(value, validator, type, f"attachment {attachment}")
    binding = AttachmentBinding(
        value=value, type=type, validator=validator, duplicable=duplicable
    )
    previous = self.values.get(attachment)
    if previous is not None:
        same_binding = (
            previous.value is value
            and previous.type == type
            and previous.validator is validator
            and previous.duplicable == duplicable
        )
        if not same_binding:
            raise InvalidHandlerError(
                f"runtime attachment {attachment} is already bound differently"
            )
    self.values[attachment] = binding
    return AttachmentRef(attachment=attachment, type=type)

bind_handler

bind_handler(handler: RuntimeHandler) -> HandlerId

Attach executable clauses to their structural handler identity.

PARAMETER DESCRIPTION
handler

The executable handler, already checked against its declaration.

TYPE: RuntimeHandler

RETURNS DESCRIPTION
HandlerId

The identity it was bound under.

RAISES DESCRIPTION
InvalidHandlerError

If a different handler is already bound to that identity.

Source code in src/quivers/qiec/evaluator.py
def bind_handler(self, handler: RuntimeHandler) -> HandlerId:
    """Attach executable clauses to their structural handler identity.

    Parameters
    ----------
    handler : RuntimeHandler
        The executable handler, already checked against its
        declaration.

    Returns
    -------
    HandlerId
        The identity it was bound under.

    Raises
    ------
    InvalidHandlerError
        If a different handler is already bound to that identity.
    """
    id = handler.definition.id
    previous = self.handlers.get(id)
    if previous is not None and previous is not handler:
        raise InvalidHandlerError(f"runtime handler {id} is already bound")
    self.handlers[id] = handler
    return id

RuntimeRequest didactic-model

RuntimeRequest(*, core: EffectRequest = field(opaque=True, extras=OPAQUE_BY_VALUE), arguments: tuple[HeldValue, ...] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), resumption_path: tuple[int, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), dynamic_path: tuple[DynamicAddressFrame, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

An evaluated request supplied to a process-local handler clause.

The core request and address compare by value. Host arguments retain their tuple's identity and the live values it holds.

PARAMETER DESCRIPTION
core

The stable request as written, before evaluation.

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

arguments

The evaluated value arguments, in order.

TYPE: tuple[HeldValue, ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

resumption_path

The ordinal of each resumption taken to reach this request.

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

dynamic_path

The call, local-instance, and operation-clause frames live when the request was performed, outermost first within each path.

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

instance property

instance: EffectInstanceId

The lexical instance this request was performed on.

RETURNS DESCRIPTION
EffectInstanceId

The instance, which decides which handler answers.

operation property

operation: OperationId

The operation requested.

RETURNS DESCRIPTION
OperationId

The operation, which decides which clause answers.

address property

address: tuple[str, tuple[tuple[str, str | int], ...], tuple[int, ...]]

Return the static, dynamic, and multi-shot address components.

RETURNS DESCRIPTION
tuple[str, tuple[tuple[str, str | int], ...], tuple[int, ...]]

The source site, the dynamic address frames, and the resumption path. Active caller shots precede the shots already recorded in the request's rewritten provenance.

ClauseComputation didactic-model

ClauseComputation(*, computation: Computation = field(opaque=True, extras=OPAQUE_BY_VALUE), bindings: tuple[tuple[Local, HeldValue], ...] = field(default=(), opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: QiecModel

Ask the evaluator to run a structural clause body outside the handler.

The computation compares by value; host bindings retain identity.

Host values introduced by a handler must first be installed through :meth:ClauseContext.attach; arbitrary callback closures do not enter the computation tree.

PARAMETER DESCRIPTION
computation

The stable computation to run.

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

bindings

Locals the computation refers to, each with its evaluated value.

TYPE: tuple[tuple[Local, HeldValue], ...] DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_IDENTITY)

Forward didactic-model

Forward(*, on_response: ResponseHook | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: QiecModel

Forward a request to an outer handler, optionally observing its reply.

The optional response hook retains identity.

PARAMETER DESCRIPTION
on_response

Called with the outer handler's answer before it reaches the resumed computation, or None to forward blindly.

TYPE: ResponseHook | None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

TailResume didactic-model

TailResume(*, value: HeldValue = field(opaque=True, extras=OPAQUE_BY_IDENTITY), arguments: tuple[HeldValue, ...] | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: QiecModel

Resume a clause's continuation in place, on the machine's own stack.

The resumed host value retains identity, including tensor gradients.

A foreign clause that answers with this resumes once, exactly as an authored resume(value) in tail position does: the captured frames return to the machine's stack and the handler's return clause applies when the computation completes. Unlike calling the resumption from the clause, which drives the continuation in a nested host call that stays pending until it returns, this leaves no host frame behind, so a multi-shot resumption captured later inside the same handler may run the continuation any number of times.

PARAMETER DESCRIPTION
value

What the resumed operation supplies.

TYPE: HeldValue DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

arguments

The values the handler's parameters have while the continuation runs, or None to keep the installation's current ones.

TYPE: tuple[HeldValue, ...] | None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

ContinuationFrame didactic-model

ContinuationFrame()

Bases: QiecModel

One frame of the reference evaluator's explicit continuation stack.

The evaluator creates and consumes every frame. A handler clause sees frames only through the :class:ClauseContext and :class:Resumption the evaluator hands it, and never inspects or builds one itself; the class exists so those two constructors can name the stack they capture.

Frame subclasses compare checked kernel terms by value and retain live environments, handler state, and callbacks by identity.

ClauseContext

ClauseContext(evaluator: Evaluator, environment: Mapping[Local, object], outer_stack: tuple[ContinuationFrame, ...], resumption_path: tuple[int, ...], request: RuntimeRequest | None, arguments: tuple[object, ...])

Disciplined runtime services available to an attached handler clause.

PARAMETER DESCRIPTION
evaluator

The evaluator running the clause.

TYPE: Evaluator

environment

The bindings in scope at the handler.

TYPE: Mapping[Local, object]

outer_stack

The continuation frames outside the handler.

TYPE: tuple[ContinuationFrame, ...]

resumption_path

The ordinal of each resumption taken to reach the clause.

TYPE: tuple[int, ...]

request

The request the clause answers, or None in a return clause.

TYPE: RuntimeRequest | None

arguments

The current values of the handler's parameters.

TYPE: tuple[object, ...]

Source code in src/quivers/qiec/evaluator.py
def __init__(
    self,
    evaluator: Evaluator,
    environment: Mapping[Local, object],
    outer_stack: tuple[ContinuationFrame, ...],
    resumption_path: tuple[int, ...],
    request: RuntimeRequest | None,
    arguments: tuple[object, ...],
) -> None:
    self._evaluator = evaluator
    self._arguments = arguments
    self._environment = environment
    self._outer_stack = _frames(outer_stack)
    self._resumption_path = resumption_path
    self._request = request

request property

request: RuntimeRequest | None

The request this clause is answering.

RETURNS DESCRIPTION
RuntimeRequest or None

The request, or None in a return clause, which answers a completed computation rather than an operation.

arguments property

arguments: tuple[object, ...]

The current values of the handler's parameters.

RETURNS DESCRIPTION
tuple[object, ...]

One value per declared parameter, in declaration order.

attachments property

attachments: RuntimeAttachments

The host values available to this clause.

RETURNS DESCRIPTION
RuntimeAttachments

The evaluator's attachment table.

emit_trace

emit_trace(event: str, detail: Callable[[], Mapping[str, object] | None]) -> None

Emit a handler event through an installed execution observer.

PARAMETER DESCRIPTION
event

The stable event name.

TYPE: str

detail

A function producing JSON-compatible data, or None to omit the event. Without a trace hook, the function is never called.

TYPE: Callable[[], Mapping[str, object] | None]

Source code in src/quivers/qiec/evaluator.py
def emit_trace(
    self,
    event: str,
    detail: Callable[[], Mapping[str, object] | None],
) -> None:
    """Emit a handler event through an installed execution observer.

    Parameters
    ----------
    event
        The stable event name.
    detail
        A function producing JSON-compatible data, or None to omit
        the event. Without a trace hook, the function is never called.
    """
    hook = self._evaluator.trace_hook
    if hook is not None and (payload := detail()) is not None:
        hook(event, payload)

evaluate

evaluate(computation: Computation) -> object

Evaluate a clause body in the outer handler context.

A delimiter prevents the clause body from consuming the continuation outside the handled expression. Effects performed here can reach only handlers outside the matched handler, which is the chosen deep-handler semantics.

PARAMETER DESCRIPTION
computation

The clause body to run.

TYPE: Computation

RETURNS DESCRIPTION
object

What the body produced.

Source code in src/quivers/qiec/evaluator.py
def evaluate(self, computation: Computation) -> object:
    """Evaluate a clause body in the outer handler context.

    A delimiter prevents the clause body from consuming the continuation
    outside the handled expression.  Effects performed here can reach only
    handlers outside the matched handler, which is the chosen deep-handler
    semantics.

    Parameters
    ----------
    computation : Computation
        The clause body to run.

    Returns
    -------
    object
        What the body produced.
    """
    delimiter = _DelimiterFrame()
    stack = [*self._outer_stack, delimiter]
    return self._evaluator._evaluate_delimited(
        computation,
        Scope.of(self._environment),
        stack,
        self._outer_stack,
        self._resumption_path,
        delimiter,
    )

attach

attach(value: object, type: TypeExpr, *, role: str, validator: RuntimeValidator = _accept, duplicable: bool = False) -> AttachmentRef

Install a generated host value under a deterministic runtime ID.

PARAMETER DESCRIPTION
value

The host value to attach.

TYPE: object

type

The type the core ascribes to it.

TYPE: TypeExpr

role

What the value is for, which enters its derived identity.

TYPE: str

validator

Checks the value inhabits the type.

TYPE: RuntimeValidator DEFAULT: _accept

duplicable

Whether the value may be copied by a multi-shot resumption.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
AttachmentRef

A reference usable in a core term. The identity derives from the run, the request, and the role rather than being generated, so a trace can name the same attachment twice.

Source code in src/quivers/qiec/evaluator.py
def attach(
    self,
    value: object,
    type: TypeExpr,
    *,
    role: str,
    validator: RuntimeValidator = _accept,
    duplicable: bool = False,
) -> AttachmentRef:
    """Install a generated host value under a deterministic runtime ID.

    Parameters
    ----------
    value : object
        The host value to attach.
    type : TypeExpr
        The type the core ascribes to it.
    role : str
        What the value is for, which enters its derived identity.
    validator : RuntimeValidator
        Checks the value inhabits the type.
    duplicable : bool
        Whether the value may be copied by a multi-shot resumption.

    Returns
    -------
    AttachmentRef
        A reference usable in a core term. The identity derives from
        the run, the request, and the role rather than being
        generated, so a trace can name the same attachment twice.
    """
    if self._request is None:
        seed: tuple[object, ...] = (
            self._evaluator._run_serial,
            "return-clause",
            self._resumption_path,
            role,
        )
    else:
        seed = (
            self._evaluator._run_serial,
            self._request.address,
            str(self._request.operation),
            role,
        )
    id = AttachmentId.derive("runtime-generated", *seed)
    return self.attachments.bind_value(
        id,
        value,
        type,
        validator=validator,
        duplicable=duplicable,
    )

Resumption

Resumption(evaluator: Evaluator, request: RuntimeRequest, grade: ResumptionGrade | ResumptionInterval, captured_environment: Mapping[Local, object], captured_stack: tuple[ContinuationFrame, ...], outer_stack: tuple[ContinuationFrame, ...], validator: RuntimeValidator, path: tuple[int, ...])

Dynamically checked, delimited continuation supplied to one clause.

PARAMETER DESCRIPTION
evaluator

The evaluator that captured the continuation.

TYPE: Evaluator

request

The request whose result the continuation awaits.

TYPE: RuntimeRequest

grade

How often the clause may invoke the continuation.

TYPE: ResumptionGrade | ResumptionInterval

captured_environment

The bindings in scope at the request.

TYPE: Mapping[Local, object]

captured_stack

The continuation frames between the request and the handler.

TYPE: tuple[ContinuationFrame, ...]

outer_stack

The continuation frames outside the handler.

TYPE: tuple[ContinuationFrame, ...]

validator

The predicate every resumed value must pass.

TYPE: RuntimeValidator

path

The ordinal of each resumption taken to reach the clause.

TYPE: tuple[int, ...]

Source code in src/quivers/qiec/evaluator.py
def __init__(
    self,
    evaluator: Evaluator,
    request: RuntimeRequest,
    grade: ResumptionGrade | ResumptionInterval,
    captured_environment: Mapping[Local, object],
    captured_stack: tuple[ContinuationFrame, ...],
    outer_stack: tuple[ContinuationFrame, ...],
    validator: RuntimeValidator,
    path: tuple[int, ...],
) -> None:
    self._evaluator = evaluator
    self._request = request
    self._grade = grade
    self._captured_environment = captured_environment
    self._captured_stack = _frames(captured_stack)
    self._outer_stack = _frames(outer_stack)
    self._validator = validator
    self._path = path
    self._calls = 0
    self._closed = False
    self._omega_owner = (
        object()
        if (
            grade is ResumptionGrade.UNRESTRICTED
            or isinstance(grade, ResumptionInterval)
        )
        else None
    )
    self._sharing_owner: object | None = None
    delimiters = tuple(
        index
        for index, frame in enumerate(self._captured_stack)
        if isinstance(frame, _DelimiterFrame)
    )
    self._owned_start = delimiters[-1] + 1 if delimiters else 0
    if isinstance(grade, ResumptionInterval) and (
        len(self._captured_stack) != 2
        or not isinstance(self._captured_stack[0], _HandlerFrame)
        or not isinstance(self._captured_stack[1], _BindFrame)
    ):
        raise ResumptionUsageError(
            "resumption interval requires an isolated owned capture"
        )
    if self._omega_owner is not None:
        evaluator._validate_duplicable_capture(
            captured_environment,
            self._captured_stack[self._owned_start :],
        )
        # Snapshot before the clause body runs. Every shot, including the
        # first, forks from this untouched seed rather than a previous
        # branch or the live handler context.
        self._seed_stack = self._fork_owned(self._captured_stack)
    else:
        self._seed_stack = self._captured_stack

grade property

The grade this resumption is held to.

RETURNS DESCRIPTION
ResumptionGrade or ResumptionInterval

The declared grade, checked statically and again here.

calls property

calls: int

How many times this resumption has been invoked so far.

RETURNS DESCRIPTION
int

The count, which the grade bounds.

__call__

__call__(value: object, arguments: tuple[HeldValue, ...] | None = None) -> object

Resume the suspended computation with a value.

The static analysis already rejects a clause that can exceed its grade. This guard stays because it protects against a foreign handler, whose body the analysis never saw, and against a compiler bug: a grade is what lets a runtime discard a continuation, so exceeding it is not recoverable.

PARAMETER DESCRIPTION
value

What the resumed operation supplies.

TYPE: object

arguments

The values the handler's parameters have while the continuation runs, or None to keep the current ones.

TYPE: tuple[HeldValue, ...] or None DEFAULT: None

RETURNS DESCRIPTION
object

What the resumed computation produced.

RAISES DESCRIPTION
ResumptionUsageError

If the next call exceeds the grade's upper bound or an interval token is closed or shared.

NonDuplicableContinuationError

If an unrestricted resumption would have to copy a captured value that is not duplicable.

RuntimeValidationError

If the value does not inhabit the operation's result type.

Source code in src/quivers/qiec/evaluator.py
def __call__(
    self, value: object, arguments: tuple[HeldValue, ...] | None = None
) -> object:
    """Resume the suspended computation with a value.

    The static analysis already rejects a clause that can exceed its
    grade. This guard stays because it protects against a foreign
    handler, whose body the analysis never saw, and against a
    compiler bug: a grade is what lets a runtime discard a
    continuation, so exceeding it is not recoverable.

    Parameters
    ----------
    value : object
        What the resumed operation supplies.
    arguments : tuple[HeldValue, ...] or None
        The values the handler's parameters have while the
        continuation runs, or ``None`` to keep the current ones.

    Returns
    -------
    object
        What the resumed computation produced.

    Raises
    ------
    ResumptionUsageError
        If the next call exceeds the grade's upper bound or an
        interval token is closed or shared.
    NonDuplicableContinuationError
        If an unrestricted resumption would have to copy a captured
        value that is not duplicable.
    RuntimeValidationError
        If the value does not inhabit the operation's result type.
    """
    captured, path = self._begin_shot(value, arguments)
    # Outer handlers remain visible to effects performed by the resumed
    # continuation, but the delimiter prevents normal completion from
    # consuming the continuation outside the handled expression.
    delimiter = _DelimiterFrame()
    stack = [*self._outer_stack, delimiter, *captured]
    protected = (
        *self._outer_stack,
        *captured[: self._owned_start],
    )
    try:
        return self._evaluator._drive_value(
            value,
            Scope.of(self._captured_environment),
            stack,
            path,
            delimiter,
        )
    except _HostUnwind as unwind:
        if unwind.delimiter is not delimiter:
            raise
        return unwind.value
    except _HoleNeeded as needed:
        raise _HoleNeededInHost(needed.closure) from None
    finally:
        # A normally returned shot has already exited every copied frame.
        # Exceptional or delimited exits leave some frames live.  Lifecycle
        # guards make this final sweep exact-once in either case.
        self._evaluator._drop_local_handlers(
            (*captured[self._owned_start :], *stack),
            protected,
        )

Evaluator

Evaluator(attachments: RuntimeAttachments | None = None, *, handler_manifest: HandlerManifest | None = None, trace_hook: EvaluationTraceHook | None = None, module: QiecModule | None = None, fuel: int | None = None, type_validator: Callable[[TypeExpr], RuntimeValidator | None] | None = None)

Execute QIEC computations with explicit runtime attachments.

PARAMETER DESCRIPTION
attachments

The host values and handlers available; empty by default.

TYPE: RuntimeAttachments | None DEFAULT: None

handler_manifest

Checked handler definitions every attached handler must match exactly on each :meth:evaluate, or None to skip that check there; :meth:evaluate_checked always derives a manifest from its registry.

TYPE: HandlerManifest | None DEFAULT: None

trace_hook

Called with each execution event's name and payload, or None for no tracing.

TYPE: EvaluationTraceHook | None DEFAULT: None

module

The module whose named computations calls resolve to and whose authored handlers handle may install without an attachment, or None when the computation calls nothing and installs only attached handlers.

TYPE: QiecModule | None DEFAULT: None

fuel

The number of machine steps a run may take before failing with :class:FuelExhaustedError, or None for no bound.

TYPE: int | None DEFAULT: None

type_validator

Supplies the host validator for a type at an authored handler's boundaries: the values it is resumed with, the handled computation's result, and its answer. None accepts every host value there, which is sound for values that only ever flowed through checked terms.

TYPE: Callable[[TypeExpr], RuntimeValidator | None] | None DEFAULT: None

Source code in src/quivers/qiec/evaluator.py
def __init__(
    self,
    attachments: RuntimeAttachments | None = None,
    *,
    handler_manifest: HandlerManifest | None = None,
    trace_hook: EvaluationTraceHook | None = None,
    module: QiecModule | None = None,
    fuel: int | None = None,
    type_validator: Callable[[TypeExpr], RuntimeValidator | None] | None = None,
) -> None:
    self.attachments = attachments or RuntimeAttachments()
    self.numbers = self.attachments.numbers
    self.distributions = self.attachments.distributions
    self._literals: dict[LiteralValue, object] = {}
    self._bind_reads: OrderedDict[int, tuple[Computation, tuple[Local, ...]]] = (
        OrderedDict()
    )
    self.handler_manifest = handler_manifest
    self.trace_hook = trace_hook
    self.fuel = fuel
    self._type_validator = type_validator
    self._computations: Mapping[ComputationId, NamedComputation] = {}
    self._pure_callees: set[ComputationId] = set()
    self._pure_records: _RecordLayouts | None = None
    self._module = module
    self._handler_definitions: Mapping[HandlerId, HandlerDef] = {}
    self._native_families: frozenset[str] = frozenset()
    if module is not None:
        (
            self._computations,
            self._handler_definitions,
            self._native_families,
        ) = _module_tables(module)
    self._run_serial = 0
    self._steps = 0
    self._call_serial = 0
    self._instance_serial = 0
    self._return_serials: dict[HandlerId, int] = {}
    self._fills: dict[str, Value] = {}
    self._filled: dict[int, tuple[HoleClosure, HeldValue]] = {}
    self._holes_live = False
    self._suspension: Suspension | None = None

evaluate

evaluate(computation: Computation, environment: Mapping[Local, object] | None = None) -> object

Evaluate a closed or explicitly supplied computation.

PARAMETER DESCRIPTION
computation

The computation to run.

TYPE: Computation

environment

Values for the computation's free locals. None means it is closed.

TYPE: Mapping[Local, object] or None DEFAULT: None

RETURNS DESCRIPTION
object

What the computation produced.

RAISES DESCRIPTION
EvaluationError

If a request reaches no handler, a handler is missing from the manifest, a resumption exceeds its grade, or a host value fails validation.

Source code in src/quivers/qiec/evaluator.py
def evaluate(
    self,
    computation: Computation,
    environment: Mapping[Local, object] | None = None,
) -> object:
    """Evaluate a closed or explicitly supplied computation.

    Parameters
    ----------
    computation : Computation
        The computation to run.
    environment : Mapping[Local, object] or None
        Values for the computation's free locals. None means it is
        closed.

    Returns
    -------
    object
        What the computation produced.

    Raises
    ------
    EvaluationError
        If a request reaches no handler, a handler is missing from
        the manifest, a resumption exceeds its grade, or a host value
        fails validation.
    """
    if self.handler_manifest is not None:
        self._validate_handler_manifest(self.handler_manifest)
    self._begin_run()
    self._arm_holes(computation)
    stack: list[_Frame] = []
    try:
        result = self._drive_computation(
            computation,
            Scope(self._machine_environment(environment)),
            stack,
            (),
        )
    except _HostUnwind as unwind:
        self._drop_stack(tuple(stack))
        raise EvaluationError(
            "a value reached a host delimiter no resumption was waiting on"
        ) from unwind
    except _HoleNeededInHost as needed:
        self._drop_stack(tuple(stack))
        return Indeterminate(needed=needed.closure, closures=(needed.closure,))
    except BaseException:
        self._drop_stack(tuple(stack))
        raise
    return self._finish(result)

evaluate_checked

evaluate_checked(computation: Computation, registry: KernelRegistry, environment: Mapping[Local, object] | None = None) -> object

Kernel-check a computation and fail closed on handler attachments.

PARAMETER DESCRIPTION
computation

The computation to run.

TYPE: Computation

registry

Declarations to check it against.

TYPE: KernelRegistry

environment

Values for its free locals.

TYPE: Mapping[Local, object] or None DEFAULT: None

RETURNS DESCRIPTION
object

What the computation produced.

RAISES DESCRIPTION
KernelError

If the computation does not check.

EvaluationError

If execution fails, as in evaluate.

Source code in src/quivers/qiec/evaluator.py
def evaluate_checked(
    self,
    computation: Computation,
    registry: KernelRegistry,
    environment: Mapping[Local, object] | None = None,
) -> object:
    """Kernel-check a computation and fail closed on handler attachments.
    Parameters
    ----------
    computation : Computation
        The computation to run.
    registry : KernelRegistry
        Declarations to check it against.
    environment : Mapping[Local, object] or None
        Values for its free locals.

    Returns
    -------
    object
        What the computation produced.

    Raises
    ------
    KernelError
        If the computation does not check.
    EvaluationError
        If execution fails, as in `evaluate`.
    """
    runtime_environment = self._machine_environment(environment)
    context = CheckContext()
    for local in runtime_environment:
        context = context.extend(local)
    infer_computation(
        computation,
        registry,
        context,
    )
    return self.evaluate_validated(computation, registry, runtime_environment)

evaluate_validated

evaluate_validated(computation: Computation, registry: KernelRegistry, environment: Mapping[Local, object] | None = None) -> object

Run a computation a module validation has already checked.

validate_module checks every body of a module against its registry; a caller holding that registry runs such a body without checking it again. The handler manifest is still held against the attachments.

PARAMETER DESCRIPTION
computation

The computation to run, a body of the validated module.

TYPE: Computation

registry

The registry the module validated against.

TYPE: KernelRegistry

environment

Values for its free locals.

TYPE: Mapping[Local, object] or None DEFAULT: None

RETURNS DESCRIPTION
object

What the computation produced.

RAISES DESCRIPTION
EvaluationError

If execution fails, as in evaluate.

Source code in src/quivers/qiec/evaluator.py
def evaluate_validated(
    self,
    computation: Computation,
    registry: KernelRegistry,
    environment: Mapping[Local, object] | None = None,
) -> object:
    """Run a computation a module validation has already checked.

    `validate_module` checks every body of a module against its
    registry; a caller holding that registry runs such a body
    without checking it again. The handler manifest is still held
    against the attachments.

    Parameters
    ----------
    computation : Computation
        The computation to run, a body of the validated module.
    registry : KernelRegistry
        The registry the module validated against.
    environment : Mapping[Local, object] or None
        Values for its free locals.

    Returns
    -------
    object
        What the computation produced.

    Raises
    ------
    EvaluationError
        If execution fails, as in `evaluate`.
    """
    runtime_environment: Scope[Local, HeldValue] = Scope.of(environment or {})
    manifest = HandlerManifest.from_registry(registry)
    self._validate_handler_manifest(manifest)
    self._begin_run()
    self._arm_holes(computation)
    stack: list[_Frame] = []
    try:
        result = self._drive_computation(
            computation,
            runtime_environment,
            stack,
            (),
        )
    except _HoleNeededInHost as needed:
        self._drop_stack(tuple(stack))
        return Indeterminate(needed=needed.closure, closures=(needed.closure,))
    except BaseException:
        self._drop_stack(tuple(stack))
        raise
    return self._finish(result)

evaluate_value

evaluate_value(value: Value, environment: Mapping[Local, object] | None = None) -> object

Erase and evaluate a checked QIEC value.

PARAMETER DESCRIPTION
value

The value to evaluate.

TYPE: Value

environment

Values for its free locals.

TYPE: Mapping[Local, object] or None DEFAULT: None

RETURNS DESCRIPTION
object

The value as the machine holds it, or an Indeterminate when the value needs a hole with no filling.

Source code in src/quivers/qiec/evaluator.py
def evaluate_value(
    self,
    value: Value,
    environment: Mapping[Local, object] | None = None,
) -> object:
    """Erase and evaluate a checked QIEC value.
    Parameters
    ----------
    value : Value
        The value to evaluate.
    environment : Mapping[Local, object] or None
        Values for its free locals.

    Returns
    -------
    object
        The value as the machine holds it, or an `Indeterminate` when
        the value needs a hole with no filling.
    """
    self._arm_holes(value)
    try:
        return self._value(value, self._machine_environment(environment))
    except _HoleNeeded as needed:
        return Indeterminate(needed=needed.closure, closures=(needed.closure,))

resume

resume(indeterminate: Indeterminate, fills: Mapping[str, Value]) -> HeldValue

Fill holes and continue an indeterminate run where it stopped.

A suspended run continues from the step that needed a hole, so nothing before that step runs again; a run that finished with open holes in its value has those holes replaced by their fillings. A filling is a value evaluated under the bindings of the hole it fills, and may contain holes of its own. Fillings accumulate: a hole filled once stays filled for every later resumption of this evaluator.

PARAMETER DESCRIPTION
indeterminate

The result of a run of this evaluator.

TYPE: Indeterminate

fills

Fillings by hole name. The caller has checked each against its hole's goal.

TYPE: Mapping[str, Value]

RETURNS DESCRIPTION
HeldValue

The run's value, or a further Indeterminate when it needs a hole that is still open.

RAISES DESCRIPTION
EvaluationError

If the suspension is not this evaluator's latest one (a suspension is a one-shot continuation), or the hole was needed inside host code, whose frames could not be suspended.

Source code in src/quivers/qiec/evaluator.py
def resume(
    self, indeterminate: Indeterminate, fills: Mapping[str, Value]
) -> HeldValue:
    """Fill holes and continue an indeterminate run where it stopped.

    A suspended run continues from the step that needed a hole, so
    nothing before that step runs again; a run that finished with open
    holes in its value has those holes replaced by their fillings. A
    filling is a value evaluated under the bindings of the hole it
    fills, and may contain holes of its own. Fillings accumulate: a
    hole filled once stays filled for every later resumption of this
    evaluator.

    Parameters
    ----------
    indeterminate : Indeterminate
        The result of a run of this evaluator.
    fills : Mapping[str, Value]
        Fillings by hole name. The caller has checked each against its
        hole's goal.

    Returns
    -------
    HeldValue
        The run's value, or a further `Indeterminate` when it needs a
        hole that is still open.

    Raises
    ------
    EvaluationError
        If the suspension is not this evaluator's latest one (a
        suspension is a one-shot continuation), or the hole was needed
        inside host code, whose frames could not be suspended.
    """
    self._fills.update(fills)
    self._holes_live = True
    suspension = indeterminate.suspension
    if suspension is None:
        if indeterminate.value is None:
            raise EvaluationError(
                f"hole ?{indeterminate.holes()[0]} was needed inside a foreign "
                "handler clause, whose host frames cannot be suspended; run "
                "the computation again with the filling"
            )
        return self._finish(indeterminate.value)
    if suspension is not self._suspension or suspension.evaluator is not self:
        raise EvaluationError(
            "an indeterminate run resumes once, from its latest suspension"
        )
    self._suspension = None
    stack = list(suspension.stack)
    try:
        result = self._run(
            suspension.current,
            Scope.of(suspension.environment),
            stack,
            suspension.resumption_path,
        )
    except _HoleNeededInHost as needed:
        self._drop_stack(tuple(stack))
        return Indeterminate(needed=needed.closure, closures=(needed.closure,))
    except BaseException:
        self._drop_stack(tuple(stack))
        raise
    return self._finish(result)

abandon

abandon(indeterminate: Indeterminate) -> None

Release the handlers a suspended run holds, without resuming it.

PARAMETER DESCRIPTION
indeterminate

The result of a run of this evaluator.

TYPE: Indeterminate

Source code in src/quivers/qiec/evaluator.py
def abandon(self, indeterminate: Indeterminate) -> None:
    """Release the handlers a suspended run holds, without resuming it.

    Parameters
    ----------
    indeterminate : Indeterminate
        The result of a run of this evaluator.
    """
    suspension = indeterminate.suspension
    if suspension is not None and suspension is self._suspension:
        self._suspension = None
        self._drop_stack(suspension.stack)

Suspension didactic-model

Suspension(*, evaluator: Evaluator = field(opaque=True, extras=OPAQUE_BY_IDENTITY), current: Computation | _Returned = field(opaque=True, extras=OPAQUE_BY_IDENTITY), environment: Mapping[Local, HeldValue] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), stack: tuple[_Frame, ...] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), resumption_path: tuple[int, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

The state of a run stopped at a step that needs an open hole.

The step has not run, so continuing the state after the hole is filled replays exactly that step. A suspension is a one-shot continuation: its frames own live handler state, so it resumes once.

PARAMETER DESCRIPTION
evaluator

The evaluator that stopped, which alone can continue it.

TYPE: Evaluator DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

current

The step that needs the hole.

TYPE: Computation | _Returned DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

environment

The bindings in scope at that step.

TYPE: Mapping[Local, HeldValue] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

stack

The frame stack beneath it.

TYPE: tuple[_Frame, ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

resumption_path

The resumption address in force.

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

Indeterminate didactic-model

Indeterminate(*, value: HeldValue = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), needed: HoleClosure | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY), closures: tuple[HoleClosure, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_IDENTITY), suspension: Suspension | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: QiecModel

The result of a run that depends on a hole with no filling.

A run around holes produces one of two indeterminate results. If a step had to inspect an open hole, the run stopped there: needed is that hole's closure and suspension continues the run after a filling. If the run finished but its value holds open holes (a hole returned, or stored in a field), value is that partial value and closures lists its open holes; filling them settles the value.

PARAMETER DESCRIPTION
value

The partial value, or None when the run stopped before finishing.

TYPE: HeldValue DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

needed

The closure of the hole the run stopped on, if it stopped.

TYPE: HoleClosure | None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

closures

Every open hole closure the result depends on, in the order met.

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

suspension

The suspended machine, when the run stopped where the evaluator can continue it; None for a finished run or for a hole needed inside a foreign handler clause.

TYPE: Suspension | None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY)

holes

holes() -> tuple[str, ...]

The names of the open holes the result depends on.

RETURNS DESCRIPTION
tuple[str, ...]

Each name once, in the order met.

Source code in src/quivers/qiec/evaluator.py
def holes(self) -> tuple[str, ...]:
    """The names of the open holes the result depends on.

    Returns
    -------
    tuple[str, ...]
        Each name once, in the order met.
    """
    return tuple(dict.fromkeys(closure.hole.name for closure in self.closures))

Cited sources

John C. Reynolds. Definitional Interpreters for Higher-Order Programming Languages. In Proceedings of the ACM Annual Conference, volume 2, 717–740. 1972. doi:10.1145/800194.805852.