Skip to content

Rule presentations

A RulePresentation states a deduction system as QIEC declarations. A judgment form (JudgmentDecl) is an indexed family, and a judgment (Judgment) is an application of the family to index arguments. A Rule is a constructor of its conclusion's family: its telescope holds its typed schematic variables, its fields are its premise judgments in order followed by the values it carries, and it may have a side condition, which is a checked QIEC computation, and a weight parameter. An AxiomSlot is a rule with no premises that is filled at run time, and every input is an AxiomOccurrence with its own identity, so two equal inputs are two axioms.

Proofs are therefore an inductive family, and the checker that checks every QIEC declaration checks the presentation: declarations lowers it to families and constructors, and construction runs validate_module on the result. The presentation adds only what the checker cannot see: every variable of a conclusion and of a side condition is bound by the premises, and every premise pattern can be matched from left to right without search.

Semantics

For input occurrences \(A_j\) the derivations of a judgment \(j\) are the initial algebra of the polynomial functor

\[ (F_A X)_j = A_j + \coprod_{r : (j_1, \dots, j_n) \to j} \prod_{k=1}^{n} X_{j_k}, \]

and a HostInterpretation, which gives an operation for each rule and slot, folds a Derivation by the unique map out of it. A derivation is a proof of an Item, not the item: one item can have many derivations, and a nonlinear function of an aggregate over an item's derivations is not in general a function of the derivations.

A host interpretation is an algebra of the signature functor \(F_A\): a carrier per judgment and an operation per rule. It is neither a weight algebra of quivers.core (a semiring of weights, with laws) nor an Eilenberg-Moore algebra of a monad in quivers.monadic; a weight algebra interprets the rules only through the weights of their applications.

The reference interpretation

ReferenceInterpretation grounds every rule against every derived item, lists every derivation of a goal, and computes an observable by its definition, \(\sum_d w(d)\, h(\mathrm{fold}(d))\). It is an oracle for small systems. Its cost is exponential in general, and executors are planned from the presentation's analysis instead.

closed_derivation_value makes an ordinary QIEC constructor value from a closed derivation of an unconditional presentation without proof equations. The value has the proved judgment's indexed family type, so a checked computation can take it as an argument. The caller retains the derivation's occurrence identities and weights separately. For instance, an expectation of a nonlinear proof encoding applies the encoding to each proof in the declared support before taking the weighted sum.

Analysis

analysis holds what a plan needs: sizes, the strongly connected components of the dependency graph of judgment forms, whether each cyclic component is linear, and the variables each rule's join is on. recursion reads the weakest recursion contract the family graph guarantees. The family graph over-approximates the derived hypergraph: span rules are cyclic as families and acyclic as items, and detecting that needs a measure on the indices, which the analysis does not yet compute.

Structural signatures

presentation_of gives the presentation of a structural Signature: each object sort is a judgment form, a constructor is a rule with no side condition whose object arguments are premises and whose data and index arguments are values, and a binder is a rule whose scoped arguments are premises with the bound variables as hypotheses. A signature builds each of its name-keyed tables once, so folding a term costs the size of the term.

Deductions and rule schemata

A deduction declaration is read once into its presentation, which the compiled DeductionSystem keeps as presentation. A slot that holds a chart position is a natural number, and every other argument is a term of one closed sort, Term, whose constructors are the atoms and applied symbols the declaration writes. A deduction T -> T derives terms, so every item whose head holds no position, such as X/Y or an atom, is an instance of one judgment form whose argument is the term, and a variable that is an item is the same variable wherever it occurs inside a term. An item whose head holds positions, such as a lexicon's span(i, j, c), is a judgment form of its own. Each sequent is a rule, and each kind of input is an axiom slot. The agenda's InferenceRule patterns and the reference machine's computations are both derived from these rules, so a pattern is read from the source in one place. A learnable rule's weight is a parameter named by the deduction and the rule. Judgments partition by form, so a premise or conclusion that is a bare variable, and does not occur inside a term, ranges over the term form and every form that holds positions: the rule is the family of its instances, one per choice of a form for each such variable, which becomes the term itself or the form's head applied to fresh variables (positions where the form has them). One variable takes one form wherever it occurs, and every instance keeps the rule's weight parameter. A bare numeral is likewise a term or the position of a form of a single position slot. schema_presentation gives the presentation of a rule schema instantiated over a category system: one span judgment, and one rule per ground binary or unary instance.

Contexts and open derivations

An OpenDerivation derives an item from a context of hypotheses. Its Holes refer to the context by de Bruijn index, counted from the last (innermost) hypothesis. A Premise declares where its hypotheses go: its before block at the left of the enclosing context and its after block at the right, so it is derived in before + context + after (extend_context is the one place this is decided). In an ordered context the side matters. Open derivations are the arrows of the free colored nonsymmetric multicategory of the presentation: identity_derivation is the identity, and compose_derivations plugs a derivation into each hypothesis in order and concatenates their contexts. Composition is associative and unital, and an interpretation is a functor out of the multicategory: folding a composite equals folding the outer derivation at the folds of its arguments. Both laws are checked.

A ContextStructure declares which structural rules a presentation's contexts admit: exchange (uses out of order), weakening (a hypothesis unused) and contraction (one used twice). ORDERED admits none and is the default, so nothing is inferred from how a context is stored; LINEAR, AFFINE, RELEVANT and CARTESIAN admit more. required_structure reads which rules a derivation uses, scope by scope, and check_structure refuses a use the presentation does not admit, such as a permutation in an ordered context. rename_hypotheses moves hypotheses to new positions, which is how exchange, weakening and contraction are written, and substitute_hypotheses replaces every hypothesis by a derivation in one shared context.

The Lambek calculus is the example. Its slash eliminations are ordinary rules, and its introductions are premises with one hypothesis: on the right for a / b, on the left for b \ a. With ORDERED structure exactly the planar derivations are admitted: type raising np |- s / (np \ s) and np |- (s / np) \ s and composition s / np, np / n |- s / n pass the QIEC checker and the structure check, and an independent cut-free sequent search proves their sequents. np |- s / (s / np) needs its hypotheses out of order; it is refused in an ordered context, admitted in a linear one, and provable only with permutation. Swapping a left introduction for a right one is refused by the checker, so the two slashes are not interchangeable.

An interpretation is context indexed: a premise with hypotheses reaches its rule's operation as a Scoped function of the hypotheses' values (the left block, then the right block), so a binder decides what its variables stand for, and fold_open folds an open derivation at values of its context.

Checked right-scoped folds

scoped_proof_types derives checked QIEC proof and environment types from an unconditional, unindexed Cartesian presentation. The presentation explicitly grants exchange, weakening, and contraction. The adapter admits right-scoped hypotheses and requires a closed semantic carrier per judgment when interpreting a proof. A structural signature can use the existing presentation_of and term_derivation adapters. Set the Cartesian permissions on that presentation explicitly before preparing the scoped types.

An environment extends a context with a nominal frame that carries the previous environment and the value of the newest hypothesis. A proof that refers to a hypothesis carries a checked witness of its exact position in that environment. Induction on the witness shows that lookup returns the newest value for the innermost reference and visits one preceding frame for each position it passes. Each premise's context is computed by extending its parent's context in the order the rule declares. Proof constructors and their stable identities are shared across choices of semantic carriers. ScopedProofTypes.value checks an open derivation and retains the original input occurrence identities.

scoped_proof_fold fixes the carriers and closed effect rows for an interpretation. ScopedProofFold.operation_parameters gives the typed arguments of each rule operation at an arbitrary environment type. Eager premises run in written order. A scoped premise gives the operation a pair of its child proof and captured environment. ScopedProofFold.applications supplies the named computation that takes that pair and one value per introduced hypothesis. Each application extends the captured environment in order and evaluates the child once. Treating scoped arguments as functions of their hypotheses requires actions to consume them through these applications. An action can also inspect the proof in the pair as a proof observer, so extensional equations are an additional obligation on such actions.

ScopedProofFold.assemble combines the operations with the generated folds and checks the module. The resulting computations serialize and run on the native QIEC evaluator. Applying a scoped argument repeatedly runs its effects at the corresponding dynamic addresses. Skipping the argument skips those effects. Applications descend into strict proof subtrees. On finite proofs they terminate when each operation uses its supplied arguments finitely and terminates apart from these calls. The adapter checks scope and effect types. Ordered and left-scoped presentations, term-dependent judgments, and preservation of proof equations require a separate contract.

An authored scoped interpretation can supply one closed lexical row using effects=[instance, ...] for a signature with several object sorts. Each judgment's generated fold must have exactly that residual row. Eager premises and scoped applications invoke the fold of the premise's nominal judgment. Two names for instances of one interface remain distinct in those folds and in the schema's effect requirements.

carriers=by_judgment assigns a closed type to each judgment from its named rule operations. The interpretation's codomain gives the root carrier. Every other judgment needs a rule whose operation returns its carrier, and every operation concluding that judgment must agree on the same type. These result types are closed independently of the ambient context binder. A frame for a bound judgment stores that judgment's carrier, so a scoped premise can read a nominal data value even when its own fold returns Real. An interpretation without this option supplies its codomain as the common carrier.

A ModelSchema exposes the selected program’s checked ScopedInterpretationBinding records through scoped_interpretations. Reachability follows ordinary calls and calls made in installed authored handler clauses. Each binding retains the original rule presentation, the assignment of rules to operation identities, the root computation, the carriers, and the named instances required by its effect rows. The binding can be serialized alongside the executable QIEC module. Its validate method rechecks the executable declarations before using a restored binding. The companion has its own wire record and describes the scope and effect contract. It carries no claims about preservation of proof equations. Its reconstruction checks the generated environment and fold against the checked computations, including premise order and the named effect instances.

For the scope comparison, let \(\rho\) map hypothesis positions in a context \(\Gamma\) to positions of the same judgment in \(\Delta\). Each renamed hypothesis reads the same value at a valuation \(v\) of \(\Delta\) as the original reads at \(v\circ\rho\). Lookup follows the membership witness, and crossing a binder extends \(\rho\) by the identity on the newly introduced positions. The same argument covers substituting a hypothesis by a reference to another position. It extends to result equality for total pure rule operations that consume scoped arguments through application. An operation that inspects proof syntax may distinguish the proofs. This comparison does not license precomputing a replacement with effects or erasing, duplicating, or permuting its requests.

For \(J\) judgment forms, the membership declarations contain \(J(J+1)\) constructors, each with \(J\) uniform carrier types. Each concrete hypothesis reference at depth \(d\) adds \(d+1\) membership nodes. Lowering also visits all rule nodes and their ordered premise fields once, sharing context tails in memory. Validation and serialization additionally process the written type arguments and the nested context types. These folds consume the supplied proofs. A deduction executor can still use a packed aggregate when its observable and algebra admit a more efficient computation.

Closed lexical interpretation contracts

A ModelSchema also exposes the reachable ClosedInterpretationBinding records through closed_interpretations. A binding retains the lexical proof presentation’s nominal rules and axioms, the operation assigned to each constructor, and the carrier over the judgment’s declared indices. It also gives the closed effect row and the lexical identity of each required instance. Reachability includes calls made in installed authored handlers. Source lowering records the companions while it builds the ordinary folds, so model binding can reuse them when the source is unchanged. The companion holds the existing immutable presentation and adds one assignment per constructor and one identity per required instance. Schema selection walks the checked call and handler graph once, independent of the number and size of proofs the program subsequently interprets.

A companion has a standalone codec. Validation reconstructs the indexed case and compares the whole fold declaration, including its ordered rule calls and specialized result type. If the executable also has a packed query for the same presentation, validation compares the whole qualified presentation. A normalized lexical query may replace source rule weights with its own ordered production addresses. Validation checks each address against the owning presentation and rule position, and checks that any source parameter belongs to its own rule. A program that folds an explicitly supplied proof may have no such query. Its checked proof constructors and fold then establish the shape of the interpretation, while the interpretation makes no claim about weighted search or theory equations.

A packed Boolean query reaches the same ordinary interpretation through its truth table. The schema's packed_interpretations contains a packed companion for each reached invocation and retains the corresponding ordinary companion in closed_interpretations. The check reconstructs the ordered calls with their actual nominal operations and literal inputs. It checks that the native query uses the original table, sentence, and normalization mode from the wrapper. Compiler validation shares the executable indexes across companions, and inference runs use the already checked declarations.

PackedBooleanInterpretationBinding didactic-model

PackedBooleanInterpretationBinding(*, interpretation: InterpretationId = field(opaque=True, extras=OPAQUE_BY_VALUE), computation: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), query: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A portable association between a proof interpretation and its packed use.

PARAMETER DESCRIPTION
interpretation

The closed interpretation whose operation table is computed.

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

computation

The wrapper that supplies that table to the native query.

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

query

The checked lexical query receiving the table.

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

validate

validate(module: QiecModule, interpretation: ClosedInterpretationBinding) -> None

Recheck the ordinary fold and its exact packed application.

PARAMETER DESCRIPTION
module

The executable containing both interpretations.

TYPE: QiecModule

interpretation

The independently checked companion of the ordinary proof fold.

TYPE: ClosedInterpretationBinding

RAISES DESCRIPTION
RuleError

If the association is stale or the query changes the table.

KernelError

If a checked module or an operation is ill typed.

Source code in src/quivers/qiec/_packed_boolean_interpretation.py
def validate(
    self, module: QiecModule, interpretation: ClosedInterpretationBinding
) -> None:
    """Recheck the ordinary fold and its exact packed application.

    Parameters
    ----------
    module
        The executable containing both interpretations.
    interpretation
        The independently checked companion of the ordinary proof fold.

    Raises
    ------
    RuleError
        If the association is stale or the query changes the table.
    KernelError
        If a checked module or an operation is ill typed.
    """
    check_packed_boolean_bindings(
        module, validate_module(module), (interpretation,), (self,)
    )

Handling a prefixed chart proof

A category prefix can be retained in a lexical proof's indices. In the example below, parse_proofs returns an unprefix proof whose child has category Wrap(S). The authored case passes just that child to a handler around its interpretation. The handler answers the two lexical reads in premise order. The earlier exterior read uses the enclosing handler of the same instance.

The proof is data. The named helper runs its fold under the handler. An ordinary interpretation rule action receives the already interpreted premise values. Placing a handler in that action leaves the earlier premise effects outside its scope.

from quivers.dsl import loads
from quivers.qiec import run_program

source = """
import std.semiring

object Token : FinSet 2
object Result : Real 1

deduction Prefix[S = std.semiring.LogProb] : Token -> Token [start=S]
    atoms span, A, B, S, Wrap, lex
    rule combine : span(I, K, Wrap(A), lex), span(K, J, Wrap(B), lex) |- span(I, J, Wrap(S), lex)
    rule unprefix : span(I, J, Wrap(S), lex) |- span(I, J, S, lex)
    lexicon
        "x" : Wrap(A) = lex
        "y" : Wrap(B) = lex

effect Inspect
    read : Unit -> Real

instance cell : Inspect
instance random : Random

handler read_env for Inspect : Real -> Real with (setting : Real) [coverage=total, forwards=none, implementation=authored]
    return value =>
        return value
    read resumes 1 =>
        resume(setting)

interpret meaning : Prefix -> Real
    rule combine = combine_meanings
    rule unprefix = preserve
    axiom span = read_token

define combine_meanings(left : Real, right : Real) : Real !{} =
    return left + 2.0 * right

define preserve(value : Real) : Real !{} =
    return value

define read_token(token : String) : Real !{cell, random} =
    let setting <- perform cell.read()
    if token == "x" then
        let bit <- perform random.sample[Bool](site("lexical"), Bernoulli(probs=setting))
        return setting + real(bit)
    else
        return setting + 1.0

define reflect_child[a : Nat, b : Nat](child : Prefix.SpanProof(a, b, Wrap(S), lex), inside : Real) : Real !{random} =
    handle cell with read_env(inside) in
        meaning[a, b, Wrap(S), lex](child)

define reflect[i : Nat, j : Nat, c : Prefix.Term, f : Prefix.Term](proof : Prefix.SpanProof(i, j, c, f), inside : Real) : Real !{cell, random} =
    let exterior <- perform cell.read()
    case proof motive (start : Nat, end : Nat, category : Prefix.Term, form : Prefix.Term) => Real
        Prefix.rule_unprefix[a, b](child) =>
            let first <- reflect_child[a, b](child, inside)
            let second = first
            return 10.0 * exterior + first + 1.0 - (first - second) * (first - second)
        Prefix.rule_combine[a, mid, b](left, right) =>
            return 0.0
        Prefix.axiom_span[a, b, cat, lf](token) =>
            return 0.0

define close_rows(rows : Prefix.Proofs, inside : Real) : Real !{cell, random} =
    case rows motive => Real
        Prefix.proof_end =>
            return 0.0
        Prefix.proof_entry[i, j, category, form](proof, weight, tail) =>
            reflect[i, j, category, form](proof, inside)

define collect(rows : Prefix.Proofs, inside : Real, outside : Real) : Real !{random} =
    handle cell with read_env(outside) in
        close_rows(rows, inside)

program read_prefix(inside : Real, outside : Real) : Token -> Result
    let proofs = parse_proofs(Prefix, sentence, 1)
    let result <- collect(proofs, inside, outside)
    return result

export read_prefix
"""
module = loads(source).qiec
assert module is not None
result = run_program(
    module, "read_prefix",
    data={"sentence": ("x", "y"), "inside": 0.25, "outside": 4.0},
    sites={"lexical": False},
)
assert float(result.value) == 43.75

The two inner reads use the setting \(a\) with \(0<a<1\). The first also draws \(B\sim\mathrm{Bernoulli}(a)\), so its parent's value is \(3a+2+B\). The second binding in reflect copies that value. With exterior setting \(b\), the expected program return is \(10b+4a+3\). Calling the same effectful child again would make a second draw and decrease the expectation by \(2a(1-a)\).

Selecting a pre-fold action

An ordinary lexical interpretation can name one unary prefix-removal rule with pre_fold=rule(prefix, instance, handler). The rule keeps the span and form indices, and its child's category differs from the conclusion by the named prefix. Its action takes the original typed child proof. The action installs the named handler on the named instance around one call of the same interpretation on that child.

This version fixes the inner setting at 0.25. The caller passes the unprefix proof directly to meaning, and the selected action installs the handler before interpreting the child.

import std.semiring

object Token : FinSet 2
object Result : Real 1

deduction Prefix[S = std.semiring.LogProb] : Token -> Token [start=S]
    atoms span, A, B, S, Wrap, lex
    rule combine : span(I, K, Wrap(A), lex), span(K, J, Wrap(B), lex) |- span(I, J, Wrap(S), lex)
    rule unprefix : span(I, J, Wrap(S), lex) |- span(I, J, S, lex)
    lexicon
        "x" : Wrap(A) = lex
        "y" : Wrap(B) = lex

effect Inspect
    read : Unit -> Real

instance cell : Inspect
instance random : Random

handler read_env for Inspect : Real -> Real with (setting : Real) [coverage=total, forwards=none, implementation=authored]
    return value =>
        return value
    read resumes 1 =>
        resume(setting)

interpret meaning [pre_fold=unprefix(Wrap, cell, read_env)] : Prefix -> Real
    rule combine = combine_meanings
    rule unprefix = close_meaning
    axiom span = read_token

define combine_meanings(left : Real, right : Real) : Real !{} =
    return left + 2.0 * right

define read_token(token : String) : Real !{cell, random} =
    let setting <- perform cell.read()
    if token == "x" then
        let bit <- perform random.sample[Bool](site("lexical"), Bernoulli(probs=setting))
        return setting + real(bit)
    else
        return setting + 1.0

define close_meaning[a : Nat, b : Nat](child : Prefix.SpanProof(a, b, Wrap(S), lex)) : Real !{random} =
    handle cell with read_env(0.25) in
        meaning[a, b, Wrap(S), lex](child)

define collect(rows : Prefix.Proofs, outside : Real) : Real !{random} =
    handle cell with read_env(outside) in
        case rows motive => Real
            Prefix.proof_end =>
                return 0.0
            Prefix.proof_entry[i, j, category, form](proof, weight, tail) =>
                let exterior <- perform cell.read()
                let first <- meaning[i, j, category, form](proof)
                return 10.0 * exterior + first + 1.0

program read_prefix(outside : Real) : Token -> Result
    let proofs = parse_proofs(Prefix, sentence, 1)
    let result <- collect(proofs, outside)
    return result

export read_prefix

This form checks literal handler arguments, total coverage, one tail resumption per clause, and an identity return. The scope removes only the declared lexical instance from the action's row. The generic fold retains the union of the rows of its reachable constructors. Its checked companion retains the chosen rule, effect instance, and handler identities. It rechecks the unchanged child call when restored.

Binding a value across two lexical premises

The same declaration accepts a contiguous binary rule that removes the named prefix from its right premise and preserves the result form. For instance, pre_fold=combine(Wrap, cell, thread) can interpret a rule with premises span(I,K,Intro,lex) and span(K,J,Wrap(S),lex) and conclusion span(I,J,S,lex).

The action takes the left premise's interpreted value followed by the unchanged indexed proof for the right premise. The fold evaluates the left premise once. The action installs the named handler with that value as its only argument and interprets the right proof once inside the installation. The right premise's requests reach that handler. Requests before the installation and after its return keep their enclosing scope. The unary form continues to use literal handler arguments.

The checked companion reconstructs both calls and verifies the exact handler and instance identities. A copied result can be read more than once, while reinterpreting an effectful premise would execute its requests again. The existing packed-proof provider is available on the native execution path.

Binding

Terms of a structural signature use de Bruijn indices. Substitution is a simultaneous substitution: the innermost variables go to replacements and the rest are shifted. substitute applies it under binders by lifting it, so no replacement is captured, and then composes two of them. The identity, composition and renaming laws are checked, and substitution agrees with textbook capture-avoiding substitution on named terms. term_derivation reads a term as an open derivation whose holes are its free variables, and substitution of terms corresponds to substitution of derivations.

Checking derivations

check_derivation checks a derivation with the QIEC checker: each node becomes a constructor value of its rule with the rule's telescope instantiated at the node's binding, and each hypothesis a local of its item's type. A premise with hypotheses is checked in the context extended by them, since QIEC has no function values; in its parent it stands for a local of its type.

Equations

A presentation states the Equations between open derivations it intends an interpretation to preserve. check_equation folds both sides at given values of the context. It returns a tested claim, since finitely many cases can refute preservation and cannot establish it, and raises EquationFails at a counterexample. A proved or decided claim needs an argument or a decision procedure. Storing contexts as tuples licenses no equation: exchange, weakening and contraction hold only when the structure declares them.

Cost

PRESENTATION_WORK counts construction and an unscoped closed fold separately. Let \(P\) count the words in the presentation and its lowered declarations by occurrence. A premise with an empty index tuple, each binder hypothesis, and each axiom value field contributes to \(P\). Assume names and scalar indices fit in words and that hash-table lookups take expected time after accounting for structural keys. Pattern validation scans each constructor occurrence in argument order. The scan checks all summands of an index sum against the incoming binding before adding any new names from that sum. Lowering and indexing scan the declarations, and analysis also sorts the lists of shared variables. With \(V\) for the time and \(W\) for the storage of the existing model and QIEC validators and the resolved registry, the construction bound is \(O(1+P\log(1+P)+V)\) time and \(O(1+P+W)\) space. Construction checks the lowered declarations. First use resolves and caches the registry and indexes. Subsequent folds reuse them. Optimality of these bounds remains open.

Matching reads the pattern and may compare a previously bound argument with a new ground term. If the pattern has \(M\) nodes and those comparisons inspect \(E\) ground nodes in total, matching takes expected \(O(M+E)\) time. An interning lookup hashes the supplied ground arguments and can also compare them structurally. A returned item reuses its own cached hash after its first use as a key. Encoding expands the serialized fields by occurrence. For a wire representation of \(S\) words, encoding uses \(O(S)\) time and space with bounded-size JSON object wrappers. Decoding also runs the constructors' validators, including the presentation check.

A fold of a supplied unscoped proof with \(N\) nodes and \(B\) total binding entries uses \(O(N+B)\) traversal work and space, counting each premise occurrence once. This bound assumes bounded scalar rule and axiom operations. If their first-order reverse rules and saved values also use bounded work and space per occurrence, one forward and reverse pass takes \(O(N+B)\) work and space at each refit. A scoped fold additionally pays for ground hypotheses, context extension, and each application of a suspended premise. Renaming walks the supplied derivation. Substitution also walks each replacement that needs to shift under a binder, once per use that requires the shift. Its work depends on these visited occurrences, the total context entries compared or copied, and the sizes of the ground hypotheses and newly built records. A replacement that is inserted unchanged can share its object. A later fold or serialization still sees every occurrence.

Extension points

Joint outputs (a rule with several conclusions), negative premises, and coinductive or productive interpretations are not part of this presentation. A joint output can be stated today as a product judgment form; negative premises need a stratification that a plan would check; a productive interpretation needs a final coalgebra in place of the initial algebra. None is claimed, and no greatest generality is claimed for the presentation.

rules

Rule presentations: typed judgments, rules, and their derivations.

A rule presentation (RulePresentation) states a deduction system as QIEC declarations. Each judgment is an indexed family, and a judgment instance is an application of the family to index arguments. A rule is a constructor of its conclusion's family whose fields are its premise judgments in order, followed by the values it carries; its telescope holds its typed schematic variables. An axiom slot is a constructor with no premises, and each input axiom is an occurrence of a slot with its own identity. Proofs are thus an inductive family, and the QIEC checker that checks every other declaration checks the presentation: declarations lowers it, and construction runs validate_module on the result.

For the presentation with input occurrences A_j the derivations of a judgment j are the initial algebra of the polynomial functor

(F_A X)_j = A_j + sum over rules r : (j_1, ..., j_n) -> j of
            X_{j_1} x ... x X_{j_n},

and a fold of a derivation by an interpretation is the unique map out of it. That is a description of the semantics; nothing here materializes every derivation except ReferenceInterpretation, which is an oracle for small systems and not an executor.

ItemTable reuses a single item for equal ground arguments. A presentation is checked at construction. Its indexes (rules by conclusion family, rules by premise family and position, the family dependency graph and its components) and resolved registry are cached on first use.

ORDERED module-attribute

ORDERED = ContextStructure()

No structural rule: every variable used once, in order (Lambek).

LINEAR module-attribute

LINEAR = ContextStructure(exchange=True)

Exchange only: every variable used exactly once.

AFFINE module-attribute

AFFINE = ContextStructure(exchange=True, weakening=True)

Exchange and weakening: every variable used at most once.

RELEVANT module-attribute

RELEVANT = ContextStructure(exchange=True, contraction=True)

Exchange and contraction: every variable used at least once.

CARTESIAN module-attribute

CARTESIAN = ContextStructure(exchange=True, weakening=True, contraction=True)

Every structural rule.

PRESENTATION_PROTOCOL module-attribute

PRESENTATION_PROTOCOL = 'quivers.rules'

The source protocol of the module a presentation lowers to.

PRESENTATION_WORK module-attribute

PRESENTATION_WORK = ComplexityClaim(query='presentation construction with cold indexes and an unscoped closed fold', parameters=(ComplexityParameter(name='P', meaning='words in presentation and lowered declarations by occurrence, including families, premises, hypotheses, telescopes, axiom and rule value fields, and index and type syntax'), ComplexityParameter(name='V', meaning='work of existing validation routines'), ComplexityParameter(name='W', meaning='storage of existing validation routines and registry'), ComplexityParameter(name='N', meaning='nodes of the unscoped derivation'), ComplexityParameter(name='B', meaning='total binding entries across the visited nodes')), model=WORD_RAM_EXPECTED_HASHING, bounds=(ComplexityBound(phase=Phase.CONSTRUCTION, resource='time', expression='1 + P * log(1 + P) + V', status=_BUILD_OPTIMALITY), ComplexityBound(phase=Phase.CONSTRUCTION, resource='space', expression='1 + P + W', status=_BUILD_OPTIMALITY), ComplexityBound(phase=Phase.EXECUTION, resource='time', expression='N + B', status=_FOLD_OPTIMALITY), ComplexityBound(phase=Phase.EXECUTION, resource='space', expression='N + B', status=_FOLD_OPTIMALITY), ComplexityBound(phase=Phase.DIFFERENTIATION, resource='time', expression='N + B', status=_FOLD_OPTIMALITY), ComplexityBound(phase=Phase.DIFFERENTIATION, resource='space', expression='N + B', status=_FOLD_OPTIMALITY), ComplexityBound(phase=Phase.REFIT, resource='time', expression='N + B', status=_FOLD_OPTIMALITY), ComplexityBound(phase=Phase.REFIT, resource='space', expression='N + B', status=_FOLD_OPTIMALITY)), conditions=('construction includes declaration lowering and the first use of the registry and indexes; the built objects are reused', 'indices and names fit in words and hash-table operations take expected time apart from structural key traversal', 'the fold runs on a supplied closed derivation without scoped premises', 'each rule and axiom operation does bounded scalar work, with bounded first-order reverse work and tape per operation', 'a refit repeats this fold and its first reverse pass at fixed structure'))

The cost of building a presentation and folding one unscoped derivation.

Ground

Ground = int | str | tuple[Ground, ...]

A ground index value: a natural number, a nullary constructor of a closed sort by name, or a constructor application as (name, *arguments).

Binding

Binding = dict[str, Ground]

Values of the schematic variables of a rule.

ProofNode

ProofNode = Derivation | Hole

A derivation or an open hypothesis.

Blocks

Blocks = tuple[tuple[Item, ...], tuple[Item, ...]]

The left and right hypotheses of one premise.

PremiseValue

PremiseValue = B | Scoped[B]

The value an operation receives for one premise.

Operation

Operation = Callable[[Derivation, tuple[PremiseValue[B], ...]], B]

The value of a rule application from its derivation node and the values of its premises, in premise order.

RuleError

Bases: ValueError

A rule presentation is ill-formed.

JudgmentDecl didactic-model

JudgmentDecl(*, id: FamilyId = field(opaque=True, extras=OPAQUE_BY_VALUE), name: str, indices: Telescope = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A judgment form: a family indexed by its arguments.

PARAMETER DESCRIPTION
id

The family's identity.

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

name

Its name.

TYPE: str

indices

Its arguments, each an index binder.

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

Judgment didactic-model

Judgment(*, family: FamilyId = field(opaque=True, extras=OPAQUE_BY_VALUE), arguments: tuple[IndexTerm, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A judgment instance: a family applied to index arguments.

PARAMETER DESCRIPTION
family

The judgment form.

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

arguments

One per index of the form; they may mention the schematic variables of the enclosing rule.

TYPE: tuple of IndexTerm DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

Premise didactic-model

Premise(*, judgment: Judgment = field(opaque=True, extras=OPAQUE_BY_VALUE), before: tuple[Judgment, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), after: tuple[Judgment, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

One premise of a rule, in its position.

The premise is derived in the context before + context + after. In an ordered context the two sides differ: in the Lambek calculus a hypothesis on the right introduces A / B and one on the left introduces B \ A.

PARAMETER DESCRIPTION
judgment

What the premise has to derive.

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

before

Hypotheses the premise may use that are inserted at the left of the rule's context, outermost first.

TYPE: tuple of Judgment DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

after

Hypotheses inserted at its right, outermost first.

TYPE: tuple of Judgment DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

hypotheses property

hypotheses: tuple[Judgment, ...]

Every hypothesis of the premise, left block then right block.

RETURNS DESCRIPTION
tuple of Judgment

before + after.

SideCondition didactic-model

SideCondition(*, computation: ComputationId = field(opaque=True, extras=OPAQUE_BY_VALUE), arguments: tuple[str, ...] = ())

Bases: QiecModel

A checked QIEC computation a rule instance has to satisfy.

PARAMETER DESCRIPTION
computation

A pure computation of the presentation's conditions with no telescope that returns Bool.

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

arguments

The rule's schematic variables or value fields passed to it, one per parameter. A natural-number variable is passed as an Int. A captured source guard reads closed matched terms at the deduction's nominal item type. A plain ground condition can read a nullary constructor of a closed sort as a String.

TYPE: tuple of str DEFAULT: ()

ComputedRuleWeight didactic-model

ComputedRuleWeight(*, operation: str)

Bases: QiecModel

A rule weight supplied by a named checked computation.

The presentation records the requirement. Checked source lowers each application to a call on the rule telescope's bound fields. An executor without that lowering cannot give the rule a numerical weight.

PARAMETER DESCRIPTION
operation

The name of the computation in the owning source module.

TYPE: str

Rule didactic-model

Rule(*, id: ConstructorId = field(opaque=True, extras=OPAQUE_BY_VALUE), name: str, telescope: Telescope = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), premises: tuple[Premise, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), conclusion: Judgment = field(opaque=True, extras=OPAQUE_BY_VALUE), values: tuple[FieldDef, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), side_condition: SideCondition | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), weight: ParameterId | ComputedRuleWeight | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

An inference rule: a constructor of its conclusion's proof family.

The premise order is part of the rule: an interpretation receives the values of the premises in this order, and no executor may permute them unless the interpretation declares that it may.

PARAMETER DESCRIPTION
id

The rule's identity, which is its constructor's.

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

name

Its name.

TYPE: str

telescope

Its typed schematic variables.

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

premises

Its premises, in order.

TYPE: tuple of Premise DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

conclusion

Its conclusion.

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

values

Values the rule carries beside its premises, such as the label of a leaf; their types are value types.

TYPE: tuple of FieldDef DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

side_condition

A checked computation each instance has to satisfy.

TYPE: SideCondition or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

weight

The parameter or checked computation that weights each application, or None for the unit weight.

TYPE: ParameterId, ComputedRuleWeight, or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

arity property

arity: int

The number of premises.

RETURNS DESCRIPTION
int

The arity.

AxiomSlot didactic-model

AxiomSlot(*, id: ConstructorId = field(opaque=True, extras=OPAQUE_BY_VALUE), name: str, telescope: Telescope = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), judgment: Judgment = field(opaque=True, extras=OPAQUE_BY_VALUE), values: tuple[FieldDef, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), weight: ParameterId | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A kind of input axiom: a rule with no premises filled at run time.

Each input is an AxiomOccurrence of a slot with its own identity, so two equal inputs are two axioms.

PARAMETER DESCRIPTION
id

The slot's identity, which is its constructor's.

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

name

Its name.

TYPE: str

telescope

Its schematic variables.

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

judgment

The judgment an occurrence derives.

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

values

Values an occurrence carries.

TYPE: tuple of FieldDef DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

weight

The parameter that weights every occurrence, or None when each occurrence brings its own weight.

TYPE: ParameterId or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

Item didactic-model

Item(*, family: FamilyId = field(opaque=True, extras=OPAQUE_BY_VALUE), arguments: tuple[Ground, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A ground judgment instance: a family with ground arguments.

An item is a conclusion, not a proof: one item may have many derivations. ItemTable interns items so that equal items are one object.

PARAMETER DESCRIPTION
family

The judgment form.

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

arguments

Its ground arguments.

TYPE: tuple of Ground DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

ItemTable

ItemTable()

Intern equal ground arguments as one item.

Each lookup hashes the supplied ground arguments and may compare them structurally. The returned item compares to itself by identity and saves its own hash on first hashing.

Source code in src/quivers/qiec/rules.py
def __init__(self) -> None:
    self._items: dict[tuple[FamilyId, tuple[Ground, ...]], Item] = {}

intern

intern(family: FamilyId, arguments: tuple[Ground, ...]) -> Item

The one item of a family with these arguments.

PARAMETER DESCRIPTION
family

The judgment form.

TYPE: FamilyId

arguments

The ground arguments.

TYPE: tuple of Ground

RETURNS DESCRIPTION
Item

The same object for equal family and arguments.

Source code in src/quivers/qiec/rules.py
def intern(self, family: FamilyId, arguments: tuple[Ground, ...]) -> Item:
    """The one item of a family with these arguments.

    Parameters
    ----------
    family : FamilyId
        The judgment form.
    arguments : tuple of Ground
        The ground arguments.

    Returns
    -------
    Item
        The same object for equal family and arguments.
    """
    key = (family, arguments)
    item = self._items.get(key)
    if item is None:
        item = Item(family=family, arguments=arguments)
        self._items[key] = item
    return item

__len__

__len__() -> int

The number of distinct items.

RETURNS DESCRIPTION
int

The count.

Source code in src/quivers/qiec/rules.py
def __len__(self) -> int:
    """The number of distinct items.

    Returns
    -------
    int
        The count.
    """
    return len(self._items)

AxiomOccurrence didactic-model

AxiomOccurrence(*, slot: ConstructorId = field(opaque=True, extras=OPAQUE_BY_VALUE), occurrence: OccurrenceId = field(opaque=True, extras=OPAQUE_BY_VALUE), binding: tuple[tuple[str, Ground], ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), values: tuple[str | int | float | bool, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

One input axiom: an occurrence of a slot at ground arguments.

PARAMETER DESCRIPTION
slot

The slot.

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

occurrence

The identity of this occurrence.

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

binding

Values of the slot's schematic variables, by name.

TYPE: tuple of tuple of str and Ground DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

values

Values of the slot's value fields, in order.

TYPE: tuple of str or int or float or bool DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

Hole didactic-model

Hole(*, index: int, item: Item = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['hole'] = 'hole')

Bases: QiecModel

An open hypothesis in a derivation: a variable of its context.

PARAMETER DESCRIPTION
index

Its de Bruijn index in the context where it occurs: 0 is the innermost hypothesis.

TYPE: int

item

The item it assumes.

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

tag

Always "hole".

TYPE: str DEFAULT: 'hole'

Derivation didactic-model

Derivation(*, constructor: ConstructorId = field(opaque=True, extras=OPAQUE_BY_VALUE), item: Item = field(opaque=True, extras=OPAQUE_BY_VALUE), binding: tuple[tuple[str, Ground], ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), values: tuple[str | int | float | bool, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), occurrence: OccurrenceId | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), premises: tuple[Derivation | Hole, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A derivation tree: a proof of an item, not the item.

PARAMETER DESCRIPTION
constructor

The rule or axiom slot at the root.

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

item

The item it proves.

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

binding

Values of the rule's schematic variables.

TYPE: tuple of tuple of str and Ground DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

values

Values of the rule's value fields.

TYPE: tuple of str or int or float or bool DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

occurrence

The input occurrence, for an axiom.

TYPE: OccurrenceId or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

premises

Derivations of the premises, in order; a hole is an open hypothesis.

TYPE: tuple of Derivation or Hole DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

size

size() -> int

The number of nodes, holes included.

RETURNS DESCRIPTION
int

The nodes of the tree, counted without recursion.

Source code in src/quivers/qiec/rules.py
def size(self) -> int:
    """The number of nodes, holes included.

    Returns
    -------
    int
        The nodes of the tree, counted without recursion.
    """
    count = 0
    stack: list[Derivation | Hole] = [self]
    while stack:
        node = stack.pop()
        count += 1
        if isinstance(node, Derivation):
            stack.extend(node.premises)
    return count

MatchError

Bases: RuleError

A pattern cannot be matched or evaluated with the variables bound.

FamilyComponent didactic-model

FamilyComponent(*, families: tuple[FamilyId, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), cyclic: bool, linear: bool)

Bases: QiecModel

A strongly connected component of the family dependency graph.

PARAMETER DESCRIPTION
families

Its families.

TYPE: tuple of FamilyId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

cyclic

Whether some rule concludes a family of the component from a premise in it.

TYPE: bool

linear

Whether every such rule has at most one premise in the component.

TYPE: bool

PresentationAnalysis didactic-model

PresentationAnalysis(*, rules: int, axiom_slots: int, families: int, max_arity: int, size: int, components: tuple[FamilyComponent, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), join_variables: tuple[tuple[ConstructorId, tuple[str, ...]], ...] = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

What an executor needs to know of a presentation to plan for it.

PARAMETER DESCRIPTION
rules

The number of rules.

TYPE: int

axiom_slots

The number of axiom slots.

TYPE: int

families

The number of judgment forms.

TYPE: int

max_arity

The largest number of premises of a rule.

TYPE: int

size

The number of index-term nodes over all judgments of all rules and slots, which bounds the cost of matching every rule once.

TYPE: int

components

The components of the dependency graph, premises before conclusions.

TYPE: tuple of FamilyComponent DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

join_variables

For each rule, the variables shared by two or more premises, which are the attributes its join is on.

TYPE: tuple of tuple of ConstructorId and tuple of str DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

recursion

recursion() -> Recursion

The weakest recursion contract the family structure guarantees.

The family graph over-approximates the derived hypergraph: if no family depends on itself no item does.

RETURNS DESCRIPTION
Recursion

Acyclic when no component is cyclic; LinearCyclic when every cyclic component is linear; MonotonePolynomial otherwise.

Source code in src/quivers/qiec/rules.py
def recursion(self) -> Recursion:
    """The weakest recursion contract the family structure guarantees.

    The family graph over-approximates the derived hypergraph: if no
    family depends on itself no item does.

    Returns
    -------
    Recursion
        `Acyclic` when no component is cyclic; `LinearCyclic` when
        every cyclic component is linear; `MonotonePolynomial`
        otherwise.
    """
    cyclic = [component for component in self.components if component.cyclic]
    if not cyclic:
        return Acyclic()
    if all(component.linear for component in cyclic):
        return LinearCyclic()
    return MonotonePolynomial()

ContextStructure didactic-model

ContextStructure(*, exchange: bool = False, weakening: bool = False, contraction: bool = False)

Bases: QiecModel

The structural rules a context admits, as declared data.

A use of the variables of a context, read from left to right, is licensed when it arises from the context in order by the declared rules: exchange permutes uses, weakening drops a variable, and contraction uses one twice. Nothing is inferred from how a context is stored.

PARAMETER DESCRIPTION
exchange

Whether variables may be used out of order.

TYPE: bool DEFAULT: False

weakening

Whether a variable may go unused.

TYPE: bool DEFAULT: False

contraction

Whether a variable may be used more than once.

TYPE: bool DEFAULT: False

admits

admits(required: ContextStructure) -> bool

Whether every rule another structure needs is admitted here.

PARAMETER DESCRIPTION
required

The rules a derivation uses.

TYPE: ContextStructure

RETURNS DESCRIPTION
bool

True when each rule used is admitted.

Source code in src/quivers/qiec/rules.py
def admits(self, required: ContextStructure) -> bool:
    """Whether every rule another structure needs is admitted here.

    Parameters
    ----------
    required : ContextStructure
        The rules a derivation uses.

    Returns
    -------
    bool
        True when each rule used is admitted.
    """
    return (
        (self.exchange or not required.exchange)
        and (self.weakening or not required.weakening)
        and (self.contraction or not required.contraction)
    )

RulePresentation didactic-model

RulePresentation(*, id: PresentationId = field(opaque=True, extras=OPAQUE_BY_VALUE), name: str, index_sorts: tuple[UserIndexSort, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), judgments: tuple[JudgmentDecl, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), rules: tuple[Rule, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), axioms: tuple[AxiomSlot, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), conditions: tuple[NamedComputation, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), structure: ContextStructure = field(default=ORDERED, opaque=True, extras=OPAQUE_BY_VALUE), equations: tuple[Equation, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A deduction system stated as QIEC declarations.

Construction validates the presentation once: the rules are well scoped and range restricted, and the lowered families, constructors and side conditions pass validate_module. The indexes an executor reads are built once, on first use.

PARAMETER DESCRIPTION
id

The presentation's identity.

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

name

Its name, which is the name of the module it lowers to.

TYPE: str

index_sorts

The closed sorts its judgments are indexed by.

TYPE: tuple of UserIndexSort DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

judgments

Its judgment forms.

TYPE: tuple of JudgmentDecl DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

rules

Its rules, in order.

TYPE: tuple of Rule DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

axioms

Its axiom slots.

TYPE: tuple of AxiomSlot DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

conditions

The computations its side conditions name.

TYPE: tuple of NamedComputation DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

structure

The structural rules its contexts admit. The default admits none: exchange, weakening and contraction are never inferred.

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

equations

The equations between open derivations it intends an interpretation to preserve.

TYPE: tuple of Equation DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

RAISES DESCRIPTION
ValidationError

If an identity or name repeats, a judgment names an unknown form or has the wrong number of arguments, a variable of a conclusion or side condition is not bound by the premises or the telescope, a pattern cannot be matched deterministically, a side condition is not a pure Bool computation of matching parameters, or the lowered module fails the QIEC checker.

computed_weight_rules cached property

computed_weight_rules: tuple[Rule, ...]

Rules requiring an executable, telescope-dependent weight.

RETURNS DESCRIPTION
tuple of Rule

The rules in presentation order.

constructors_by_id cached property

constructors_by_id: Mapping[ConstructorId, Rule | AxiomSlot]

Every rule and slot by its identity.

RETURNS DESCRIPTION
Mapping[ConstructorId, Rule or AxiomSlot]

Read-only; built once.

judgments_by_id cached property

judgments_by_id: Mapping[FamilyId, JudgmentDecl]

Every judgment form by its identity.

RETURNS DESCRIPTION
Mapping[FamilyId, JudgmentDecl]

Read-only; built once.

conditions_by_id cached property

conditions_by_id: Mapping[ComputationId, NamedComputation]

Every side condition's computation by its identity.

RETURNS DESCRIPTION
Mapping[ComputationId, NamedComputation]

Read-only; built once.

registry cached property

registry: KernelRegistry

The QIEC registry of the lowered module, resolved once.

RETURNS DESCRIPTION
KernelRegistry

The registry derivations are checked against.

rules_by_conclusion cached property

rules_by_conclusion: Mapping[FamilyId, tuple[Rule, ...]]

The rules that conclude each judgment form.

RETURNS DESCRIPTION
Mapping[FamilyId, tuple of Rule]

Read-only; built once.

rules_by_premise cached property

rules_by_premise: Mapping[FamilyId, tuple[tuple[Rule, int], ...]]

The rules and premise positions that each judgment form can fill.

RETURNS DESCRIPTION
Mapping[FamilyId, tuple of tuple of Rule and int]

Read-only; built once.

analysis cached property

Sizes, components and join variables, for planning.

RETURNS DESCRIPTION
PresentationAnalysis

Built once in time linear in the presentation.

declarations

declarations() -> tuple[tuple[FamilyDecl, ...], tuple[ConstructorDecl, ...]]

The QIEC families and constructors of the presentation.

Each judgment form is a closed family whose constructors are the rules and slots that conclude it. A rule's fields are its premises, named premise0, premise1, ..., then its value fields; a premise's field type is its judgment's family applied to the premise arguments.

RETURNS DESCRIPTION
tuple of tuple of FamilyDecl and tuple of ConstructorDecl

The families and the constructors.

Source code in src/quivers/qiec/rules.py
def declarations(
    self,
) -> tuple[tuple[FamilyDecl, ...], tuple[ConstructorDecl, ...]]:
    """The QIEC families and constructors of the presentation.

    Each judgment form is a closed family whose constructors are the
    rules and slots that conclude it. A rule's fields are its premises,
    named ``premise0``, ``premise1``, ..., then its value fields; a
    premise's field type is its judgment's family applied to the
    premise arguments.

    Returns
    -------
    tuple of tuple of FamilyDecl and tuple of ConstructorDecl
        The families and the constructors.
    """
    return self._declarations

to_module

to_module() -> QiecModule

The QIEC module of the presentation.

RETURNS DESCRIPTION
QiecModule

Its index sorts, families, constructors and conditions.

RAISES DESCRIPTION
RuleError

If term guards do not agree on their owned item declarations.

Source code in src/quivers/qiec/rules.py
def to_module(self) -> QiecModule:
    """The QIEC module of the presentation.

    Returns
    -------
    QiecModule
        Its index sorts, families, constructors and conditions.

    Raises
    ------
    RuleError
        If term guards do not agree on their owned item declarations.
    """
    families, constructors = self.declarations()
    if self.conditions:
        from quivers.qiec._deduction_guards import _TermGuard

        captures = tuple(
            guard for guard in self.conditions if isinstance(guard, _TermGuard)
        )
        if captures:
            first = captures[0]
            if first.item_family.name != member_name(self.name, "Item") or any(
                guard.item_family != first.item_family
                or guard.item_constructors != first.item_constructors
                for guard in captures[1:]
            ):
                raise RuleError("term guards require one shared owned item family")
            families = (*families, first.item_family)
            constructors = (*constructors, *first.item_constructors)
    return QiecModule(
        module=self.name,
        source_protocol=PRESENTATION_PROTOCOL,
        index_sorts=self.index_sorts,
        families=families,
        constructors=constructors,
        computations=self.conditions,
    )

StructureError

Bases: RuleError

A derivation uses its context in a way the structure does not admit.

OpenDerivation didactic-model

OpenDerivation(*, context: tuple[Item, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), body: Derivation | Hole = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A derivation with open hypotheses: an arrow of the free multicategory.

It derives its body's item from the items of its context, in order. Its holes refer to the context by de Bruijn index, counted from the innermost (last) item, and inside a premise with hypotheses the context is extended by them.

PARAMETER DESCRIPTION
context

The hypotheses, outermost first.

TYPE: tuple of Item DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

body

The derivation.

TYPE: Derivation or Hole DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

item property

item: Item

The item derived.

RETURNS DESCRIPTION
Item

The body's item.

Equation didactic-model

Equation(*, law: Law = field(opaque=True, extras=OPAQUE_BY_VALUE), left: OpenDerivation = field(opaque=True, extras=OPAQUE_BY_VALUE), right: OpenDerivation = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

An equation between two open derivations an interpretation may preserve.

PARAMETER DESCRIPTION
law

The law the equation is an instance of.

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

left

One side.

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

right

The other side, with the same context and item.

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

RAISES DESCRIPTION
ValidationError

If the sides differ in context or item.

InterpretationDecl didactic-model

InterpretationDecl(*, id: InterpretationId = field(opaque=True, extras=OPAQUE_BY_VALUE), presentation: PresentationId = field(opaque=True, extras=OPAQUE_BY_VALUE), operations: tuple[tuple[ConstructorId, ComputationId], ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), preserves: tuple[LawClaim, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A serializable interpretation: a QIEC computation per rule and slot.

PARAMETER DESCRIPTION
id

Its identity.

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

presentation

The presentation it interprets.

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

operations

The computation of each rule and slot.

TYPE: tuple of tuple of ConstructorId and ComputationId DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

preserves

The equations of the presentation it claims to preserve, each with its evidence.

TYPE: tuple of LawClaim DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

Scoped didactic-model

Scoped(*, apply: Callable[[tuple[B, ...]], B] = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

The value of a premise derived under hypotheses.

It is a function of the hypotheses' values, the premise's left block then its right block, each outermost first: the context-indexed reading of a premise. Calling it folds the premise with them bound.

PARAMETER DESCRIPTION
apply

The function.

TYPE: Callable[[tuple of B], B] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

__call__

__call__(hypotheses: tuple[V, ...]) -> V

Fold the premise with values for its hypotheses.

PARAMETER DESCRIPTION
hypotheses

Their values, outermost first.

TYPE: tuple of V

RETURNS DESCRIPTION
V

The premise's value.

Source code in src/quivers/qiec/rules.py
def __call__[V](self: Scoped[V], hypotheses: tuple[V, ...]) -> V:
    """Fold the premise with values for its hypotheses.

    Parameters
    ----------
    hypotheses : tuple of V
        Their values, outermost first.

    Returns
    -------
    V
        The premise's value.
    """
    return self.apply(hypotheses)

HostInterpretation didactic-model

HostInterpretation(*, presentation: RulePresentation = field(opaque=True, extras=OPAQUE_BY_VALUE), operations: Mapping[ConstructorId, Operation[B]] = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

An interpretation by host functions, one per rule and slot.

A premise without hypotheses reaches its rule's operation as a value; a premise with hypotheses reaches it as a function from the values of the hypotheses, so a binder decides what its variables stand for.

PARAMETER DESCRIPTION
presentation

The presentation.

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

operations

The operation of each rule and axiom slot. An axiom's operation receives no premise values.

TYPE: Mapping[ConstructorId, Operation] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

fold

fold(derivation: Derivation) -> V

The value of a closed derivation: the unique map out of the initial algebra.

PARAMETER DESCRIPTION
derivation

The derivation.

TYPE: Derivation

RETURNS DESCRIPTION
V

Its value.

Source code in src/quivers/qiec/rules.py
def fold[V](self: HostInterpretation[V], derivation: Derivation) -> V:
    """The value of a closed derivation: the unique map out of the initial algebra.

    Parameters
    ----------
    derivation : Derivation
        The derivation.

    Returns
    -------
    V
        Its value.
    """
    return self.fold_open(OpenDerivation(body=derivation), ())

fold_open

fold_open(derivation: OpenDerivation, environment: tuple[V, ...]) -> V

The value of an open derivation at values of its hypotheses.

The cost is one operation per node; the traversal uses an explicit stack, and a premise under hypotheses is folded when its rule's operation applies it.

PARAMETER DESCRIPTION
derivation

The derivation.

TYPE: OpenDerivation

environment

A value per hypothesis of its context, outermost first.

TYPE: tuple of V

RETURNS DESCRIPTION
V

Its value.

RAISES DESCRIPTION
RuleError

If the environment does not match the context, or a hole lies outside it.

Source code in src/quivers/qiec/rules.py
def fold_open[V](
    self: HostInterpretation[V],
    derivation: OpenDerivation,
    environment: tuple[V, ...],
) -> V:
    """The value of an open derivation at values of its hypotheses.

    The cost is one operation per node; the traversal uses an explicit
    stack, and a premise under hypotheses is folded when its rule's
    operation applies it.

    Parameters
    ----------
    derivation : OpenDerivation
        The derivation.
    environment : tuple of V
        A value per hypothesis of its context, outermost first.

    Returns
    -------
    V
        Its value.

    Raises
    ------
    RuleError
        If the environment does not match the context, or a hole lies
        outside it.
    """
    if len(environment) != len(derivation.context):
        raise RuleError("one value per hypothesis")
    return self._evaluate(derivation.body, environment)

EquationFails

Bases: RuleError

An interpretation gives the two sides of an equation different values.

CyclicDerivations

Bases: RuleError

A goal has infinitely many derivations and no height bound was given.

ReferenceInterpretation

ReferenceInterpretation(presentation: RulePresentation, axioms: Sequence[AxiomOccurrence], *, item_limit: int = 10000)

Every derivation of a small system, listed explicitly.

This is an oracle: it grounds every rule against every item, lists every derivation of a goal, and folds each one. Its cost is exponential in general. Executors are planned from the presentation's analysis and checked against this.

PARAMETER DESCRIPTION
presentation

The presentation.

TYPE: RulePresentation

axioms

The input occurrences.

TYPE: Sequence of AxiomOccurrence

item_limit

The most items it may derive before refusing.

TYPE: int DEFAULT: 10000

Source code in src/quivers/qiec/rules.py
def __init__(
    self,
    presentation: RulePresentation,
    axioms: Sequence[AxiomOccurrence],
    *,
    item_limit: int = 10_000,
) -> None:
    self.presentation = presentation
    self.axioms = tuple(axioms)
    self.items = ItemTable()
    self.item_limit = item_limit
    self._leaves: dict[Item, list[Derivation]] = {}
    self._instances: dict[Item, list[tuple[Rule, Binding, tuple[Item, ...]]]] = {}
    if any(
        premise.hypotheses
        for rule in presentation.rules
        for premise in rule.premises
    ):
        raise RuleError(
            "the reference interpretation lists closed derivations; a premise "
            "with hypotheses is derived open, by an open derivation"
        )
    self._ground()

item

item(family: FamilyId, arguments: tuple[Ground, ...]) -> Item

The interned item of a family with arguments.

PARAMETER DESCRIPTION
family

The judgment form.

TYPE: FamilyId

arguments

The arguments.

TYPE: tuple of Ground

RETURNS DESCRIPTION
Item

The item.

Source code in src/quivers/qiec/rules.py
def item(self, family: FamilyId, arguments: tuple[Ground, ...]) -> Item:
    """The interned item of a family with arguments.

    Parameters
    ----------
    family : FamilyId
        The judgment form.
    arguments : tuple of Ground
        The arguments.

    Returns
    -------
    Item
        The item.
    """
    return self.items.intern(family, arguments)

observe

observe(goal: Item, weight: Callable[[Derivation], N], value: Callable[[Derivation], N], observer: Callable[[N], N], zero: N, *, height: int | None = None) -> N

The weighted sum over derivations of an observer of their values.

This is the observable sum_d w(d) h(fold(d)) computed by its definition: the observer is applied to each derivation's value and never to an aggregate, so it may be nonlinear.

PARAMETER DESCRIPTION
goal

The item.

TYPE: Item

weight

The weight of one node of a derivation; a derivation's weight is the product over its nodes.

TYPE: Callable[[Derivation], N]

value

The value of a whole derivation, usually a fold.

TYPE: Callable[[Derivation], N]

observer

Any function of one value.

TYPE: Callable[[N], N]

zero

The empty sum.

TYPE: N

height

The greatest height, as for derivations.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
N

The sum, zero when the item has no derivation.

RAISES DESCRIPTION
RuleError

If a derivation has an open hypothesis.

Source code in src/quivers/qiec/rules.py
def observe[N: (Fraction, float)](
    self,
    goal: Item,
    weight: Callable[[Derivation], N],
    value: Callable[[Derivation], N],
    observer: Callable[[N], N],
    zero: N,
    *,
    height: int | None = None,
) -> N:
    """The weighted sum over derivations of an observer of their values.

    This is the observable ``sum_d w(d) h(fold(d))`` computed by its
    definition: the observer is applied to each derivation's value and
    never to an aggregate, so it may be nonlinear.

    Parameters
    ----------
    goal : Item
        The item.
    weight : Callable[[Derivation], N]
        The weight of one node of a derivation; a derivation's weight
        is the product over its nodes.
    value : Callable[[Derivation], N]
        The value of a whole derivation, usually a fold.
    observer : Callable[[N], N]
        Any function of one value.
    zero : N
        The empty sum.
    height : int or None
        The greatest height, as for `derivations`.

    Returns
    -------
    N
        The sum, ``zero`` when the item has no derivation.

    Raises
    ------
    RuleError
        If a derivation has an open hypothesis.
    """
    total = zero
    for derivation in self.derivations(goal, height=height):
        product = weight(derivation)
        stack: list[ProofNode] = list(derivation.premises)
        while stack:
            node = stack.pop()
            if isinstance(node, Hole):
                raise RuleError("a reference derivation has no open hypothesis")
            product = product * weight(node)
            stack.extend(node.premises)
        total = total + product * observer(value(derivation))
    return total

derivations

derivations(goal: Item, *, height: int | None = None) -> list[Derivation]

Every derivation of an item.

PARAMETER DESCRIPTION
goal

The item.

TYPE: Item

height

The greatest height, a restriction of the model that is required when the item lies above a cycle.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
list of Derivation

Every derivation, each once.

RAISES DESCRIPTION
CyclicDerivations

If the item has infinitely many derivations and no height was given.

Source code in src/quivers/qiec/rules.py
def derivations(self, goal: Item, *, height: int | None = None) -> list[Derivation]:
    """Every derivation of an item.

    Parameters
    ----------
    goal : Item
        The item.
    height : int or None
        The greatest height, a restriction of the model that is
        required when the item lies above a cycle.

    Returns
    -------
    list of Derivation
        Every derivation, each once.

    Raises
    ------
    CyclicDerivations
        If the item has infinitely many derivations and no height was
        given.
    """
    if height is None:
        self._refuse_cycles(goal)

    def trees(item: Item, budget: int | None) -> Iterator[Derivation]:
        """The derivations of one item within a height.

        Parameters
        ----------
        item : Item
            The item.
        budget : int or None
            The height left.

        Yields
        ------
        Derivation
            A derivation.
        """
        yield from self._leaves.get(item, ())
        if budget == 0:
            return
        lower = None if budget is None else budget - 1
        for rule, binding, premises in self._instances.get(item, ()):
            branches = [list(trees(premise, lower)) for premise in premises]
            for children in itertools.product(*branches):
                yield Derivation(
                    constructor=rule.id,
                    item=item,
                    binding=tuple(sorted(binding.items())),
                    premises=tuple(children),
                )

    return list(trees(goal, height))

evaluate_index

evaluate_index(term: IndexTerm, binding: Mapping[str, Ground]) -> Ground

The ground value of an index term whose variables are bound.

PARAMETER DESCRIPTION
term

The term.

TYPE: IndexTerm

binding

Values of its variables.

TYPE: Mapping[str, Ground]

RETURNS DESCRIPTION
Ground

Its value.

RAISES DESCRIPTION
MatchError

If a variable is unbound, a sum has a summand that is not a number, or the term is a shape.

Source code in src/quivers/qiec/rules.py
def evaluate_index(term: IndexTerm, binding: Mapping[str, Ground]) -> Ground:
    """The ground value of an index term whose variables are bound.

    Parameters
    ----------
    term : IndexTerm
        The term.
    binding : Mapping[str, Ground]
        Values of its variables.

    Returns
    -------
    Ground
        Its value.

    Raises
    ------
    MatchError
        If a variable is unbound, a sum has a summand that is not a
        number, or the term is a shape.
    """
    if isinstance(term, IndexVariable):
        if term.name not in binding:
            raise MatchError(f"index variable {term.name!r} is unbound")
        return binding[term.name]
    if isinstance(term, IndexLiteral):
        return _ground_literal(term)
    if isinstance(term, IndexConstructor):
        return (term.name, *(evaluate_index(item, binding) for item in term.arguments))
    if isinstance(term, IndexSum):
        total = term.constant
        for summand in term.terms:
            value = evaluate_index(summand, binding)
            if not isinstance(value, int):
                raise MatchError(f"summand {summand.name!r} is not a number")
            total += value
        return total
    raise MatchError("a shape is not a judgment argument")

match_index

match_index(term: IndexTerm, value: Ground, binding: Binding) -> bool

Extend a binding so that an index term equals a ground value.

The work includes the pattern and any structural comparisons with previously bound ground values.

PARAMETER DESCRIPTION
term

The pattern.

TYPE: IndexTerm

value

The ground value.

TYPE: Ground

binding

The variables bound so far; extended in place on success.

TYPE: Binding

RETURNS DESCRIPTION
bool

Whether an extension exists. On failure the binding may hold variables bound by this call.

RAISES DESCRIPTION
MatchError

If a sum has more than one unbound variable, which the presentation's validation excludes.

Source code in src/quivers/qiec/rules.py
def match_index(term: IndexTerm, value: Ground, binding: Binding) -> bool:
    """Extend a binding so that an index term equals a ground value.

    The work includes the pattern and any structural comparisons with
    previously bound ground values.

    Parameters
    ----------
    term : IndexTerm
        The pattern.
    value : Ground
        The ground value.
    binding : Binding
        The variables bound so far; extended in place on success.

    Returns
    -------
    bool
        Whether an extension exists. On failure the binding may hold
        variables bound by this call.

    Raises
    ------
    MatchError
        If a sum has more than one unbound variable, which the
        presentation's validation excludes.
    """
    if isinstance(term, IndexVariable):
        if term.name in binding:
            return binding[term.name] == value
        binding[term.name] = value
        return True
    if isinstance(term, IndexLiteral):
        return _ground_literal(term) == value
    if isinstance(term, IndexConstructor):
        if not isinstance(value, tuple) or len(value) != len(term.arguments) + 1:
            return False
        if value[0] != term.name:
            return False
        return all(
            match_index(item, part, binding)
            for item, part in zip(term.arguments, value[1:], strict=True)
        )
    if isinstance(term, IndexSum):
        if not isinstance(value, int):
            return False
        unbound = [item for item in term.terms if item.name not in binding]
        known = term.constant
        for item in term.terms:
            if item.name in binding:
                bound = binding[item.name]
                if not isinstance(bound, int):
                    return False
                known += bound
        if not unbound:
            return known == value
        if len(unbound) > 1:
            raise MatchError("an index sum with two unbound summands is not a pattern")
        rest = value - known
        if rest < 0:
            return False
        binding[unbound[0].name] = rest
        return True
    if isinstance(term, ShapeIndex):
        raise MatchError("a shape is not a judgment argument")
    raise MatchError("unknown index term")

named_conditions

named_conditions(presentation: RulePresentation) -> tuple[SideCondition, ...]

The side conditions of a presentation's rules.

PARAMETER DESCRIPTION
presentation

The presentation.

TYPE: RulePresentation

RETURNS DESCRIPTION
tuple of SideCondition

One per rule that has one, in rule order.

Source code in src/quivers/qiec/rules.py
def named_conditions(presentation: RulePresentation) -> tuple[SideCondition, ...]:
    """The side conditions of a presentation's rules.

    Parameters
    ----------
    presentation : RulePresentation
        The presentation.

    Returns
    -------
    tuple of SideCondition
        One per rule that has one, in rule order.
    """
    return tuple(
        rule.side_condition for rule in presentation.rules if rule.side_condition
    )

presentation_of

presentation_of(signature: Signature) -> RulePresentation

The rule presentation of a structural signature.

Each object sort is a judgment form without arguments. A constructor is a rule with no side condition: its object arguments are premises in order and its data and index arguments are value fields. An argument that binds variables is a premise with those variables as hypotheses, so each premise carries its own binding arity. The presentation is built once per signature.

PARAMETER DESCRIPTION
signature

A term signature.

TYPE: Signature

RETURNS DESCRIPTION
RulePresentation

Its presentation.

RAISES DESCRIPTION
RuleError

If the signature is graph shaped, or an argument binds a variable of a sort that is not an object sort.

Source code in src/quivers/qiec/rules.py
def presentation_of(signature: Signature) -> RulePresentation:
    """The rule presentation of a structural signature.

    Each object sort is a judgment form without arguments. A constructor
    is a rule with no side condition: its object arguments are premises
    in order and its data and index arguments are value fields. An
    argument that binds variables is a premise with those variables as
    hypotheses, so each premise carries its own binding arity. The
    presentation is built once per signature.

    Parameters
    ----------
    signature : Signature
        A term signature.

    Returns
    -------
    RulePresentation
        Its presentation.

    Raises
    ------
    RuleError
        If the signature is graph shaped, or an argument binds a variable
        of a sort that is not an object sort.
    """
    known = _SIGNATURE_PRESENTATIONS.get(signature)
    if known is not None:
        return known
    if signature.vertex_kinds_t or signature.edge_kinds_t:
        raise RuleError(
            f"signature {signature.name!r} is graph shaped; a graph is not a term "
            "algebra and has no rule presentation here"
        )
    objects = [sort.name for sort in signature.sorts_t if sort.kind == "object"]

    def judgment(sort: str) -> Judgment:
        """The judgment of an object sort.

        Parameters
        ----------
        sort : str
            The sort.

        Returns
        -------
        Judgment
            Its judgment.
        """
        return Judgment(family=_sort_family(signature, sort))

    def split(domain: Sequence[str]) -> tuple[list[Premise], list[FieldDef]]:
        """Premises and value fields of a positional domain.

        Parameters
        ----------
        domain : Sequence of str
            The sorts of the positions.

        Returns
        -------
        tuple of list of Premise and list of FieldDef
            The premises of object positions and the fields of the others.
        """
        premises: list[Premise] = []
        values: list[FieldDef] = []
        for position, sort in enumerate(domain):
            if signature.sorts[sort].kind == "object":
                premises.append(Premise(judgment=judgment(sort)))
            else:
                values.append(
                    FieldDef(name=f"value{position}", type=_value_type(signature, sort))
                )
        return premises, values

    rules: list[Rule] = []
    for constructor in signature.constructors_t:
        premises, values = split(constructor.domain)
        hypotheses_at: list[tuple[Judgment, ...]] = []
        for position in range(constructor.arity):
            hypotheses = []
            for variable in constructor.bound_at(position):
                if variable.sort not in objects:
                    raise RuleError(
                        f"constructor {constructor.name!r} binds "
                        f"{variable.name!r} of sort {variable.sort!r}, which is "
                        "not an object sort"
                    )
                hypotheses.append(judgment(variable.sort))
            hypotheses_at.append(tuple(hypotheses))
        object_positions = [
            position
            for position, sort in enumerate(constructor.domain)
            if signature.sorts[sort].kind == "object"
        ]
        premises = [
            premise.with_(after=hypotheses_at[position])
            if hypotheses_at[position]
            else premise
            for premise, position in zip(premises, object_positions, strict=True)
        ]
        rules.append(
            Rule(
                id=ConstructorId.derive("signature", signature.name, constructor.name),
                name=constructor.name,
                premises=tuple(premises),
                conclusion=judgment(constructor.codomain),
                values=tuple(values),
            )
        )
    presentation = RulePresentation(
        id=PresentationId.derive("signature", signature.name),
        name=signature.name,
        judgments=tuple(
            JudgmentDecl(id=_sort_family(signature, sort), name=sort)
            for sort in objects
        ),
        rules=tuple(rules),
    )
    _SIGNATURE_PRESENTATIONS[signature] = presentation
    return presentation

identity_derivation

identity_derivation(item: Item) -> OpenDerivation

The identity arrow on an item: its own hypothesis.

PARAMETER DESCRIPTION
item

The item.

TYPE: Item

RETURNS DESCRIPTION
OpenDerivation

The derivation of the item from itself.

Source code in src/quivers/qiec/rules.py
def identity_derivation(item: Item) -> OpenDerivation:
    """The identity arrow on an item: its own hypothesis.

    Parameters
    ----------
    item : Item
        The item.

    Returns
    -------
    OpenDerivation
        The derivation of the item from itself.
    """
    return OpenDerivation(context=(item,), body=Hole(index=0, item=item))

extend_context

extend_context(before: tuple[T, ...], context: tuple[T, ...], after: tuple[T, ...]) -> tuple[T, ...]

The context of a premise: its left hypotheses, the context, its right ones.

Every operation on open derivations places a premise's hypotheses by this function or by the counts it implies, so the side of a hypothesis is decided in one place.

PARAMETER DESCRIPTION
before

The left block.

TYPE: tuple

context

The enclosing context.

TYPE: tuple

after

The right block.

TYPE: tuple

RETURNS DESCRIPTION
tuple

before + context + after.

Source code in src/quivers/qiec/rules.py
def extend_context[T](
    before: tuple[T, ...], context: tuple[T, ...], after: tuple[T, ...]
) -> tuple[T, ...]:
    """The context of a premise: its left hypotheses, the context, its right ones.

    Every operation on open derivations places a premise's hypotheses by
    this function or by the counts it implies, so the side of a
    hypothesis is decided in one place.

    Parameters
    ----------
    before : tuple
        The left block.
    context : tuple
        The enclosing context.
    after : tuple
        The right block.

    Returns
    -------
    tuple
        ``before + context + after``.
    """
    return (*before, *context, *after)

compose_derivations

compose_derivations(presentation: RulePresentation, outer: OpenDerivation, arguments: Sequence[OpenDerivation]) -> OpenDerivation

Plug derivations into the hypotheses of a derivation, in order.

This is composition in the free colored nonsymmetric multicategory: hypothesis k of outer is replaced by arguments[k], and the contexts of the arguments are concatenated in order. It needs no structural rule.

PARAMETER DESCRIPTION
presentation

The presentation.

TYPE: RulePresentation

outer

The derivation whose hypotheses are filled.

TYPE: OpenDerivation

arguments

One derivation per hypothesis, of its item.

TYPE: Sequence of OpenDerivation

RETURNS DESCRIPTION
OpenDerivation

The composite.

RAISES DESCRIPTION
RuleError

If the number of arguments or the item of one differs.

Source code in src/quivers/qiec/rules.py
def compose_derivations(
    presentation: RulePresentation,
    outer: OpenDerivation,
    arguments: Sequence[OpenDerivation],
) -> OpenDerivation:
    """Plug derivations into the hypotheses of a derivation, in order.

    This is composition in the free colored nonsymmetric multicategory:
    hypothesis ``k`` of ``outer`` is replaced by ``arguments[k]``, and the
    contexts of the arguments are concatenated in order. It needs no
    structural rule.

    Parameters
    ----------
    presentation : RulePresentation
        The presentation.
    outer : OpenDerivation
        The derivation whose hypotheses are filled.
    arguments : Sequence of OpenDerivation
        One derivation per hypothesis, of its item.

    Returns
    -------
    OpenDerivation
        The composite.

    Raises
    ------
    RuleError
        If the number of arguments or the item of one differs.
    """
    if len(arguments) != len(outer.context):
        raise RuleError(
            f"{len(outer.context)} hypotheses take as many derivations, got "
            f"{len(arguments)}"
        )
    for position, (argument, item) in enumerate(
        zip(arguments, outer.context, strict=True)
    ):
        if argument.item != item:
            raise RuleError(f"argument {position} derives another item")
    context = tuple(item for argument in arguments for item in argument.context)
    offsets: list[int] = []
    start = 0
    for argument in arguments:
        offsets.append(start)
        start += len(argument.context)
    total = len(context)
    placed: list[ProofNode] = []
    for argument, offset in zip(arguments, offsets, strict=True):
        width = len(argument.context)
        items = argument.context

        def moved(
            level: int,
            left: int,
            right: int,
            offset: int = offset,
            items: tuple[Item, ...] = items,
        ) -> Hole:
            """A hole of an argument, placed in the concatenated context.

            Parameters
            ----------
            level : int
                Its level in the argument's context.
            left, right : int
                The argument's own hypotheses around it.
            offset : int
                Where the argument's context starts.
            items : tuple of Item
                The argument's context.

            Returns
            -------
            Hole
                The same hypothesis in the new context.
            """
            del left
            return Hole(index=right + total - 1 - (offset + level), item=items[level])

        placed.append(_map_holes(presentation, argument.body, width, total, moved))

    def filled(level: int, left: int, right: int) -> ProofNode:
        """The derivation that fills one hypothesis of ``outer``.

        Parameters
        ----------
        level : int
            The hypothesis.
        left, right : int
            The hypotheses of ``outer`` around it.

        Returns
        -------
        Derivation or Hole
            The argument, moved between those hypotheses.
        """
        return _weaken(presentation, placed[level], total, left, right)

    return OpenDerivation(
        context=context,
        body=_map_holes(presentation, outer.body, len(outer.context), total, filled),
    )

substitute_hypotheses

substitute_hypotheses(presentation: RulePresentation, outer: OpenDerivation, arguments: Sequence[OpenDerivation], context: tuple[Item, ...]) -> OpenDerivation

Replace every hypothesis of a derivation by a derivation in one context.

Unlike compose_derivations, every argument is in the same context, so a hypothesis used twice duplicates its argument and one unused drops it. Whether that is licensed is a question for required_structure.

PARAMETER DESCRIPTION
presentation

The presentation.

TYPE: RulePresentation

outer

The derivation.

TYPE: OpenDerivation

arguments

One derivation per hypothesis, each in context.

TYPE: Sequence of OpenDerivation

context

The shared context.

TYPE: tuple of Item

RETURNS DESCRIPTION
OpenDerivation

The substituted derivation.

RAISES DESCRIPTION
RuleError

If the number, items or contexts of the arguments differ.

Source code in src/quivers/qiec/rules.py
def substitute_hypotheses(
    presentation: RulePresentation,
    outer: OpenDerivation,
    arguments: Sequence[OpenDerivation],
    context: tuple[Item, ...],
) -> OpenDerivation:
    """Replace every hypothesis of a derivation by a derivation in one context.

    Unlike `compose_derivations`, every argument is in the same context, so a
    hypothesis used twice duplicates its argument and one unused drops
    it. Whether that is licensed is a question for `required_structure`.

    Parameters
    ----------
    presentation : RulePresentation
        The presentation.
    outer : OpenDerivation
        The derivation.
    arguments : Sequence of OpenDerivation
        One derivation per hypothesis, each in ``context``.
    context : tuple of Item
        The shared context.

    Returns
    -------
    OpenDerivation
        The substituted derivation.

    Raises
    ------
    RuleError
        If the number, items or contexts of the arguments differ.
    """
    if len(arguments) != len(outer.context):
        raise RuleError("one derivation per hypothesis")
    for position, (argument, item) in enumerate(
        zip(arguments, outer.context, strict=True)
    ):
        if argument.item != item or argument.context != context:
            raise RuleError(f"argument {position} has another item or context")
    width = len(context)

    def filled(level: int, left: int, right: int) -> ProofNode:
        """The argument of one hypothesis, between the inner hypotheses.

        Parameters
        ----------
        level : int
            The hypothesis.
        left, right : int
            The hypotheses around it.

        Returns
        -------
        Derivation or Hole
            The argument.
        """
        return _weaken(presentation, arguments[level].body, width, left, right)

    return OpenDerivation(
        context=context,
        body=_map_holes(presentation, outer.body, len(outer.context), width, filled),
    )

rename_hypotheses

rename_hypotheses(presentation: RulePresentation, derivation: OpenDerivation, targets: Sequence[int], context: tuple[Item, ...]) -> OpenDerivation

Move each hypothesis of a derivation to a position of a new context.

An injective, order-keeping renaming is a weakening; a permutation is an exchange; a renaming that sends two hypotheses to one is a contraction. The result says which rules it uses through required_structure.

PARAMETER DESCRIPTION
presentation

The presentation.

TYPE: RulePresentation

derivation

The derivation.

TYPE: OpenDerivation

targets

The new level of each old level.

TYPE: Sequence of int

context

The new context.

TYPE: tuple of Item

RETURNS DESCRIPTION
OpenDerivation

The renamed derivation.

RAISES DESCRIPTION
RuleError

If a target is outside the new context or holds another item.

Source code in src/quivers/qiec/rules.py
def rename_hypotheses(
    presentation: RulePresentation,
    derivation: OpenDerivation,
    targets: Sequence[int],
    context: tuple[Item, ...],
) -> OpenDerivation:
    """Move each hypothesis of a derivation to a position of a new context.

    An injective, order-keeping renaming is a weakening; a permutation is
    an exchange; a renaming that sends two hypotheses to one is a
    contraction. The result says which rules it uses through
    `required_structure`.

    Parameters
    ----------
    presentation : RulePresentation
        The presentation.
    derivation : OpenDerivation
        The derivation.
    targets : Sequence of int
        The new level of each old level.
    context : tuple of Item
        The new context.

    Returns
    -------
    OpenDerivation
        The renamed derivation.

    Raises
    ------
    RuleError
        If a target is outside the new context or holds another item.
    """
    if len(targets) != len(derivation.context):
        raise RuleError("one target per hypothesis")
    for level, target in enumerate(targets):
        if (
            not 0 <= target < len(context)
            or context[target] != derivation.context[level]
        ):
            raise RuleError(f"hypothesis {level} goes to a position of another item")
    width = len(context)

    def moved(level: int, left: int, right: int) -> Hole:
        """The hole of an old level in the new context.

        Parameters
        ----------
        level : int
            The old level.
        left, right : int
            The hypotheses around it.

        Returns
        -------
        Hole
            The renamed hole.
        """
        del left
        return Hole(
            index=right + width - 1 - targets[level], item=context[targets[level]]
        )

    return OpenDerivation(
        context=context,
        body=_map_holes(
            presentation, derivation.body, len(derivation.context), width, moved
        ),
    )

required_structure

required_structure(presentation: RulePresentation, derivation: OpenDerivation) -> ContextStructure

The structural rules a derivation uses.

In every scope (the derivation's context, and each premise with hypotheses) the uses of visible hypotheses, read left to right, are compared with the scope's context in order: a use out of order needs exchange, a hypothesis of the scope not used needs weakening, and one used twice needs contraction.

PARAMETER DESCRIPTION
presentation

The presentation.

TYPE: RulePresentation

derivation

The derivation.

TYPE: OpenDerivation

RETURNS DESCRIPTION
ContextStructure

The least structure that admits it.

Source code in src/quivers/qiec/rules.py
def required_structure(
    presentation: RulePresentation, derivation: OpenDerivation
) -> ContextStructure:
    """The structural rules a derivation uses.

    In every scope (the derivation's context, and each premise with
    hypotheses) the uses of visible hypotheses, read left to right, are
    compared with the scope's context in order: a use out of order needs
    exchange, a hypothesis of the scope not used needs weakening, and one
    used twice needs contraction.

    Parameters
    ----------
    presentation : RulePresentation
        The presentation.
    derivation : OpenDerivation
        The derivation.

    Returns
    -------
    ContextStructure
        The least structure that admits it.
    """
    exchange = weakening = contraction = False

    def scope(
        body: ProofNode, width: int, own: set[int], start: int, outer: int
    ) -> list[int]:
        """Check one scope and return the uses of its enclosing context.

        Parameters
        ----------
        body : Derivation or Hole
            The derivation of the scope.
        width : int
            The length of the scope's context.
        own : set of int
            The positions this scope binds.
        start : int
            Where the enclosing context begins in the scope's.
        outer : int
            The length of the enclosing context.

        Returns
        -------
        list of int
            The uses of positions of the enclosing context, in order.
        """
        nonlocal exchange, weakening, contraction
        uses = _uses(body, width)
        if any(later < earlier for earlier, later in itertools.pairwise(uses)):
            exchange = True
        counts = Counter(position for position in uses if position in own)
        if any(counts[position] == 0 for position in own):
            weakening = True
        if any(count > 1 for count in counts.values()):
            contraction = True
        return [p - start for p in uses if start <= p < start + outer]

    def _uses(body: ProofNode, width: int) -> list[int]:
        """The positions used in a scope, in order, after checking inner scopes.

        Parameters
        ----------
        body : Derivation or Hole
            The derivation.
        width : int
            The length of its context.

        Returns
        -------
        list of int
            The positions of the scope's context used, left to right.
        """
        if isinstance(body, Hole):
            return [width - 1 - body.index]
        found: list[int] = []
        blocks = _hypotheses(presentation, body)
        for position, child in enumerate(body.premises):
            before, after = _counts(blocks, position)
            if before or after:
                inner = before + width + after
                own = set(range(before)) | set(range(before + width, inner))
                found.extend(scope(child, inner, own, before, width))
            else:
                found.extend(_uses(child, width))
        return found

    width = len(derivation.context)
    scope(derivation.body, width, set(range(width)), 0, width)
    return ContextStructure(
        exchange=exchange, weakening=weakening, contraction=contraction
    )

check_structure

check_structure(presentation: RulePresentation, derivation: OpenDerivation) -> None

Refuse a derivation that uses a structural rule the presentation lacks.

PARAMETER DESCRIPTION
presentation

The presentation.

TYPE: RulePresentation

derivation

The derivation.

TYPE: OpenDerivation

RAISES DESCRIPTION
StructureError

Naming each rule used and not admitted.

Source code in src/quivers/qiec/rules.py
def check_structure(presentation: RulePresentation, derivation: OpenDerivation) -> None:
    """Refuse a derivation that uses a structural rule the presentation lacks.

    Parameters
    ----------
    presentation : RulePresentation
        The presentation.
    derivation : OpenDerivation
        The derivation.

    Raises
    ------
    StructureError
        Naming each rule used and not admitted.
    """
    required = required_structure(presentation, derivation)
    missing = [
        name
        for name in ("exchange", "weakening", "contraction")
        if getattr(required, name) and not getattr(presentation.structure, name)
    ]
    if missing:
        raise StructureError(
            f"the derivation uses {', '.join(missing)}, which "
            f"{presentation.name!r} does not admit"
        )

check_derivation

check_derivation(presentation: RulePresentation, derivation: OpenDerivation) -> None

Check a derivation with the QIEC checker.

Each node becomes a QIEC constructor value of its rule, with the rule's telescope instantiated at the node's binding, its premises as fields, and its values as literals; each hypothesis becomes a local of its item's type. quivers.qiec.checking.infer_value then checks that every field has the type the rule gives it and that the node has its item's type. A premise with hypotheses is checked as its own value in the context extended by them, and stands for a local of its type in its parent, since QIEC has no function values.

PARAMETER DESCRIPTION
presentation

The presentation.

TYPE: RulePresentation

derivation

The derivation.

TYPE: OpenDerivation

RAISES DESCRIPTION
RuleError

If a node names another presentation's rule, a hole assumes an item other than its context's, or the checker refuses it.

Source code in src/quivers/qiec/rules.py
def check_derivation(
    presentation: RulePresentation, derivation: OpenDerivation
) -> None:
    """Check a derivation with the QIEC checker.

    Each node becomes a QIEC constructor value of its rule, with the
    rule's telescope instantiated at the node's binding, its premises as
    fields, and its values as literals; each hypothesis becomes a local of
    its item's type. `quivers.qiec.checking.infer_value` then checks that
    every field has the type the rule gives it and that the node has its
    item's type. A premise with hypotheses is checked as its own value in
    the context extended by them, and stands for a local of its type in
    its parent, since QIEC has no function values.

    Parameters
    ----------
    presentation : RulePresentation
        The presentation.
    derivation : OpenDerivation
        The derivation.

    Raises
    ------
    RuleError
        If a node names another presentation's rule, a hole assumes an
        item other than its context's, or the checker refuses it.
    """
    hypotheses: list[Local] = []

    def local(item: Item) -> Local:
        """A fresh local of an item's proof type.

        Parameters
        ----------
        item : Item
            The item.

        Returns
        -------
        Local
            The local, named by its number, and recorded.
        """
        made = Local(
            name=f"hypothesis{len(hypotheses)}", type=_item_type(presentation, item)
        )
        hypotheses.append(made)
        return made

    context_locals = tuple(local(item) for item in derivation.context)
    pending: list[tuple[ProofNode, tuple[Local, ...], Item]] = [
        (derivation.body, context_locals, derivation.item)
    ]
    while pending:
        body, scope, item = pending.pop()
        placeholders: list[Local] = []
        value = _lower_value(
            presentation, body, scope, pending, local, hypotheses, placeholders
        )
        _check_lowered_proof(presentation, value, item, (*scope, *placeholders))

closed_derivation_value

closed_derivation_value(presentation: RulePresentation, derivation: Derivation) -> ConstructorValue

Give a closed derivation's checked proof value to an ordinary QIEC call.

The value has exactly the source rule constructors, index arguments, ordered premises, and data fields. Axiom occurrence identities and weights remain in the derivation or forest that supplied the value. Encoding several derivations does not combine their weights.

PARAMETER DESCRIPTION
presentation

The unconditional rule presentation containing the proof declarations.

TYPE: RulePresentation

derivation

A closed proof in that presentation.

TYPE: Derivation

RETURNS DESCRIPTION
ConstructorValue

A value of the proved judgment's exact indexed family type. Its consuming module needs the declarations of the same presentation.

RAISES DESCRIPTION
RuleError

If the presentation requires side conditions or proof equations, the proof uses holes or scoped premises, or a proof field is ill typed.

Source code in src/quivers/qiec/rules.py
def closed_derivation_value(
    presentation: RulePresentation, derivation: Derivation
) -> ConstructorValue:
    """Give a closed derivation's checked proof value to an ordinary QIEC call.

    The value has exactly the source rule constructors, index arguments,
    ordered premises, and data fields. Axiom occurrence identities and
    weights remain in the derivation or forest that supplied the value.
    Encoding several derivations does not combine their weights.

    Parameters
    ----------
    presentation
        The unconditional rule presentation containing the proof declarations.
    derivation
        A closed proof in that presentation.

    Returns
    -------
    ConstructorValue
        A value of the proved judgment's exact indexed family type. Its
        consuming module needs the declarations of the same presentation.

    Raises
    ------
    RuleError
        If the presentation requires side conditions or proof equations,
        the proof uses holes or scoped premises, or a proof field is ill typed.
    """
    if presentation.conditions or presentation.equations:
        raise RuleError(
            "closed proof values require unconditional syntax without equations"
        )

    frames: list[
        tuple[
            Derivation,
            Rule | AxiomSlot,
            tuple[IndexTerm, ...],
            tuple[Blocks, ...],
            list[Value],
        ]
    ] = []
    node: ProofNode = derivation
    while True:
        if isinstance(node, Hole):
            raise RuleError(f"hole {node.index} lies outside its context")
        rule, _, static = _proof_arguments(presentation, node)
        frames.append((node, rule, static, _hypotheses(presentation, node), []))
        while frames:
            current, rule, static, blocks, fields = frames[-1]
            position = len(fields)
            if position < len(current.premises):
                if blocks and any(blocks[position]):
                    raise RuleError(
                        "a closed proof value cannot encode a premise under hypotheses"
                    )
                node = current.premises[position]
                break
            value = _proof_constructor(presentation, current, rule, static, fields)
            frames.pop()
            if not frames:
                _check_lowered_proof(presentation, value, derivation.item, ())
                return value
            frames[-1][-1].append(value)

term_derivation

term_derivation(signature: Signature, term: Term, context: tuple[str, ...] = ()) -> OpenDerivation

The derivation of a structural term in its signature's presentation.

A constructor node is a rule application, its data and index arguments are values, and a bound variable is a hole.

PARAMETER DESCRIPTION
signature

The signature.

TYPE: Signature

term

The term.

TYPE: Term

context

The sorts of its free variables, outermost first.

TYPE: tuple of str DEFAULT: ()

RETURNS DESCRIPTION
OpenDerivation

The derivation, in the context of the free variables.

RAISES DESCRIPTION
RuleError

If the term does not fit its signature.

Source code in src/quivers/qiec/rules.py
def term_derivation(
    signature: Signature, term: Term, context: tuple[str, ...] = ()
) -> OpenDerivation:
    """The derivation of a structural term in its signature's presentation.

    A constructor node is a rule application, its data and index
    arguments are values, and a bound variable is a hole.

    Parameters
    ----------
    signature : Signature
        The signature.
    term : Term
        The term.
    context : tuple of str
        The sorts of its free variables, outermost first.

    Returns
    -------
    OpenDerivation
        The derivation, in the context of the free variables.

    Raises
    ------
    RuleError
        If the term does not fit its signature.
    """
    rules = {rule.name: rule.id for rule in presentation_of(signature).rules}

    def item(sort: str) -> Item:
        """The item of an object sort.

        Parameters
        ----------
        sort : str
            The sort.

        Returns
        -------
        Item
            The item.
        """
        return Item(family=_sort_family(signature, sort))

    frames: list[
        tuple[
            Term, tuple[str, ...], str, list[ProofNode], list[str | int | float | bool]
        ]
    ] = []
    finished: ProofNode | None = None

    def deliver(node: ProofNode) -> None:
        """Hand a finished node to its parent.

        Parameters
        ----------
        node : Derivation or Hole
            The node.
        """
        nonlocal finished
        if frames:
            frames[-1][3].append(node)
        else:
            finished = node

    def enter(node: Term, scope: tuple[str, ...], sort: str) -> None:
        """Start a node, or finish a variable at once.

        Parameters
        ----------
        node : Term
            The node.
        scope : tuple of str
            The sorts of the variables in scope, outermost first.
        sort : str
            The sort the node must have.

        Raises
        ------
        RuleError
            If a variable is out of scope or of another sort.
        """
        if node.op == "BoundVar":
            index = node.args[0]
            assert isinstance(index, int)
            if index >= len(scope) or scope[len(scope) - 1 - index] != sort:
                raise RuleError(f"variable {index} is out of scope or of another sort")
            deliver(Hole(index=index, item=item(sort)))
            return
        if signature.codomain_of(node.op) != sort:
            raise RuleError(f"{node.op!r} does not produce sort {sort!r}")
        frames.append((node, scope, sort, [], []))

    enter(term, context, _sort_of_root(signature, term, context))
    while frames:
        node, scope, sort, premises, values = frames[-1]
        domain = signature.domain_of(node.op)
        position = len(premises) + len(values)
        if position == len(node.args):
            frames.pop()
            deliver(
                Derivation(
                    constructor=rules[node.op],
                    item=item(sort),
                    values=tuple(values),
                    premises=tuple(premises),
                )
            )
            continue
        argument = node.args[position]
        argument_sort = domain[position]
        inner = scope + tuple(
            variable.sort
            for variable in signature.constructor(node.op).bound_at(position)
        )
        if signature.sorts[argument_sort].kind == "object":
            if not isinstance(argument, Term):
                raise RuleError(f"{node.op!r} takes a term at position {position}")
            enter(argument, inner, argument_sort)
        else:
            if isinstance(argument, Term) or isinstance(argument, bytes):
                raise RuleError(f"{node.op!r} takes a value at position {position}")
            values.append(argument)
    assert finished is not None
    return OpenDerivation(context=tuple(item(sort) for sort in context), body=finished)

closed_values

closed_values(values: tuple[PremiseValue[V], ...]) -> tuple[V, ...]

The values of premises that have no hypotheses.

PARAMETER DESCRIPTION
values

What an operation received.

TYPE: tuple of PremiseValue

RETURNS DESCRIPTION
tuple of V

The same values.

RAISES DESCRIPTION
RuleError

If a premise is scoped under hypotheses.

Source code in src/quivers/qiec/rules.py
def closed_values[V](values: tuple[PremiseValue[V], ...]) -> tuple[V, ...]:
    """The values of premises that have no hypotheses.

    Parameters
    ----------
    values : tuple of PremiseValue
        What an operation received.

    Returns
    -------
    tuple of V
        The same values.

    Raises
    ------
    RuleError
        If a premise is scoped under hypotheses.
    """
    found: list[V] = []
    for value in values:
        if isinstance(value, Scoped):
            raise RuleError("a premise under hypotheses is a function, not a value")
        found.append(value)
    return tuple(found)

check_equation

check_equation(interpretation: HostInterpretation[V], equation: Equation, environments: Sequence[tuple[V, ...]], equal: Callable[[V, V], bool], *, subject: ClaimSubject, check: str, domain: str) -> LawClaim

Test whether an interpretation preserves an equation.

Both sides are folded at every environment. A test on finitely many environments can refute preservation and cannot establish it, so the claim it returns is tested, never proved.

PARAMETER DESCRIPTION
interpretation

The interpretation.

TYPE: HostInterpretation

equation

The equation.

TYPE: Equation

environments

Values of the context to try.

TYPE: Sequence of tuple of V

equal

Equality of values.

TYPE: Callable[[V, V], bool]

subject

The interpretation, as the claim names it.

TYPE: ClaimSubject

check

The test that runs this.

TYPE: str

domain

Where the environments come from.

TYPE: str

RETURNS DESCRIPTION
LawClaim

The tested claim that the interpretation preserves the equation's law.

RAISES DESCRIPTION
EquationFails

With the first environment at which the sides differ.

ValueError

If no environment is given.

Source code in src/quivers/qiec/rules.py
def check_equation[V](
    interpretation: HostInterpretation[V],
    equation: Equation,
    environments: Sequence[tuple[V, ...]],
    equal: Callable[[V, V], bool],
    *,
    subject: ClaimSubject,
    check: str,
    domain: str,
) -> LawClaim:
    """Test whether an interpretation preserves an equation.

    Both sides are folded at every environment. A test on finitely many
    environments can refute preservation and cannot establish it, so the
    claim it returns is tested, never proved.

    Parameters
    ----------
    interpretation : HostInterpretation
        The interpretation.
    equation : Equation
        The equation.
    environments : Sequence of tuple of V
        Values of the context to try.
    equal : Callable[[V, V], bool]
        Equality of values.
    subject : ClaimSubject
        The interpretation, as the claim names it.
    check : str
        The test that runs this.
    domain : str
        Where the environments come from.

    Returns
    -------
    LawClaim
        The tested claim that the interpretation preserves the equation's law.

    Raises
    ------
    EquationFails
        With the first environment at which the sides differ.
    ValueError
        If no environment is given.
    """
    if not environments:
        raise ValueError("a test of an equation needs an environment")
    for environment in environments:
        left = interpretation.fold_open(equation.left, environment)
        right = interpretation.fold_open(equation.right, environment)
        if not equal(left, right):
            raise EquationFails(
                f"{equation.law.name!r} fails at {environment!r}: {left!r} and {right!r}"
            )
    return LawClaim(
        law=equation.law,
        subject=subject,
        evidence=Tested(check=check, cases=len(environments), domain=domain),
    )