Skip to content

quivers.dsl

QVR is the modeling language of quivers, written in .qvr files. load and loads parse, check, and compile source to a Program, parse produces the AST that Compiler compiles and module_to_source prints, and the QIEC lowering elaborates a module into the Quivers Indexed Effect Core and checks it. The package re-exports the public names of its modules, and the AST node classes are documented in quivers.dsl.ast_nodes.

dsl

quivers DSL: parse .qvr files into trainable PyTorch models.

The DSL provides a declarative syntax for specifying V-enriched categorical morphism networks that compile to quivers.Program instances (nn.Module subclasses). Parsing is delegated to panproto via the qvr tree-sitter grammar; the AST is a tree of quivers.dsl.ast_nodes didactic Models.

Morphism roles need not be declared: a morphism drawn with sample compiles as latent, one drawn with observe as observed, and any other morphism as a kernel. An explicit [role=...] option always wins over inference.

Quick start

::

from quivers.dsl import load, loads

program = loads('''
    object Resp : FinSet 8
    morphism bias : Resp -> Real 1 ~ Normal(0.0, 5.0)
    program m : Resp -> Resp
        let b <- sample bias
        observe y : Resp <- Normal(b, 1.0)
        return y
    export m
''')

program = load("model.qvr")

optimizer = torch.optim.Adam(program.parameters())

DISTRIBUTION_FAMILIES module-attribute

DISTRIBUTION_FAMILIES: frozenset[str] = frozenset((*_FAMILY_PARAMETERS, *FAMILY_ALIASES))

Every distribution-family name accepted in QVR source.

Highlighters consume this set so their surface vocabulary follows the same schemas used by validation and lowering.

FAMILY_ALIASES module-attribute

FAMILY_ALIASES: dict[str, str] = {'Pushforward': 'Transformed', 'Truncate': 'Restrict'}

Surface family names that resolve to another family's registry record.

A key is a name a source may write; its value is the family whose specification builds the distribution.

PARAMETER_ALIASES module-attribute

PARAMETER_ALIASES: dict[str, dict[str, str]] = {'LogitNormal': {'mu': 'loc', 'sigma': 'scale'}, 'TruncatedNormal': {'mu': 'loc', 'sigma': 'scale'}, 'Mixture': {'components': 'component'}, 'OrderedLogistic': {'predictor': 'eta'}, 'Pushforward': {'bijector': 'transforms'}}

Surface keywords that name a registry parameter under another name.

A family's entry maps each keyword a source may write to the registry parameter it fills, which means the same quantity. A keyword absent here and from the registry record names no parameter of the family.

NOMINAL_KINDS module-attribute

NOMINAL_KINDS: frozenset[StructureKind] = frozenset({'category', 'morphism', 'encoder', 'decoder', 'relation', 'theory'})

Structure kinds whose name is part of their meaning.

A category is an atom of a categorial calculus, distinct from every other atom by its name alone; a morphism, encoder, decoder, or relation owns learned parameters that the compiled runtime and its fit state key by the declaration's name, outside the checked core. Two such declarations with the same content are still different declarations, so their name is content. A theory's name is content too: it is the theory's identity of origin, so two theories with one presentation are different theories, which a colimit keeps apart. A deduction is not nominal: its learned parameters are read through quivers.qiec.terms.ParameterName, whose owner the core reads as a name, so the deduction's name reaches the free names of every entry that reads them, where fit keys see it, and the deduction itself is identified by its content. Every other declaration is identified by its content, and its name is metadata.

STRUCTURE_STATEMENT_TYPES module-attribute

STRUCTURE_STATEMENT_TYPES: tuple[type[Statement], ...] = tuple(_KINDS)

The statement classes recorded as structure declarations.

MAX_LENGTH module-attribute

MAX_LENGTH = 3

The longest sentence a refutation search parses.

MAX_SENTENCES module-attribute

MAX_SENTENCES = 400

The most sentences a refutation search parses.

SHARED_OPTION module-attribute

SHARED_OPTION = 'shared'

The option key naming a rule's shared weight family.

QVR_DEDUCTION_PROTOCOL module-attribute

QVR_DEDUCTION_PROTOCOL: Protocol = panproto.define_protocol({'name': 'qvr_deduction', 'schema_theory': 'ThBratSchema', 'instance_theory': 'ThBratInstance', 'edge_rules': _DEDUCTION_EDGE_RULES, 'obj_kinds': _DEDUCTION_OBJECT_KINDS, 'constraint_sorts': _DEDUCTION_CONSTRAINT_SORTS})

Panproto protocol for a weighted deductive system.

Vertex kinds: * deduction_system: the top-level declaration. * deduction_atom: an atom of the item algebra. * deduction_rule: a named sequent-style inference rule. * deduction_premise: one premise pattern of a rule. * deduction_conclusion: a rule's conclusion pattern.

Edges: * decl: system :math:\to rule. * atom: system :math:\to atom. * premise: rule :math:\to premise. * conclusion: rule :math:\to conclusion.

Constraint sorts carry the system's semiring and the status of each law the semiring claims, its start and depth, each pattern's textual form, and, from the rule presentation the rules are derived from, each rule's identity and weight parameter and each pattern's judgment. Schema morphisms over this protocol correspond to specializations of deduction systems (e.g., :math:\mathsf{CCG} \subset \mathsf{Lambek} \subset \mathsf{MultimodalLambek}).

QVR_PROGRAM_PROTOCOL module-attribute

QVR_PROGRAM_PROTOCOL: Protocol = panproto.define_protocol({'name': 'qvr_program', 'schema_theory': 'ThBratSchema', 'instance_theory': 'ThBratInstance', 'edge_rules': _EDGE_RULES, 'obj_kinds': _OBJECT_KINDS, 'constraint_sorts': _CONSTRAINT_SORTS})

Panproto protocol for a compiled QVR program.

extract_program_schema writes schemas in this protocol. The vertex kinds, edge rules, and constraint sorts are the ones the module docstring lists.

QVR_SOURCE_VERSION module-attribute

QVR_SOURCE_VERSION = 'qvr-source/v0.22'

The source protocol a QvrQiecLowerer route accepts.

lower_qvr_to_qiec checks its source_version argument against this identifier, which names the QVR surface the elaboration reads.

SchemaValue

SchemaValue = int | bool | str

A value of a schema parameter: a numeral, a Boolean, or an index value.

Module didactic-model

Module(*, statements: tuple[Statement, ...] = field(default_factory=tuple), tests: tuple[TestDecl, ...] = field(default_factory=tuple), experiments: tuple[ExperimentDecl, ...] = field(default_factory=tuple))

Bases: Model

A complete .qvr program (sequence of statements).

PARAMETER DESCRIPTION
statements

The module's code, in source order.

TYPE: tuple[Statement, ...] DEFAULT: field(default_factory=tuple)

tests

Its test, property and example declarations, and the examples written in its doc comments, in source order. They check the code and are not part of it: the compiler and the content of the code never include them.

TYPE: tuple[TestDecl, ...] DEFAULT: field(default_factory=tuple)

experiments

Its experiment declarations, in source order. An experiment runs the code and is not part of it, so, like a test, it is kept out of the statements the compiler and the content hashes read.

TYPE: tuple[ExperimentDecl, ...] DEFAULT: field(default_factory=tuple)

Compiler

Compiler(module: Module, *, module_name: str | None = None, file_path: str = '<source>', lower_qiec: bool = True, families: FamilyCatalog | None = None)

Bases: _DeclarationsMixin, _ProgramsMixin, _StructuralMixin, _DeductionsMixin, _ResolutionMixin, _ExpressionsMixin

Compile a quivers DSL AST into a Program.

The compiler maintains three environments:

  • objects: name -> SetObject (discrete finite sets)
  • spaces: name -> ContinuousSpace
  • morphisms: name -> Morphism or ContinuousMorphism (any morphism-like)

It processes statements in order and compiles the output expression into a Program wrapping the morphism DAG.

PARAMETER DESCRIPTION
module

The parsed AST.

TYPE: Module

lower_qiec

Whether to lower the checked QIEC projection. Tooling sets this to False only for its classic-compiler recovery pass after QIEC has already produced a diagnostic.

TYPE: bool DEFAULT: True

families

Immutable custom family contracts and native implementations.

TYPE: FamilyCatalog or None DEFAULT: None

Source code in src/quivers/dsl/compiler/core.py
def __init__(
    self,
    module: Module,
    *,
    module_name: str | None = None,
    file_path: str = "<source>",
    lower_qiec: bool = True,
    families: FamilyCatalog | None = None,
) -> None:
    self._family_catalog = families
    self._distribution_families = families if families is not None else FAMILIES
    _check_named_law_calls(module, self._distribution_families, file_path)
    try:
        validate_model_binds(module)
    except ModelBindError as error:
        raise CompileError(
            error.explanation, error.step.line, error.step.col
        ) from error
    self._qiec_module: QiecModule | None = None
    self._closed_interpretations: tuple[ClosedInterpretationBinding, ...] = ()
    self._packed_interpretations: tuple[
        PackedBooleanInterpretationBinding, ...
    ] = ()
    self._qiec_generated_declarations: tuple[GeneratedDeclaration, ...] = ()
    self._deferred_statements: tuple[Statement, ...] = ()
    # The QIEC projection is lowered on first use, after the
    # statements' own checks when `compile` drives it, so a source
    # error the statement compiler names is reported by it.
    self._qiec_source: Module | None = None
    self._qiec_module_name = module_name
    self._qiec_file_path = file_path
    self._structures = StructureLayer()
    self._theory_layer = TheoryLayer()
    self._semirings: dict[str, CheckedSemiring] = {}
    for statement in module.statements:
        if isinstance(statement, ImportDecl | OpenDecl):
            raise CompileError(
                "this source imports other modules; interpret its module "
                "graph with quivers.dsl.modules (quivers.dsl.load and "
                "quivers.dsl.loads do) and compile the flat program",
                statement.line,
                statement.col,
            )
    try:
        module = compose_deductions(module)
    except CompositionError as error:
        raise CompileError(str(error), error.line, error.col) from error
    try:
        lexical = expand_lexical(
            module,
            module_name=module_name or _module_name(file_path),
            file_path=file_path,
        )
    except LexicalError as error:
        raise CompileError(error.message, error.line, error.col) from error
    module = lexical.module
    self._refinements = lexical.refinements
    self._agenda_plans = lexical.plans
    self._chart_item_readers = {}
    try:
        module = expand_latent_weights(module, LATENT_WEIGHT_HEADS)
    except LatentWeightsError as error:
        raise CompileError(str(error), error.line, error.col) from error
    self._shares = module
    structured = self._read_structures(module)
    if lower_qiec and has_qiec_surface(module):
        self._qiec_source = module
        module = non_qiec_projection(structured)
    else:
        module = structured
    self._module = module
    self._site_ties: SiteTies | None = None
    self._drawn_sites: dict[tuple[str, str], tuple[str, tuple[str, str]]] = {}
    self._algebra: Algebra = PRODUCT_FUZZY
    self._categories: list[str] = []
    self._rules: dict = {}
    self._bundles: dict[str, tuple[str, ...]] = {}
    self._aliases: dict[str, ObjectExpr] = {}
    self._alias_names: set[str] = set()
    # Built-in transformation catalog: singletons looked up by
    # bare name (``expectation``, ``log_prob``, …) and
    # constructors invoked with arguments (``softmax(B)``,
    # ``bayes_invert(prior)``).  Disjoint from
    # `_transformations`, which holds user define-bound
    # transformations defined inside the module.
    self._trans_singletons: dict = _build_default_trans_singletons()
    self._trans_constructors: dict = _build_default_trans_constructors()
    # User-defined transformations bound via ``define t = …``.
    # Disjoint from `_morphisms`: a ``define`` whose RHS
    # resolves to a transformation lands here; a ``define`` whose
    # RHS resolves to a morphism lands in ``_morphisms``.
    self._transformations: dict = {}
    self._objects: dict[str, SetObject] = {}
    self._spaces: dict = {}
    self._morphisms: dict = {}
    # The `~ Family(...)` prior of each `role=parameter` morphism that
    # declares one: a draw from the morphism draws from this family,
    # as the reference machine and every transpile target read it.
    self._latent_priors: dict[str, MorphismInitFamily] = {}
    self._groups: dict[str, list[str]] = {}
    self._output_expr: Expr | None = None
    # Parametric-program templates: dependent kernels Π(p:P).Kern(dom(p),cod(p))
    # stored as their unsubstituted AST decl. Instantiated at each call
    # site by parameter substitution + α-renaming of internal latents.
    self._program_templates: dict[str, ProgramDecl] = {}
    self._instantiated_program_contracts = {}
    # The located refusal of the first call each program keeps
    # because it cannot be lowered to compiled runtime steps.
    self._call_refusals: dict[str, CompileError] = {}
    # Every ``program`` declaration of the module by name, parametric
    # or not: the scope model a program's sites are addressed through.
    self._program_decls: dict[str, ProgramDecl] = {}
    # The parameter spaces of the program being compiled, innermost
    # last: its host data and its lets, by name.
    self._parameter_space_stack: list[dict[str, AnySpace]] = []
    # Nested latent kernels use the ordinary raw-network binding at
    # each site; the scoped context is compile-time metadata only.
    self._sampleable_context_stack: list[
        dict[tuple[str, str], tuple[ContinuousMorphism, str]]
    ] = []
    # The checked extents of the values the program being compiled
    # binds, innermost last, by name.
    self._value_extents_stack: list[dict[str, tuple[int, ...]]] = []
    # Operadic contraction declarations. Each entry is callable
    # from the DSL at define-binding sites; the value records the
    # compiled `EinsumWiring` plus the declared domain /
    # codomain typing for shape-checking at invocation time.
    self._contractions: dict[str, "_CompiledContraction"] = {}
    # The step programs the expansion of a scan over a program cell
    # declares, their compiled forms, and the learned initial state
    # of each scan that declares one, shared by name as the checked
    # elaboration shares its `weight` input.
    self._scan_step_declarations: dict[str, ProgramDecl] = {}
    self._scan_step_programs: dict[str, MonadicProgram] = {}
    self._scan_initial_states: dict[str, nn.Parameter] = {}
    # The network of each latent-weight kernel, which a draw through
    # the kernel applies at the run's drawn weights.
    self._latent_networks: dict[str, LearnedFunction] = {}

categories property

categories: list[str]

The declared category atoms.

rules property

rules: dict

The compiled rule schemas from rule declarations.

objects property

objects: dict[str, SetObject]

The compiled object environment.

spaces property

spaces: dict

The compiled space environment.

morphisms property

morphisms: dict

The compiled morphism environment.

algebra property

algebra: Algebra

The active algebra.

programs property

programs: dict[str, ProgramDecl]

Every declared program, by name.

A program with typed parameters (a template) and one without both appear: each is a scope whose parameters and sites are addressed by program::site paths. A program without typed parameters also compiles to a morphism, listed in morphisms.

deductions property

deductions: dict

Declared deduction systems (deduction NAME : ...).

syntaxes property

syntaxes: dict

Declared binding signatures (syntax NAME).

encoders property

encoders: dict

Declared encoders (encoder NAME : Sig).

decoders property

decoders: dict

Declared decoders (decoder NAME : Sig).

losses property

losses: dict

Declared loss heads (loss NAME : ... [on=...]).

Keyed by entry name; values are the registered :class:LossEntry records. Empty when no loss decl appears in the module.

bundles property

bundles: dict[str, tuple[str, ...]]

Declared bundle aliases (bundle NAME = R1 | R2 | ...).

contractions property

contractions: dict

Declared tensor-network contractions (contraction NAME : ... [wiring=...]).

transformations property

transformations: dict

User-declared transformation constructors / singletons.

qiec_module property

qiec_module: QiecModule | None

The checked QIEC module, or None when the source has no QIEC surface.

RETURNS DESCRIPTION
QiecModule | None

The module, lowered on first access.

RAISES DESCRIPTION
QiecDiagnosticError

If the source's QIEC surface fails to lower, other than by a program gap, which the module records instead.

qiec_generated_declarations property

qiec_generated_declarations: tuple[GeneratedDeclaration, ...]

Return generated declarations retained by the cached QIEC check.

relation_specs property

relation_specs: dict[str, RationalRelationSpec]

Return the checked authored relation specifications in this source.

RETURNS DESCRIPTION
dict[str, RationalRelationSpec]

Topologies and live weight identities keyed by source name.

composed_relation_specs property

composed_relation_specs: dict[str, ComposedRelationSpec]

Return checked binary compositions keyed by their authored names.

RETURNS DESCRIPTION
dict[str, ComposedRelationSpec]

Ordered operand specifications and original weight identities.

transformed_relation_specs property

Return checked sparse transformations by their authored names.

RETURNS DESCRIPTION
dict[str, UnaryRelationTransformSpec | BinaryRelationTransformSpec | RelationCascadeSpec]

Ordered original operands and selected sparse operations, including cascades.

string_graph_specs property

string_graph_specs: dict[str, StringFactorGraphSpec]

Return checked string graphs by their authored names.

RETURNS DESCRIPTION
dict[str, StringFactorGraphSpec]

Ordered observations and factor scopes with original relation identities.

deferred_statements property

deferred_statements: tuple[Statement, ...]

Authored declarations awaiting finite-object specialization.

RETURNS DESCRIPTION
tuple[Statement, ...]

Uncompiled declarations in source order, retaining their authored types. No finite cardinalities are invented for these declarations.

entry_points

entry_points() -> tuple[EntryPoint, ...]

The executable entry points of the checked module.

RETURNS DESCRIPTION
tuple[EntryPoint, ...]

Every program and define computation, in declaration order; empty when the source has no checked module.

Source code in src/quivers/dsl/compiler/core.py
def entry_points(self) -> tuple[EntryPoint, ...]:
    """The executable entry points of the checked module.

    Returns
    -------
    tuple[EntryPoint, ...]
        Every ``program`` and ``define`` computation, in declaration
        order; empty when the source has no checked module.
    """
    module = self.qiec_module
    if module is None:
        return ()
    return entry_points(module)

entry

entry(name: str) -> EntryPoint

One entry point of the checked module, by name.

PARAMETER DESCRIPTION
name

The entry's source name.

TYPE: str

RETURNS DESCRIPTION
EntryPoint

The entry.

RAISES DESCRIPTION
ExecutionFailure

With code qiec-run-module if the source has no checked module, or qiec-run-computation for an unknown name.

Source code in src/quivers/dsl/compiler/core.py
def entry(self, name: str) -> EntryPoint:
    """One entry point of the checked module, by name.

    Parameters
    ----------
    name : str
        The entry's source name.

    Returns
    -------
    EntryPoint
        The entry.

    Raises
    ------
    ExecutionFailure
        With code ``qiec-run-module`` if the source has no checked
        module, or ``qiec-run-computation`` for an unknown name.
    """
    module = self.qiec_module
    if module is None:
        raise ExecutionFailure(
            ExecutionDiagnostic(
                code="qiec-run-module",
                message="the source has no checked module and no entry points",
                computation=name,
            )
        )
    if module.gap and not any(point.name == name for point in entry_points(module)):
        raise ExecutionFailure(
            ExecutionDiagnostic(
                code="qiec-program-gap",
                message=f"entry point {name!r} was not lowered: {module.gap}",
                computation=name,
            )
        )
    return entry_point(module, name)

authored_checkpointed_gradient

authored_checkpointed_gradient(name: str, arguments: tuple[int | Fraction, ...], *, max_work: int = 65536, fuel: int = 65536) -> ExactCheckpointCertificate

Differentiate a named source iteration using checkpoint replay.

PARAMETER DESCRIPTION
name

The module-local checkpoint derivative declaration.

TYPE: str

arguments

The exact initial state and shared parameters in declared order.

TYPE: tuple of int or Fraction

max_work

The bound on transition evaluations, including replay.

TYPE: int DEFAULT: 65536

fuel

The reference step budget per transition evaluation.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
ExactCheckpointCertificate

The checked source identities, derived step count and measured result.

RAISES DESCRIPTION
ValueError

If the declaration is absent or the request arguments are malformed.

QiecDiagnosticError

If the source fails the checkpoint call-chain check.

JvpUnsupported

If a reached transition fails the regular scalar derivative check.

JvpLimit

If evaluation exhausts a resource limit.

Source code in src/quivers/dsl/compiler/core.py
def authored_checkpointed_gradient(
    self,
    name: str,
    arguments: tuple[int | Fraction, ...],
    *,
    max_work: int = 65_536,
    fuel: int = 65_536,
) -> ExactCheckpointCertificate:
    """Differentiate a named source iteration using checkpoint replay.

    Parameters
    ----------
    name : str
        The module-local checkpoint derivative declaration.
    arguments : tuple of int or Fraction
        The exact initial state and shared parameters in declared order.
    max_work : int
        The bound on transition evaluations, including replay.
    fuel : int
        The reference step budget per transition evaluation.

    Returns
    -------
    ExactCheckpointCertificate
        The checked source identities, derived step count and measured result.

    Raises
    ------
    ValueError
        If the declaration is absent or the request arguments are malformed.
    QiecDiagnosticError
        If the source fails the checkpoint call-chain check.
    JvpUnsupported
        If a reached transition fails the regular scalar derivative check.
    JvpLimit
        If evaluation exhausts a resource limit.
    """
    module = self.qiec_module
    if self._qiec_source is not None and module is not None:
        claims = _authored_checkpoint_derivatives(
            self._qiec_source, module, self._qiec_file_path
        )
        if name in claims:
            primal, transition, steps = claims[name]
            return _certify_checkpoint_gradient(
                module,
                primal,
                transition,
                steps,
                arguments,
                max_work=max_work,
                fuel=fuel,
            )
    raise ValueError(f"unknown authored checkpoint derivative `{name}`")

authored_implicit_gradient

authored_implicit_gradient(name: str, arguments: tuple[int | Fraction, ...], *, max_work: int = 65536, fuel: int = 65536) -> ExactImplicitCertificate

Check a named source computation's implicit derivative.

PARAMETER DESCRIPTION
name

The module-local implicit derivative claim.

TYPE: str

arguments

The exact point in the primal's parameter order.

TYPE: tuple of int or Fraction

max_work

The arithmetic budget for the rational composition proof.

TYPE: int DEFAULT: 65536

fuel

The reference evaluator step budget per run.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
ExactImplicitCertificate

The named definitions, strict domain, and local derivative.

RAISES DESCRIPTION
ValueError

If the claim is missing or the request arguments are malformed.

QiecDiagnosticError

If a definition in the declaration fails nominal resolution.

ImplicitRootError

If the identity is false or the reached root is singular.

JvpUnsupported

If an exact rational proof or a regular scalar evaluation is unavailable.

JvpLimit

If the proof or evaluation exhausts a bound.

Source code in src/quivers/dsl/compiler/core.py
def authored_implicit_gradient(
    self,
    name: str,
    arguments: tuple[int | Fraction, ...],
    *,
    max_work: int = 65_536,
    fuel: int = 65_536,
) -> ExactImplicitCertificate:
    """Check a named source computation's implicit derivative.

    Parameters
    ----------
    name : str
        The module-local implicit derivative claim.
    arguments : tuple of int or Fraction
        The exact point in the primal's parameter order.
    max_work : int
        The arithmetic budget for the rational composition proof.
    fuel : int
        The reference evaluator step budget per run.

    Returns
    -------
    ExactImplicitCertificate
        The named definitions, strict domain, and local derivative.

    Raises
    ------
    ValueError
        If the claim is missing or the request arguments are malformed.
    QiecDiagnosticError
        If a definition in the declaration fails nominal resolution.
    ImplicitRootError
        If the identity is false or the reached root is singular.
    JvpUnsupported
        If an exact rational proof or a regular scalar evaluation is unavailable.
    JvpLimit
        If the proof or evaluation exhausts a bound.
    """
    module = self.qiec_module
    if self._qiec_source is not None and module is not None:
        claims = _authored_implicit_derivatives(
            self._qiec_source, module, self._qiec_file_path
        )
        if name in claims:
            primal, residual = claims[name]
            return _certify_implicit_gradient(
                module, primal, residual, arguments, max_work=max_work, fuel=fuel
            )
    raise ValueError(f"unknown authored implicit derivative `{name}`")

authored_derivative_rule

authored_derivative_rule(name: str) -> RationalDerivativeDeclaration

Resolve a source claim's scalar derivative actions by checked identity.

PARAMETER DESCRIPTION
name

The module-local name in the authored effect law declaration.

TYPE: str

RETURNS DESCRIPTION
RationalDerivativeDeclaration

The named primal and actions in the checked source. Use the derivative checker or an effect plan request to check the formulas.

RAISES DESCRIPTION
ValueError

If the checked source has no derivative declaration of this name.

QiecDiagnosticError

If the source fails to lower or names an unknown computation.

Source code in src/quivers/dsl/compiler/core.py
def authored_derivative_rule(self, name: str) -> RationalDerivativeDeclaration:
    """Resolve a source claim's scalar derivative actions by checked identity.

    Parameters
    ----------
    name : str
        The module-local name in the authored effect law declaration.

    Returns
    -------
    RationalDerivativeDeclaration
        The named primal and actions in the checked source. Use the
        derivative checker or an effect plan request to check the formulas.

    Raises
    ------
    ValueError
        If the checked source has no derivative declaration of this name.
    QiecDiagnosticError
        If the source fails to lower or names an unknown computation.
    """
    module = self.qiec_module
    if self._qiec_source is not None and module is not None:
        rules = _authored_derivative_rules(
            self._qiec_source, module, self._qiec_file_path
        )
        if name in rules:
            return rules[name]
    raise ValueError(f"unknown authored derivative rule `{name}`")

authored_bernoulli_completion

authored_bernoulli_completion(name: str, arguments: tuple[int | Fraction, ...], direction: tuple[int | Fraction, ...], *, completed_module: QiecModule | None = None, fuel: int = 65536) -> BernoulliCompletion

Check a named source completion at an exact point and direction.

PARAMETER DESCRIPTION
name

The named completion in the checked source.

TYPE: str

arguments

The original computation's arguments and an exact direction.

TYPE: tuple of int or Fraction

direction

The original computation's arguments and an exact direction.

TYPE: tuple of int or Fraction

completed_module

An optional completed graph to verify against the declaration.

TYPE: QiecModule or None DEFAULT: None

fuel

The step limit for each ordinary replay.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
BernoulliCompletion

The completed graph and the exact original, extended and projected addressed histories at the requested point.

RAISES DESCRIPTION
ValueError

If the completion does not exist or the arguments are invalid.

QiecDiagnosticError

If the parsed source or completion fails to lower.

JvpUnsupported

If the point or completed graph leaves the checked fragment.

JvpLimit

If the exact replay exhausts its bound.

Source code in src/quivers/dsl/compiler/core.py
def authored_bernoulli_completion(
    self,
    name: str,
    arguments: tuple[int | Fraction, ...],
    direction: tuple[int | Fraction, ...],
    *,
    completed_module: QiecModule | None = None,
    fuel: int = 65_536,
) -> BernoulliCompletion:
    """Check a named source completion at an exact point and direction.

    Parameters
    ----------
    name : str
        The named completion in the checked source.
    arguments, direction : tuple of int or Fraction
        The original computation's arguments and an exact direction.
    completed_module : QiecModule or None
        An optional completed graph to verify against the declaration.
    fuel : int
        The step limit for each ordinary replay.

    Returns
    -------
    BernoulliCompletion
        The completed graph and the exact original, extended and
        projected addressed histories at the requested point.

    Raises
    ------
    ValueError
        If the completion does not exist or the arguments are invalid.
    QiecDiagnosticError
        If the parsed source or completion fails to lower.
    JvpUnsupported
        If the point or completed graph leaves the checked fragment.
    JvpLimit
        If the exact replay exhausts its bound.
    """
    module, source = self.qiec_module, self._qiec_source
    if module is not None and source is not None:
        claims = _authored_bernoulli_completions(
            source, module, self._qiec_file_path
        )
        if name in claims:
            computation, auxiliaries = claims[name]
            return plan_bernoulli_completion(
                module,
                computation,
                arguments,
                direction,
                auxiliaries,
                completed_module=completed_module,
                fuel=fuel,
            )
    raise ValueError(f"unknown authored Bernoulli completion `{name}`")

authored_site_estimators

authored_site_estimators(computation: str) -> tuple[SiteEstimator, ...]

Return the explicit estimator policies for one lexical computation.

PARAMETER DESCRIPTION
computation

The name of the authored computation containing the sample requests.

TYPE: str

RETURNS DESCRIPTION
tuple of SiteEstimator

The policies in source order, bound to the original static sites. A computation with no assignments has an empty tuple. The estimator planner checks which sites execute at its point.

RAISES DESCRIPTION
ValueError

If the source has no authored computation of this name.

QiecDiagnosticError

If the checked source or an estimator assignment fails to lower.

Source code in src/quivers/dsl/compiler/core.py
def authored_site_estimators(self, computation: str) -> tuple[SiteEstimator, ...]:
    """Return the explicit estimator policies for one lexical computation.

    Parameters
    ----------
    computation : str
        The name of the authored computation containing the sample requests.

    Returns
    -------
    tuple of SiteEstimator
        The policies in source order, bound to the original static
        sites. A computation with no assignments has an empty tuple.
        The estimator planner checks which sites execute at its point.

    Raises
    ------
    ValueError
        If the source has no authored computation of this name.
    QiecDiagnosticError
        If the checked source or an estimator assignment fails to lower.
    """
    module, source = self.qiec_module, self._qiec_source
    if (
        module is not None
        and source is not None
        and any(
            isinstance(item, QiecComputationDecl) and item.name == computation
            for item in source.statements
        )
    ):
        return _authored_site_estimators(source, module, self._qiec_file_path).get(
            computation, ()
        )
    raise ValueError(f"unknown authored site-estimator computation `{computation}`")

effect_plan

effect_plan(name: str, *, obligations: tuple[EffectLawObligation, ...] = (), interchanges: tuple[FiniteHandlerInterchange, ...] = (), law_evidence: tuple[EffectLawEvidence, ...] = (), max_assignments: int = 65536, max_work: int = 65536, fuel: int = 65536) -> EffectPlan

Report checked effect analysis for one of the source's entry points.

PARAMETER DESCRIPTION
name

The program or computation entry point's name.

TYPE: str

obligations

The additional nominal equations to check alongside this source's authored finite laws.

TYPE: tuple[EffectLawObligation, ...] DEFAULT: ()

interchanges

The additional finite handler interchanges to check after those declared in the source.

TYPE: tuple[FiniteHandlerInterchange, ...] DEFAULT: ()

law_evidence

Claimed tests or assumptions bound to the requested obligations.

TYPE: tuple[EffectLawEvidence, ...] DEFAULT: ()

max_assignments

The domain size limit per finite obligation.

TYPE: int DEFAULT: 65536

max_work

The work limit per scalar obligation.

TYPE: int DEFAULT: 65536

fuel

The step limit per side and assignment in an exact interpreter.

TYPE: int DEFAULT: 65536

RETURNS DESCRIPTION
EffectPlan

The entry's carrier reports, separately checked obligations, and the stages and obstacles of the ordinary discharge result. For a program, retains the matching parsed source for target reports on the public export.

RAISES DESCRIPTION
ExecutionFailure

If the source does not have the named checked entry point.

ValueError

If a requested resource limit is invalid.

Source code in src/quivers/dsl/compiler/core.py
def effect_plan(
    self,
    name: str,
    *,
    obligations: tuple[EffectLawObligation, ...] = (),
    interchanges: tuple[FiniteHandlerInterchange, ...] = (),
    law_evidence: tuple[EffectLawEvidence, ...] = (),
    max_assignments: int = 65_536,
    max_work: int = 65_536,
    fuel: int = 65_536,
) -> EffectPlan:
    """Report checked effect analysis for one of the source's entry points.

    Parameters
    ----------
    name : str
        The program or computation entry point's name.
    obligations : tuple[EffectLawObligation, ...]
        The additional nominal equations to check alongside this source's
        authored finite laws.
    interchanges : tuple[FiniteHandlerInterchange, ...]
        The additional finite handler interchanges to check after
        those declared in the source.
    law_evidence : tuple[EffectLawEvidence, ...]
        Claimed tests or assumptions bound to the requested obligations.
    max_assignments : int
        The domain size limit per finite obligation.
    max_work : int
        The work limit per scalar obligation.
    fuel : int
        The step limit per side and assignment in an exact interpreter.

    Returns
    -------
    EffectPlan
        The entry's carrier reports, separately checked obligations,
        and the stages and obstacles of the ordinary discharge result.
        For a program, retains the matching parsed source for target
        reports on the public export.

    Raises
    ------
    ExecutionFailure
        If the source does not have the named checked entry point.
    ValueError
        If a requested resource limit is invalid.
    """
    entry = self.entry(name)
    module = self.qiec_module
    assert module is not None
    if entry.kind == "program":
        root = next(
            item.computation for item in module.entries if item.name == name
        )
    else:
        root = next(item.id for item in module.computations if item.name == name)
    authored: tuple[tuple[str, FiniteHandlerInterchange], ...] = ()
    if self._qiec_source is not None:
        authored = _authored_effect_interchanges(
            self._qiec_source, module, self._qiec_file_path
        )
        obligations = (
            *_authored_effect_law_obligations(
                self._qiec_source, module, self._qiec_file_path
            ),
            *obligations,
        )
    plan = checked_effect_plan(
        EffectLawBundle(module=module, obligations=obligations),
        root,
        interchanges=(*(statement for _, statement in authored), *interchanges),
        law_evidence=law_evidence,
        max_assignments=max_assignments,
        max_work=max_work,
        fuel=fuel,
    )
    if authored:
        plan = plan._with_interchange_names(tuple(name for name, _ in authored))
    if entry.kind == "program" and self._qiec_source is not None:
        return plan._with_program_source(self._qiec_source)
    return plan

compile

compile() -> Program

Compile the module into a trainable Program.

RETURNS DESCRIPTION
Program

The compiled nn.Module wrapping the morphism DAG.

RAISES DESCRIPTION
CompileError

On semantic errors (undefined names, type mismatches, etc.), and for a module with typed holes, which has no compiled form; the message lists every hole.

Source code in src/quivers/dsl/compiler/core.py
def compile(self) -> Program:
    """Compile the module into a trainable Program.

    Returns
    -------
    Program
        The compiled nn.Module wrapping the morphism DAG.

    Raises
    ------
    CompileError
        On semantic errors (undefined names, type mismatches, etc.), and
        for a module with typed holes, which has no compiled form; the
        message lists every hole.
    """
    self._specialize_data_objects()
    checked = self.qiec_module
    if checked is not None:
        try:
            refuse_holes(checked, action="compilation to PyTorch")
        except HoleError as error:
            first = next(
                (hole.origin for hole in error.holes if hole.origin is not None),
                None,
            )
            line = 0 if first is None else first.line or 0
            column = 0 if first is None else first.column or 0
            raise CompileError(str(error), line, column) from error
    return self._build_program()

check

check() -> None

Compile the module to check it, without keeping a Program.

Every check compile makes is made, but no compiled program leaves the call, so a module with typed holes is checked around them: a hole is well typed at its goal, and only a compiled form has nowhere to put it.

RAISES DESCRIPTION
CompileError

On semantic errors, as compile raises them.

Source code in src/quivers/dsl/compiler/core.py
def check(self) -> None:
    """Compile the module to check it, without keeping a Program.

    Every check `compile` makes is made, but no compiled program
    leaves the call, so a module with typed holes is checked around
    them: a hole is well typed at its goal, and only a compiled form
    has nowhere to put it.

    Raises
    ------
    CompileError
        On semantic errors, as `compile` raises them.
    """
    self._specialize_data_objects()
    self._build_program()

compile_env

compile_env(*, defer_unresolved: bool = False) -> dict

Compile all statements and return the full environment.

Useful for inspection without requiring an output declaration.

PARAMETER DESCRIPTION
defer_unresolved

Retain unresolved finite objects and their dependent declarations symbolically, compiling independent declarations for inspection. False requires data to specialize every inferred object.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
dict

Combined environment of every declared atom: the active algebra, objects, spaces, morphisms, rules, programs (parametric templates), deductions, signatures, encoders, decoders, losses, bundles, contractions, transformations.

Source code in src/quivers/dsl/compiler/core.py
def compile_env(self, *, defer_unresolved: bool = False) -> dict:
    """Compile all statements and return the full environment.

    Useful for inspection without requiring an output declaration.

    Parameters
    ----------
    defer_unresolved : bool
        Retain unresolved finite objects and their dependent declarations
        symbolically, compiling independent declarations for inspection.
        False requires data to specialize every inferred object.

    Returns
    -------
    dict
        Combined environment of every declared atom: the active
        algebra, objects, spaces, morphisms, rules, programs
        (parametric templates), deductions, signatures, encoders,
        decoders, losses, bundles, contractions, transformations.
    """
    deferred = (
        self._inferred_dependency_projection() if defer_unresolved else frozenset()
    )
    self._deferred_statements = tuple(
        statement
        for index, statement in enumerate(self._module.statements)
        if index in deferred
    )
    if not deferred:
        self._specialize_data_objects()
    for index, stmt in enumerate(self._module.statements):
        if index in deferred:
            if isinstance(stmt, ProgramDecl):
                self._program_decls[stmt.name] = stmt
            continue
        self._compile_statement(stmt)
    self._finish_theories()
    self._finish_semirings()
    env: dict = {}
    env["__algebra__"] = self._algebra
    qiec_module = self.qiec_module
    if qiec_module is not None:
        self._attach_host_data_types(qiec_module)
        env["__qiec__"] = qiec_module
    for name, obj in self._objects.items():
        env[name] = obj
    for name, space in self._spaces.items():
        env[name] = space
    for name, morph in self._morphisms.items():
        env[name] = morph
    for name, rule in self._rules.items():
        env[name] = rule
    for name, tmpl in getattr(self, "_program_templates", {}).items():
        env[name] = tmpl
    for name, system in getattr(self, "_deductions", {}).items():
        env[name] = system
    for name, sig in getattr(self, "_signatures", {}).items():
        env[name] = sig
    for name, enc in getattr(self, "_encoders", {}).items():
        env[name] = enc
    for name, dec in getattr(self, "_decoders", {}).items():
        env[name] = dec
    reg = getattr(self, "_loss_registry", None)
    if reg is not None:
        for entry in reg.entries:
            env[entry.name] = entry
    for name, bundle in self._bundles.items():
        env[name] = bundle
    for name, contr in getattr(self, "_contractions", {}).items():
        env[name] = contr
    for statement in self._deferred_statements:
        names = getattr(statement, "names", ()) or (
            (statement.name,) if hasattr(statement, "name") else ()
        )
        for name in names:
            env.setdefault(name, statement)
    return env

CompileError

CompileError(message: str, line: int = 0, col: int = 0)

Bases: Exception

Raised when the compiler encounters a semantic error.

PARAMETER DESCRIPTION
message

Error description.

TYPE: str

line

Source line number (0 if unknown).

TYPE: int DEFAULT: 0

col

Source column number (0 if unknown).

TYPE: int DEFAULT: 0

Source code in src/quivers/dsl/compiler/_prelude.py
def __init__(self, message: str, line: int = 0, col: int = 0) -> None:
    self.message = message
    self.line = line
    self.col = col
    loc = f"line {line}, col {col}: " if line else ""
    super().__init__(f"{loc}{message}")

Violation didactic-model

Violation(*, code: str, message: str, line: int, col: int, severity: str = 'error')

Bases: Model

One constraint-solver finding.

Every finding check_constraints reports is an error. Compiler diagnostics that should surface in qvr check output without failing the compile set severity to "warning".

PARAMETER DESCRIPTION
code

The stable diagnostic code.

TYPE: str

message

What is wrong.

TYPE: str

line

The one-based source line.

TYPE: int

col

The source column.

TYPE: int

severity

"error" or "warning".

TYPE: str DEFAULT: 'error'

EmitError

Bases: Exception

Raised when an AST value has no valid .qvr surface form.

LetExprExtension

Bases: Protocol

Expose binder-free downstream expressions to canonical traversal.

An adapter lists every expression child in a stable order and rebuilds its node over children in that same order. It preserves all other fields. An extension cannot introduce a binder; binder scope and capture avoidance are defined by the shared surface AST, independently of the downstream IR.

children

children(node: LetExprNode) -> tuple[LetExprNode, ...] | None

Read the direct children of a supported extension.

PARAMETER DESCRIPTION
node

Expression that is not a canonical surface variant.

TYPE: LetExprNode

RETURNS DESCRIPTION
tuple[LetExprNode, ...] or None

All expression children in source order, or None for an unsupported node. An empty tuple denotes a supported leaf.

Source code in src/quivers/dsl/let_expr_traversal.py
def children(
    self, node: surface.LetExprNode
) -> tuple[surface.LetExprNode, ...] | None:
    """Read the direct children of a supported extension.

    Parameters
    ----------
    node : LetExprNode
        Expression that is not a canonical surface variant.

    Returns
    -------
    tuple[LetExprNode, ...] or None
        All expression children in source order, or None for an unsupported
        node. An empty tuple denotes a supported leaf.
    """
    ...

rebuild

rebuild(node: LetExprNode, children: tuple[LetExprNode, ...]) -> LetExprNode

Rebuild an extension without changing its non-expression metadata.

PARAMETER DESCRIPTION
node

Supported extension previously read by children.

TYPE: LetExprNode

children

Rewritten operands in the same order and arity.

TYPE: tuple[LetExprNode, ...]

RETURNS DESCRIPTION
LetExprNode

The reconstructed extension, retaining its other fields.

Source code in src/quivers/dsl/let_expr_traversal.py
def rebuild(
    self, node: surface.LetExprNode, children: tuple[surface.LetExprNode, ...]
) -> surface.LetExprNode:
    """Rebuild an extension without changing its non-expression metadata.

    Parameters
    ----------
    node : LetExprNode
        Supported extension previously read by children.
    children : tuple[LetExprNode, ...]
        Rewritten operands in the same order and arity.

    Returns
    -------
    LetExprNode
        The reconstructed extension, retaining its other fields.
    """
    ...

StructureEncodingError

Bases: ValueError

A statement holds a value no structure term represents.

StructureLayer didactic-model

StructureLayer(*, structures: tuple[StructureDecl, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), names: Mapping[StructureTarget, str] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

A module's structure declarations with the names their references use.

PARAMETER DESCRIPTION
structures

The declarations, in source order.

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

names

The name each referenced declaration has in the module.

TYPE: Mapping[StructureTarget, str] DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE)

ModuleError

ModuleError(diagnostic: ModuleDiagnostic)

Bases: Exception

Raised when the module graph does not load or a name does not resolve.

PARAMETER DESCRIPTION
diagnostic

The structured diagnostic.

TYPE: ModuleDiagnostic

ATTRIBUTE DESCRIPTION
diagnostic

The structured diagnostic.

TYPE: ModuleDiagnostic

Source code in src/quivers/dsl/modules/errors.py
def __init__(self, diagnostic: ModuleDiagnostic) -> None:
    self.diagnostic = diagnostic
    super().__init__(diagnostic.render())

code property

The diagnostic's code.

RETURNS DESCRIPTION
ModuleErrorCode

The stable code.

ParseError

Bases: Exception

Raised when .qvr source fails to parse or wrap into AST nodes.

parse and parse_file raise it with a message that starts with the file path and locates the first syntax error.

CompositionError

CompositionError(message: str, line: int, col: int)

Bases: ValueError

A deduction whose parts do not compose.

PARAMETER DESCRIPTION
message

What is wrong.

TYPE: str

line

Where.

TYPE: int

col

Where.

TYPE: int

Source code in src/quivers/dsl/deduction_composition.py
def __init__(self, message: str, line: int, col: int) -> None:
    super().__init__(message)
    self.line = line
    self.col = col

ExtensionVerdict didactic-model

ExtensionVerdict(*, deduction: str, signature: str, classification: Classification, reason: str, sentence: tuple[str, ...] = (), item: str = '', line: int = 0, col: int = 0)

Bases: Model

The classification of one deduction's extension of one signature.

PARAMETER DESCRIPTION
deduction

The extending deduction.

TYPE: str

signature

The extended signature.

TYPE: str

classification

What the checker established.

TYPE: Classification

reason

Why.

TYPE: str

sentence

For "neither", the sentence the witness parses.

TYPE: tuple[str, ...] DEFAULT: ()

item

For "neither", the item of the signature's language the extension derives on it and the signature's rules do not.

TYPE: str DEFAULT: ''

line

The deduction's location.

TYPE: int DEFAULT: 0

col

The deduction's location.

TYPE: int DEFAULT: 0

ReificationError

ReificationError(message: str, line: int, col: int)

Bases: ValueError

A signature whose item family or folds cannot be generated.

PARAMETER DESCRIPTION
message

What is wrong.

TYPE: str

line

Where.

TYPE: int

col

Where.

TYPE: int

Source code in src/quivers/dsl/deduction_reification.py
def __init__(self, message: str, line: int, col: int) -> None:
    super().__init__(message)
    self.line = line
    self.col = col

SchemaError

SchemaError(message: str, line: int, col: int)

Bases: ValueError

A rule schema or instantiation that does not denote a finite rule set.

PARAMETER DESCRIPTION
message

What is wrong.

TYPE: str

line

Where.

TYPE: int

col

Where.

TYPE: int

Source code in src/quivers/dsl/deduction_schemata.py
def __init__(self, message: str, line: int, col: int) -> None:
    super().__init__(message)
    self.line = line
    self.col = col

QvrLexer

Bases: Lexer

Pygments lexer for .qvr (quivers DSL) files.

The lexer is a thin walker over the in-tree tree-sitter parse; the grammar is the single source of truth. There is no regex approximation: when the shared library can't be loaded, the lexer raises a typed exception so the failure is visible at the rendering site rather than silently emitting a degraded highlight.

get_tokens_unprocessed

get_tokens_unprocessed(text: str) -> Iterator[tuple[int, _TokenType, str]]

Yield (index, token_type, text) tuples for text.

PARAMETER DESCRIPTION
text

The .qvr source to tokenize.

TYPE: str

YIELDS DESCRIPTION
tuple[int, _TokenType, str]

The character offset, Pygments token type, and text of each leaf of the parse and of the whitespace between leaves.

RAISES DESCRIPTION
OSError

If the in-tree tree-sitter parser library cannot be loaded.

Source code in src/quivers/dsl/pygments_lexer.py
def get_tokens_unprocessed(
    self, text: str
) -> Iterator[tuple[int, _TokenType, str]]:
    """Yield ``(index, token_type, text)`` tuples for ``text``.

    Parameters
    ----------
    text : str
        The ``.qvr`` source to tokenize.

    Yields
    ------
    tuple[int, _TokenType, str]
        The character offset, Pygments token type, and text of each
        leaf of the parse and of the whitespace between leaves.

    Raises
    ------
    OSError
        If the in-tree tree-sitter parser library cannot be loaded.
    """
    parser, _, _ = _load_parser()
    src_bytes = text.encode("utf-8")
    tree = parser.parse(src_bytes)

    # Walk leaf-first in source order, emitting tokens for
    # each leaf and reproducing inter-leaf whitespace as Text.
    leaves: list[tuple[tree_sitter.Node, str | None, str | None]] = []

    def walk(
        node: tree_sitter.Node,
        parent_kind: str | None,
        field_name: str | None,
    ) -> None:
        if not node.children:
            leaves.append((node, parent_kind, field_name))
            return
        for index, child in enumerate(node.children):
            walk(child, node.type, node.field_name_for_child(index))

    walk(tree.root_node, None, None)

    cursor = 0
    for node, parent_kind, field_name in leaves:
        start = node.start_byte
        end = node.end_byte
        if start > cursor:
            gap = src_bytes[cursor:start].decode("utf-8")
            if gap:
                yield (_byte_to_char_offset(src_bytes, cursor), Text, gap)
        node_text = src_bytes[start:end].decode("utf-8")
        parts = _contextual_token_parts(node, node_text, parent_kind, field_name)
        offset = _byte_to_char_offset(src_bytes, start)
        if parts:
            for token, part in parts:
                yield (offset, token, part)
                offset += len(part)
        else:
            token = _node_kind_to_pygments_token(
                node.type, node_text, parent_kind, field_name
            )
            yield (offset, token, node_text)
        cursor = end
    if cursor < len(src_bytes):
        tail = src_bytes[cursor:].decode("utf-8")
        if tail:
            yield (_byte_to_char_offset(src_bytes, cursor), Text, tail)

QiecDiagnosticError

QiecDiagnosticError(message: str, *, code: str, file: str, line: int = 0, column: int = 0, program: str | None = None)

Bases: ValueError

A source-located, stable-code diagnostic from QIEC elaboration.

PARAMETER DESCRIPTION
message

What was rejected.

TYPE: str

code

The stable diagnostic code.

TYPE: str

file

The file the source was read from.

TYPE: str

line

The one-based line, or zero when unknown.

TYPE: int DEFAULT: 0

column

The zero-based column.

TYPE: int DEFAULT: 0

program

The program whose elaboration raised the diagnostic, when it was raised inside a program body; None for any other declaration.

TYPE: str | None DEFAULT: None

Source code in src/quivers/dsl/qiec_diagnostics.py
def __init__(
    self,
    message: str,
    *,
    code: str,
    file: str,
    line: int = 0,
    column: int = 0,
    program: str | None = None,
) -> None:
    self.message = message
    self.code = code
    self.file = file
    self.line = line
    self.column = column
    self.program = program
    location = f"{file}:{line}:{column}" if line else file
    super().__init__(f"{location}: [{code}] {message}")

InferenceError

InferenceError(message: str, node: object)

Bases: ValueError

An expression has no type, or one inference cannot find.

PARAMETER DESCRIPTION
message

What failed.

TYPE: str

node

The source node, read for its line and column.

TYPE: object

Source code in src/quivers/dsl/row_inference.py
def __init__(self, message: str, node: object) -> None:
    super().__init__(message)
    self.line = int(getattr(node, "line", 0))
    self.col = int(getattr(node, "col", 0))

TypeScheme didactic-model

TypeScheme(*, binders: Telescope = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), predicates: tuple[RowPredicate, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), type: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A principal type: a type over variables and the predicates they meet.

PARAMETER DESCRIPTION
binders

The type and row variables, in order of first occurrence.

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

predicates

The row predicates every instance must meet.

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

type

The type.

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

render

render() -> str

Write the scheme in source spelling.

RETURNS DESCRIPTION
str

forall a r. P => T, or the bare type when nothing is generalized.

Source code in src/quivers/dsl/row_inference.py
def render(self) -> str:
    """Write the scheme in source spelling.

    Returns
    -------
    str
        ``forall a r. P => T``, or the bare type when nothing is
        generalized.
    """
    rendered = render_static(self.type)
    if self.predicates:
        constraints = ", ".join(render_predicate(item) for item in self.predicates)
        rendered = f"{constraints} => {rendered}"
    if self.binders:
        rendered = (
            f"forall {' '.join(binder.name for binder in self.binders)}. {rendered}"
        )
    return rendered

CheckedQvrQiec didactic-model

CheckedQvrQiec(*, module: QiecModule = field(opaque=True, extras=OPAQUE_BY_VALUE), closed_interpretations: tuple[ClosedInterpretationBinding, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), packed_interpretations: tuple[PackedBooleanInterpretationBinding, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), generated_declarations: tuple[GeneratedDeclaration, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

The checked result passed between Didactic's ordered stages.

PARAMETER DESCRIPTION
module

The kernel module the stages produced.

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

closed_interpretations

Source companions retained through checked model schema extraction.

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

packed_interpretations

Each verified invocation of a closed interpretation's packed form.

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

generated_declarations

Source declarations and their provenance from the checked meta expansion.

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

QvrQiecLowerer

Quivers-owned implementation of Didactic's extension-lowering protocol.

check

check(source: QvrQiecSource) -> CheckedQvrQiec

Elaborate a source module and recheck the result.

The recheck is deliberate rather than redundant: it rebuilds a registry from the lowered module alone, so a bug in elaboration surfaces here instead of reaching a backend.

PARAMETER DESCRIPTION
source

The QIEC projection, its module name, and its file path.

TYPE: QvrQiecSource

RETURNS DESCRIPTION
CheckedQvrQiec

The checked module.

RAISES DESCRIPTION
QiecDiagnosticError

If elaboration rejects the source, carrying a stable code and a source position.

KernelError

If the lowered module fails its independent recheck.

Source code in src/quivers/dsl/qiec_lowering.py
def check(self, source: QvrQiecSource, /) -> CheckedQvrQiec:
    """Elaborate a source module and recheck the result.

    The recheck is deliberate rather than redundant: it rebuilds a
    registry from the lowered module alone, so a bug in elaboration
    surfaces here instead of reaching a backend.

    Parameters
    ----------
    source : QvrQiecSource
        The QIEC projection, its module name, and its file path.

    Returns
    -------
    CheckedQvrQiec
        The checked module.

    Raises
    ------
    QiecDiagnosticError
        If elaboration rejects the source, carrying a stable code and
        a source position.
    KernelError
        If the lowered module fails its independent recheck.
    """
    _check_named_law_calls(
        source.syntax,
        FAMILIES.keys() | {family.name for family in source.distribution_families},
        source.file_path,
    )
    elaborator = _Elaborator(source)
    module = elaborator.elaborate()
    registry = validate_module(module)
    check_prefold_interpretations(elaborator, module, registry)
    _authored_effect_law_obligations(source.syntax, module, source.file_path)
    _check_local_effect_theories(source.syntax, module, source.file_path)
    _authored_effect_interchanges(source.syntax, module, source.file_path)
    _authored_derivative_rules(source.syntax, module, source.file_path)
    _authored_bernoulli_completions(source.syntax, module, source.file_path)
    _authored_checkpoint_derivatives(source.syntax, module, source.file_path)
    _authored_implicit_derivatives(source.syntax, module, source.file_path)
    _authored_site_estimators(source.syntax, module, source.file_path)
    closed = tuple(elaborator.closed_interpretations)
    packed = tuple(elaborator.packed_interpretations)
    check_packed_boolean_bindings(module, registry, closed, packed)
    return CheckedQvrQiec(
        module=module,
        closed_interpretations=closed,
        packed_interpretations=packed,
    )

lower

lower(checked: CheckedQvrQiec) -> QiecModule

Return the checked module.

Checking and lowering are one step here, because the elaborator produces the kernel module directly, so this unwraps rather than transforms.

PARAMETER DESCRIPTION
checked

The result of check.

TYPE: CheckedQvrQiec

RETURNS DESCRIPTION
QiecModule

The lowered module.

Source code in src/quivers/dsl/qiec_lowering.py
def lower(self, checked: CheckedQvrQiec, /) -> QiecModule:
    """Return the checked module.

    Checking and lowering are one step here, because the elaborator
    produces the kernel module directly, so this unwraps rather than
    transforms.

    Parameters
    ----------
    checked : CheckedQvrQiec
        The result of `check`.

    Returns
    -------
    QiecModule
        The lowered module.
    """
    return checked.module

validate

validate(target: QiecModule) -> None

Recheck a module and confirm it survives serialization.

PARAMETER DESCRIPTION
target

The module to validate.

TYPE: QiecModule

RAISES DESCRIPTION
KernelError

If the module fails its recheck, or if a dump and load round trip does not return an equal module. The second is checked because identities downstream are content addressed: a module that changed under serialization would hash differently on the other side of the boundary.

Source code in src/quivers/dsl/qiec_lowering.py
def validate(self, target: QiecModule, /) -> None:
    """Recheck a module and confirm it survives serialization.

    Parameters
    ----------
    target : QiecModule
        The module to validate.

    Raises
    ------
    KernelError
        If the module fails its recheck, or if a dump and load round
        trip does not return an equal module. The second is checked
        because identities downstream are content addressed: a module
        that changed under serialization would hash differently on
        the other side of the boundary.
    """
    validate_module(target)
    if has_holes(target):
        # A module with typed holes checks but has no stable form; every
        # export path refuses it, so there is no round trip to confirm.
        return
    decoded = loads(dumps(target))
    if decoded != target:
        raise KernelError("QIEC module changed during canonical serialization")

QvrQiecSource didactic-model

QvrQiecSource(*, syntax: Module, module_name: str, file_path: str = '<source>', elaborate_programs: bool = True, distribution_families: tuple[DistributionFamily, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), prechecked: QiecModule | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), structures: tuple[StructureDecl, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), spellings: tuple[NameSpelling, ...] = ())

Bases: ValueModel

A parsed QVR projection plus the identity absent from the AST root.

PARAMETER DESCRIPTION
syntax

The projected module.

TYPE: Module

module_name

The name every stable identity derives from.

TYPE: str

file_path

The path recorded on diagnostics.

TYPE: str DEFAULT: '<source>'

elaborate_programs

Whether program declarations become computations. A caller that has found a program using a construct the elaboration does not yet cover lowers the rest of the module without it.

TYPE: bool DEFAULT: True

prechecked

A module already checked from declarations of this syntax under the same module name, such as a library shared by many modules and checked from its own file. A computation declaration whose name and origin, apart from the file, match one of its computations is not lowered again: that computation is reused, with the families its lowering generated. The module's independent recheck still checks it.

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

structures

The module's structure declarations, which the checked module records beside its computations.

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

spellings

How the program's root module writes the names other modules declare, which generated printers write them as.

TYPE: tuple[NameSpelling, ...] DEFAULT: ()

LawReport didactic-model

LawReport(*, signature: str, instance: str, status: Literal['checked', 'assumed'], reason: str = '')

Bases: Model

How one module met its obligation to a signature's laws.

ATTRIBUTE DESCRIPTION
signature

The signature.

TYPE: str

instance

The module.

TYPE: str

status

checked when every law held at every assignment of the module's finite carriers; assumed when a carrier is not finite, so the laws are recorded as assumed rather than passed.

TYPE: Literal['checked', 'assumed']

reason

For an assumed obligation, why it could not be checked.

TYPE: str

check_constraints

check_constraints(module: Module) -> list[Violation]

Return every well-formedness violation in module.

Walks the statements in source order, building up the symbol tables (residuated universes, enum sets, free monoids, declared rule / schema / bundle names) incrementally so that out-of-order references are flagged.

PARAMETER DESCRIPTION
module

The parsed module to check.

TYPE: Module

RETURNS DESCRIPTION
list[Violation]

The findings in source order, empty for a well-formed module.

Source code in src/quivers/dsl/constraints.py
def check_constraints(module: Module) -> list[Violation]:
    """Return every well-formedness violation in ``module``.

    Walks the statements in source order, building up the symbol
    tables (residuated universes, enum sets, free monoids, declared
    rule / schema / bundle names) incrementally so that out-of-order
    references are flagged.

    Parameters
    ----------
    module : Module
        The parsed module to check.

    Returns
    -------
    list[Violation]
        The findings in source order, empty for a well-formed module.
    """
    out: list[Violation] = []

    residuated_universes: dict[str, TypeFreeResiduated] = {}
    enum_sets: dict[str, TypeEnumSet] = {}
    free_monoids: dict[str, TypeFreeMonoid] = {}
    aliased_names: dict[str, ObjectExpr] = {}
    rule_names: set[str] = set()
    schema_names: set[str] = set()
    bundle_names: set[str] = set()
    category_atoms: set[str] = set()

    builtin_schemas = set(SCHEMA_REGISTRY.keys())

    def is_residuated_object(name: str) -> bool:
        """True iff ``name`` resolves (via aliases) to a residuated universe."""
        seen: set[str] = set()
        cur = name
        while cur not in seen:
            seen.add(cur)
            if cur in residuated_universes:
                return True
            if cur in aliased_names:
                rhs = aliased_names[cur]
                if isinstance(rhs, TypeName):
                    cur = rhs.name
                    continue
            return False
        return False

    def is_known_effect(name: str) -> bool:
        """True iff ``name`` matches the conventional effect-naming pattern."""
        return bool(name) and (name[0].isupper() or "_" in name)

    def walk_pattern(
        texpr: ObjectExpr,
        *,
        in_residuated_context: bool,
        line_hint: int = 0,
        col_hint: int = 0,
    ) -> None:
        if isinstance(texpr, TypeName):
            return
        if isinstance(texpr, ObjectProduct):
            for c in texpr.components:
                walk_pattern(
                    c,
                    in_residuated_context=in_residuated_context,
                    line_hint=line_hint,
                    col_hint=col_hint,
                )
            return
        if isinstance(texpr, ObjectCoproduct):
            for c in texpr.components:
                walk_pattern(
                    c,
                    in_residuated_context=in_residuated_context,
                    line_hint=line_hint,
                    col_hint=col_hint,
                )
            return
        if isinstance(texpr, ObjectSlash):
            if not in_residuated_context:
                line = texpr.line or line_hint
                col = texpr.col or col_hint
                out.append(
                    Violation(
                        code="residuated_constraint",
                        message=(
                            f"ObjectSlash {texpr.direction!r} appears "
                            "outside a residuated context; either "
                            "declare a FreeResiduated universe and "
                            "parameterize the schema by it, or remove "
                            "the slash"
                        ),
                        line=line,
                        col=col,
                    )
                )
            walk_pattern(
                texpr.result,
                in_residuated_context=in_residuated_context,
                line_hint=line_hint,
                col_hint=col_hint,
            )
            walk_pattern(
                texpr.argument,
                in_residuated_context=in_residuated_context,
                line_hint=line_hint,
                col_hint=col_hint,
            )
            return
        if isinstance(texpr, ObjectEffectApply):
            if not is_known_effect(texpr.effect):
                line = texpr.line or line_hint
                col = texpr.col or col_hint
                out.append(
                    Violation(
                        code="effect_constraint",
                        message=(
                            f"effect {texpr.effect!r} has no "
                            "recognized naming pattern; effect names "
                            "must start with an uppercase letter or "
                            "contain an underscore"
                        ),
                        line=line,
                        col=col,
                    )
                )
            for arg in texpr.args:
                walk_pattern(
                    arg,
                    in_residuated_context=in_residuated_context,
                    line_hint=line_hint,
                    col_hint=col_hint,
                )
            return

    for stmt in module.statements:
        if isinstance(stmt, ObjectDecl):
            init = stmt.init
            for name in stmt.names:
                if isinstance(init, TypeFreeResiduated):
                    residuated_universes[name] = init
                elif isinstance(init, TypeEnumSet):
                    enum_sets[name] = init
                elif isinstance(init, TypeFreeMonoid):
                    free_monoids[name] = init
                elif isinstance(init, TypeFromExpr):
                    aliased_names[name] = init.expr
        elif isinstance(stmt, CategoryDecl):
            for name in stmt.names:
                category_atoms.add(name)
        elif isinstance(stmt, RuleDecl):
            rule_names.add(stmt.name)
            for prem in stmt.premises:
                walk_pattern(
                    prem,
                    in_residuated_context=True,
                    line_hint=stmt.line,
                    col_hint=stmt.col,
                )
            walk_pattern(
                stmt.conclusion,
                in_residuated_context=True,
                line_hint=stmt.line,
                col_hint=stmt.col,
            )
        elif isinstance(stmt, SchemaDecl):
            schema_names.add(stmt.name)
            in_res = any(
                isinstance(p.type_expr, TypeName)
                and is_residuated_object(p.type_expr.name)
                for p in stmt.parameters
            )
            walk_pattern(
                stmt.domain,
                in_residuated_context=in_res,
                line_hint=stmt.line,
                col_hint=stmt.col,
            )
            walk_pattern(
                stmt.codomain,
                in_residuated_context=in_res,
                line_hint=stmt.line,
                col_hint=stmt.col,
            )
        elif isinstance(stmt, BundleDecl):
            bundle_names.add(stmt.name)
            for member in stmt.rules:
                if (
                    member not in rule_names
                    and member not in schema_names
                    and member not in bundle_names
                    and member not in builtin_schemas
                ):
                    out.append(
                        Violation(
                            code="bundle_unknown_member",
                            message=(
                                f"bundle {stmt.name!r} references "
                                f"unknown member {member!r}; not a "
                                "declared rule / schema / bundle, "
                                "nor a built-in schema"
                            ),
                            line=stmt.line,
                            col=stmt.col,
                        )
                    )

    return out

module_to_source

module_to_source(module: Module) -> str

Serialize a Module AST to canonical .qvr source.

PARAMETER DESCRIPTION
module

The module to print.

TYPE: Module

RETURNS DESCRIPTION
str

The canonical source, ending in a single newline.

RAISES DESCRIPTION
EmitError

If a node in module has no valid .qvr surface form.

Source code in src/quivers/dsl/emit.py
def module_to_source(module: Module) -> str:
    """Serialize a `Module` AST to canonical ``.qvr`` source.

    Parameters
    ----------
    module : Module
        The module to print.

    Returns
    -------
    str
        The canonical source, ending in a single newline.

    Raises
    ------
    EmitError
        If a node in ``module`` has no valid ``.qvr`` surface form.
    """
    declared = [test for test in module.tests if not test.subject]
    entries = [
        (getattr(stmt, "line", 0), 0, index, _emit_statement(stmt, 0))
        for index, stmt in enumerate(module.statements)
    ]
    entries.extend(
        (test.line, 1, index, _emit_test(test)) for index, test in enumerate(declared)
    )
    entries.extend(
        (experiment.line, 1, index, _emit_experiment(experiment))
        for index, experiment in enumerate(module.experiments)
    )
    entries.sort(key=lambda entry: (entry[0] or _LAST, entry[1], entry[2]))
    return "\n\n".join(entry[3] for entry in entries) + "\n"

static_argument_to_source

static_argument_to_source(argument: QiecStaticArgument) -> str

Emit one static argument of an effect or type application.

PARAMETER DESCRIPTION
argument

A type, an effect written as type syntax, or an index literal.

TYPE: QiecStaticArgument

RETURNS DESCRIPTION
str

The argument's source form, as the module emitter writes it.

Source code in src/quivers/dsl/emit.py
def static_argument_to_source(argument: QiecStaticArgument) -> str:
    """Emit one static argument of an effect or type application.

    Parameters
    ----------
    argument : QiecStaticArgument
        A type, an effect written as type syntax, or an index literal.

    Returns
    -------
    str
        The argument's source form, as the module emitter writes it.
    """
    return _emit_qiec_static_argument(argument)

family_parameter_names

family_parameter_names(family: str) -> tuple[str, ...] | None

Return the canonical QVR keyword order for family.

PARAMETER DESCRIPTION
family

The family name as written in source.

TYPE: str

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

The keyword names in canonical order, or None when no keyword schema is declared for family.

Source code in src/quivers/_family_schemas.py
def family_parameter_names(family: str) -> tuple[str, ...] | None:
    """Return the canonical QVR keyword order for ``family``.

    Parameters
    ----------
    family : str
        The family name as written in source.

    Returns
    -------
    tuple[str, ...] | None
        The keyword names in canonical order, or None when no keyword
        schema is declared for ``family``.
    """
    return _FAMILY_PARAMETERS.get(family)

family_parameterizations

family_parameterizations(family: str, canonical: tuple[str, ...]) -> tuple[tuple[str, ...], ...]

Return every complete keyword schema accepted by family.

PARAMETER DESCRIPTION
family

The family name as written in source.

TYPE: str

canonical

The parameter names the family's registry record declares, used when no schema for family is declared here.

TYPE: tuple[str, ...]

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

One tuple of keyword names per accepted parameterization, empty when the family takes no parameters.

Source code in src/quivers/_family_schemas.py
def family_parameterizations(
    family: str, canonical: tuple[str, ...]
) -> tuple[tuple[str, ...], ...]:
    """Return every complete keyword schema accepted by ``family``.

    Parameters
    ----------
    family : str
        The family name as written in source.
    canonical : tuple[str, ...]
        The parameter names the family's registry record declares,
        used when no schema for ``family`` is declared here.

    Returns
    -------
    tuple[tuple[str, ...], ...]
        One tuple of keyword names per accepted parameterization, empty
        when the family takes no parameters.
    """
    alternatives = _ALTERNATIVE_SCHEMAS.get(family)
    if alternatives is not None:
        if family in ("Restrict", "Truncate"):
            # Endpoint policies are independent optional Boolean arguments.
            # Retain the legacy positional schema and accept every explicit
            # subset without inventing a second operator construction path.
            return tuple(
                (*schema, *flags)
                for schema in alternatives
                for flags in (
                    (),
                    ("lower_closed",),
                    ("upper_closed",),
                    ("lower_closed", "upper_closed"),
                )
            )
        return alternatives
    parameters = _FAMILY_PARAMETERS.get(family, canonical)
    return (parameters,) if parameters else ()

free_let_callees

free_let_callees(expr: LetExprNode, *, bound: frozenset[str] = frozenset(), extension: LetExprExtension | None = None) -> tuple[str, ...]

Return the free callee names of calls in first-use order.

A call f(...) whose f is not bound by an enclosing lambda parameter or factor index contributes f.

PARAMETER DESCRIPTION
expr

The expression to scan.

TYPE: LetExprNode

bound

Names already bound around expr, which are not free.

TYPE: frozenset[str] DEFAULT: frozenset()

extension

Child/rebuild adapter for binder-free downstream IR nodes.

TYPE: LetExprExtension or None DEFAULT: None

RETURNS DESCRIPTION
tuple[str, ...]

Each free callee once, in the order of its first occurrence.

RAISES DESCRIPTION
TypeError

If the scan reaches an unsupported let-expression variant.

Source code in src/quivers/dsl/let_expr_traversal.py
def free_let_callees(
    expr: surface.LetExprNode,
    *,
    bound: frozenset[str] = frozenset(),
    extension: LetExprExtension | None = None,
) -> tuple[str, ...]:
    """Return the free callee names of calls in first-use order.

    A call ``f(...)`` whose ``f`` is not bound by an enclosing lambda
    parameter or factor index contributes ``f``.

    Parameters
    ----------
    expr : LetExprNode
        The expression to scan.
    bound : frozenset[str]
        Names already bound around ``expr``, which are not free.
    extension : LetExprExtension or None
        Child/rebuild adapter for binder-free downstream IR nodes.

    Returns
    -------
    tuple[str, ...]
        Each free callee once, in the order of its first occurrence.

    Raises
    ------
    TypeError
        If the scan reaches an unsupported let-expression variant.
    """
    found: list[str] = []

    def visit(node: surface.LetExprNode, local_bound: frozenset[str]) -> None:
        if isinstance(node, surface.LetExprCall):
            if node.func not in local_bound and node.func not in found:
                found.append(node.func)
        elif isinstance(node, surface.LetExprLambda):
            visit(node.body, local_bound | {node.param})
            return
        elif isinstance(node, surface.LetExprFactor):
            inner = local_bound | {binder.var for binder in node.binders}
            for child in let_expr_children(node, extension=extension):
                visit(child, inner)
            return
        elif isinstance(node, LetExprTabulation | LetExprReduction):
            visit(node.body, local_bound | {binder.name for binder in node.binders})
            return
        elif isinstance(node, LetExprCaseValue):
            for branch in node.branches:
                visit(
                    branch.body,
                    local_bound
                    if branch.binder is None
                    else local_bound | {branch.binder},
                )
            return
        for child in let_expr_children(node, extension=extension):
            visit(child, local_bound)

    visit(expr, bound)
    return tuple(found)

free_let_names

free_let_names(expr: LetExprNode, *, bound: frozenset[str] = frozenset(), include_callees: bool = False, extension: LetExprExtension | None = None) -> tuple[str, ...]

Return free value names in first-use order.

Lambda parameters and factor indices bind in their bodies. Call names are declarations by default; callers that model a callee as a host value can include them explicitly.

PARAMETER DESCRIPTION
expr

The expression to scan.

TYPE: LetExprNode

bound

Names already bound around expr, which are not free.

TYPE: frozenset[str] DEFAULT: frozenset()

include_callees

Whether the function name of a call counts as a free name.

TYPE: bool DEFAULT: False

extension

Child/rebuild adapter for binder-free downstream IR nodes.

TYPE: LetExprExtension or None DEFAULT: None

RETURNS DESCRIPTION
tuple[str, ...]

Each free name once, in the order of its first occurrence.

RAISES DESCRIPTION
TypeError

If the scan reaches an unsupported let-expression variant.

Source code in src/quivers/dsl/let_expr_traversal.py
def free_let_names(
    expr: surface.LetExprNode,
    *,
    bound: frozenset[str] = frozenset(),
    include_callees: bool = False,
    extension: LetExprExtension | None = None,
) -> tuple[str, ...]:
    """Return free value names in first-use order.

    Lambda parameters and factor indices bind in their bodies. Call names are
    declarations by default; callers that model a callee as a host value can
    include them explicitly.

    Parameters
    ----------
    expr : LetExprNode
        The expression to scan.
    bound : frozenset[str]
        Names already bound around ``expr``, which are not free.
    include_callees : bool
        Whether the function name of a call counts as a free name.
    extension : LetExprExtension or None
        Child/rebuild adapter for binder-free downstream IR nodes.

    Returns
    -------
    tuple[str, ...]
        Each free name once, in the order of its first occurrence.

    Raises
    ------
    TypeError
        If the scan reaches an unsupported let-expression variant.
    """
    found: list[str] = []

    def visit(node: surface.LetExprNode, local_bound: frozenset[str]) -> None:
        if isinstance(node, surface.LetExprVar):
            if node.name not in local_bound and node.name not in found:
                found.append(node.name)
            return
        if isinstance(node, surface.LetExprCall):
            if (
                include_callees
                and node.func not in local_bound
                and node.func not in found
            ):
                found.append(node.func)
            for argument in node.args:
                visit(argument, local_bound)
            return
        if isinstance(node, surface.LetExprLambda):
            visit(node.body, local_bound | {node.param})
            return
        if isinstance(node, surface.LetExprFactor):
            inner = local_bound | {binder.var for binder in node.binders}
            if node.body is not None:
                visit(node.body, inner)
            for case in node.cases:
                visit(case.value, inner)
            return
        if isinstance(node, LetExprTabulation | LetExprReduction):
            visit(node.body, local_bound | {binder.name for binder in node.binders})
            return
        if isinstance(node, LetExprCaseValue):
            for branch in node.branches:
                visit(
                    branch.body,
                    local_bound
                    if branch.binder is None
                    else local_bound | {branch.binder},
                )
            return
        for child in let_expr_children(node, extension=extension):
            visit(child, local_bound)

    visit(expr, bound)
    return tuple(found)

let_expr_children

let_expr_children(expr: LetExprNode, *, extension: LetExprExtension | None = None) -> tuple[LetExprNode, ...]

Return the immediate expression children of expr in source order.

PARAMETER DESCRIPTION
expr

The expression to take apart.

TYPE: LetExprNode

extension

Child/rebuild adapter for binder-free nodes owned by a downstream IR.

TYPE: LetExprExtension or None DEFAULT: None

RETURNS DESCRIPTION
tuple[LetExprNode, ...]

The direct subexpressions, empty for a leaf.

RAISES DESCRIPTION
TypeError

If expr is a let-expression variant this function does not cover.

Source code in src/quivers/dsl/let_expr_traversal.py
def let_expr_children(
    expr: surface.LetExprNode, *, extension: LetExprExtension | None = None
) -> tuple[surface.LetExprNode, ...]:
    """Return the immediate expression children of ``expr`` in source order.

    Parameters
    ----------
    expr : LetExprNode
        The expression to take apart.
    extension : LetExprExtension or None
        Child/rebuild adapter for binder-free nodes owned by a downstream IR.

    Returns
    -------
    tuple[LetExprNode, ...]
        The direct subexpressions, empty for a leaf.

    Raises
    ------
    TypeError
        If ``expr`` is a let-expression variant this function does not
        cover.
    """
    if isinstance(
        expr,
        surface.LetExprLiteral
        | surface.LetExprBool
        | surface.LetExprUnit
        | surface.LetExprVar
        | surface.LetExprString
        | LetExprHole,
    ):
        return ()
    if isinstance(expr, surface.LetExprBinOp):
        return (expr.left, expr.right)
    if isinstance(expr, surface.LetExprUnaryOp):
        return (expr.operand,)
    if isinstance(expr, surface.LetExprCall):
        return expr.args
    if isinstance(expr, surface.LetExprIndex):
        return (expr.array, *expr.indices)
    if isinstance(expr, surface.LetExprList | surface.LetExprTuple):
        return expr.items
    if isinstance(expr, surface.LetExprLambda):
        return (expr.body,)
    if isinstance(expr, surface.LetExprFactor):
        body = () if expr.body is None else (expr.body,)
        return (*body, *(case.value for case in expr.cases))
    if isinstance(expr, surface.LetExprMethodCall):
        return (expr.receiver, *expr.args)
    if isinstance(expr, surface.QiecConstructorValue):
        return expr.fields
    if isinstance(expr, surface.QiecAnnotatedValue):
        return (expr.value,)
    if isinstance(expr, LetExprRecord):
        base = () if expr.base is None else (expr.base,)
        return (*base, *(field.value for field in expr.fields))
    if isinstance(expr, LetExprInjection):
        return () if expr.payload is None else (expr.payload,)
    if isinstance(expr, LetExprProjection):
        return (expr.record,)
    if isinstance(expr, LetExprCaseValue):
        return tuple(branch.body for branch in expr.branches)
    if isinstance(expr, LetExprTabulation | LetExprReduction):
        return (expr.body,)
    if extension is not None and (children := extension.children(expr)) is not None:
        return children
    raise TypeError(
        f"let_expr_children: unsupported let-expression variant {type(expr).__name__}"
    )

map_let_expr

map_let_expr(expr: LetExprNode, transform: Callable[[LetExprNode], LetExprNode], *, extension: LetExprExtension | None = None, descend: Callable[[LetExprNode], bool] | None = None) -> LetExprNode

Rebuild expr bottom-up, applying transform at every node.

Each node is first rebuilt over its rewritten children and then passed to transform, so transform sees a node whose subexpressions are already rewritten. The rebuild is structural and does not track binders, so a rewrite of variable names belongs in substitute_let_expr.

PARAMETER DESCRIPTION
expr

The root of the rewrite.

TYPE: LetExprNode

transform

The rewrite applied to each rebuilt node.

TYPE: Callable[[LetExprNode], LetExprNode]

extension

Child/rebuild adapter for binder-free downstream IR nodes.

TYPE: LetExprExtension or None DEFAULT: None

descend

Whether to rewrite a node's children before applying transform. A false result leaves child traversal to the transform, for instance when a target indexes subscripts but keeps an existing array opaque.

TYPE: Callable[[LetExprNode], bool] or None DEFAULT: None

RETURNS DESCRIPTION
LetExprNode

The rewritten expression.

RAISES DESCRIPTION
TypeError

If the rewrite reaches an unsupported let-expression variant.

Source code in src/quivers/dsl/let_expr_traversal.py
def map_let_expr(
    expr: surface.LetExprNode,
    transform: Callable[[surface.LetExprNode], surface.LetExprNode],
    *,
    extension: LetExprExtension | None = None,
    descend: Callable[[surface.LetExprNode], bool] | None = None,
) -> surface.LetExprNode:
    """Rebuild ``expr`` bottom-up, applying ``transform`` at every node.

    Each node is first rebuilt over its rewritten children and then
    passed to ``transform``, so ``transform`` sees a node whose
    subexpressions are already rewritten. The rebuild is structural and
    does not track binders, so a rewrite of variable names belongs in
    `substitute_let_expr`.

    Parameters
    ----------
    expr : LetExprNode
        The root of the rewrite.
    transform : Callable[[LetExprNode], LetExprNode]
        The rewrite applied to each rebuilt node.
    extension : LetExprExtension or None
        Child/rebuild adapter for binder-free downstream IR nodes.
    descend : Callable[[LetExprNode], bool] or None
        Whether to rewrite a node's children before applying ``transform``.
        A false result leaves child traversal to the transform, for instance
        when a target indexes subscripts but keeps an existing array opaque.

    Returns
    -------
    LetExprNode
        The rewritten expression.

    Raises
    ------
    TypeError
        If the rewrite reaches an unsupported let-expression variant.
    """

    def rebuild(node: surface.LetExprNode) -> surface.LetExprNode:
        """Rebuild an expression with the rewrite applied below it.

        Parameters
        ----------
        node : surface.LetExprNode
            The expression.

        Returns
        -------
        surface.LetExprNode
            The rebuilt expression.
        """
        if descend is not None and not descend(node):
            return transform(node)
        if isinstance(
            node,
            surface.LetExprLiteral
            | surface.LetExprBool
            | surface.LetExprUnit
            | surface.LetExprVar
            | surface.LetExprString
            | LetExprHole,
        ):
            return transform(node)
        if isinstance(node, surface.LetExprBinOp):
            return transform(
                node.with_(left=rebuild(node.left), right=rebuild(node.right))
            )
        if isinstance(node, surface.LetExprUnaryOp):
            return transform(node.with_(operand=rebuild(node.operand)))
        if isinstance(node, surface.LetExprCall):
            return transform(node.with_(args=tuple(map(rebuild, node.args))))
        if isinstance(node, surface.LetExprIndex):
            return transform(
                node.with_(
                    array=rebuild(node.array),
                    indices=tuple(map(rebuild, node.indices)),
                )
            )
        if isinstance(node, surface.LetExprList | surface.LetExprTuple):
            return transform(node.with_(items=tuple(map(rebuild, node.items))))
        if isinstance(node, surface.LetExprLambda):
            return transform(node.with_(body=rebuild(node.body)))
        if isinstance(node, surface.LetExprFactor):
            return transform(
                node.with_(
                    body=None if node.body is None else rebuild(node.body),
                    cases=tuple(
                        case.with_(value=rebuild(case.value)) for case in node.cases
                    ),
                )
            )
        if isinstance(node, surface.LetExprMethodCall):
            return transform(
                node.with_(
                    receiver=rebuild(node.receiver),
                    args=tuple(map(rebuild, node.args)),
                )
            )
        if isinstance(node, surface.QiecConstructorValue):
            return transform(node.with_(fields=tuple(map(rebuild, node.fields))))
        if isinstance(node, surface.QiecAnnotatedValue):
            return transform(node.with_(value=rebuild(node.value)))
        if isinstance(node, LetExprRecord):
            return transform(
                node.with_(
                    base=None if node.base is None else rebuild(node.base),
                    fields=tuple(
                        field.with_(value=rebuild(field.value)) for field in node.fields
                    ),
                )
            )
        if isinstance(node, LetExprInjection):
            return transform(
                node.with_(
                    payload=None if node.payload is None else rebuild(node.payload)
                )
            )
        if isinstance(node, LetExprProjection):
            return transform(node.with_(record=rebuild(node.record)))
        if isinstance(node, LetExprCaseValue):
            return transform(
                node.with_(
                    branches=tuple(
                        branch.with_(body=rebuild(branch.body))
                        for branch in node.branches
                    )
                )
            )
        if isinstance(node, LetExprTabulation | LetExprReduction):
            return transform(node.with_(body=rebuild(node.body)))
        if extension is not None and (children := extension.children(node)) is not None:
            return transform(extension.rebuild(node, tuple(map(rebuild, children))))
        raise TypeError(
            f"map_let_expr: unsupported let-expression variant {type(node).__name__}"
        )

    return rebuild(expr)

substitute_let_expr

substitute_let_expr(expr: LetExprNode, substitution: Mapping[str, LetExprNode], *, callees: Mapping[str, str] | None = None, index_substitution: Mapping[str, LetExprNode] | None = None, extension: LetExprExtension | None = None) -> LetExprNode

Substitute expressions for free variables in expr without capture.

A lambda parameter or factor binder that would capture a free name of a replacement is renamed to a fresh name first.

PARAMETER DESCRIPTION
expr

The expression to rewrite.

TYPE: LetExprNode

substitution

The replacement for each free variable name.

TYPE: Mapping[str, LetExprNode]

callees

The replacement name for each free callee of a call f(...). A callee bound by an enclosing lambda or factor is not free and keeps its name; a binder that would capture a replacement callee name is renamed like any other capture.

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

index_substitution

Optional overrides in the direct index positions of an indexing node. All other positions use substitution. This preserves the separate value and index origins of a target language without a second walk.

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

extension

Child/rebuild adapter for binder-free downstream IR nodes. Extensions add structural cases; scope and capture avoidance remain in this walk.

TYPE: LetExprExtension or None DEFAULT: None

RETURNS DESCRIPTION
LetExprNode

expr with every free occurrence of a key replaced.

RAISES DESCRIPTION
TypeError

If the rewrite reaches an unsupported let-expression variant.

Source code in src/quivers/dsl/let_expr_traversal.py
def substitute_let_expr(
    expr: surface.LetExprNode,
    substitution: Mapping[str, surface.LetExprNode],
    *,
    callees: Mapping[str, str] | None = None,
    index_substitution: Mapping[str, surface.LetExprNode] | None = None,
    extension: LetExprExtension | None = None,
) -> surface.LetExprNode:
    """Substitute expressions for free variables in ``expr`` without capture.

    A lambda parameter or factor binder that would capture a free name of a
    replacement is renamed to a fresh name first.

    Parameters
    ----------
    expr : LetExprNode
        The expression to rewrite.
    substitution : Mapping[str, LetExprNode]
        The replacement for each free variable name.
    callees : Mapping[str, str] or None
        The replacement name for each free callee of a call
        ``f(...)``. A callee bound by an enclosing lambda or factor is
        not free and keeps its name; a binder that would capture a
        replacement callee name is renamed like any other capture.
    index_substitution : Mapping[str, LetExprNode] or None
        Optional overrides in the direct index positions of an indexing node.
        All other positions use ``substitution``. This preserves the separate
        value and index origins of a target language without a second walk.
    extension : LetExprExtension or None
        Child/rebuild adapter for binder-free downstream IR nodes. Extensions
        add structural cases; scope and capture avoidance remain in this walk.

    Returns
    -------
    LetExprNode
        ``expr`` with every free occurrence of a key replaced.

    Raises
    ------
    TypeError
        If the rewrite reaches an unsupported let-expression variant.
    """
    callee_map: Mapping[str, str] = {} if callees is None else callees
    index_map = (
        substitution
        if index_substitution is None
        else dict(substitution) | dict(index_substitution)
    )

    def free_names(
        node: surface.LetExprNode, *, include_callees: bool = False
    ) -> tuple[str, ...]:
        """Read free names through the same structural extension boundary."""
        return free_let_names(
            node, include_callees=include_callees, extension=extension
        )

    occupied = set(free_names(expr, include_callees=True))
    replacement_maps = (
        (substitution,) if index_map is substitution else (substitution, index_map)
    )
    for replacements in replacement_maps:
        for replacement in replacements.values():
            occupied.update(free_names(replacement, include_callees=True))
    occupied.update(callee_map.values())
    for node in walk_let_expr(expr, extension=extension):
        if isinstance(node, surface.LetExprLambda):
            occupied.add(node.param)
        elif isinstance(node, surface.LetExprFactor):
            occupied.update(binder.var for binder in node.binders)
        elif isinstance(node, LetExprTabulation | LetExprReduction):
            occupied.update(binder.name for binder in node.binders)
        elif isinstance(node, LetExprCaseValue):
            occupied.update(
                branch.binder for branch in node.branches if branch.binder is not None
            )

    def fresh(base: str) -> str:
        suffix = 1
        candidate = f"{base}_{suffix}"
        while candidate in occupied:
            suffix += 1
            candidate = f"{base}_{suffix}"
        occupied.add(candidate)
        return candidate

    def replacement_names(
        active: Mapping[str, surface.LetExprNode],
        active_indices: Mapping[str, surface.LetExprNode],
        active_callees: Mapping[str, str],
        body: surface.LetExprNode,
    ) -> set[str]:
        used_keys = set(free_names(body))
        replacements_by_slot = (
            (active,) if active_indices is active else (active, active_indices)
        )
        names = {
            name
            for replacements in replacements_by_slot
            for key in used_keys & replacements.keys()
            for name in free_names(replacements[key], include_callees=True)
        }
        used_callees = set(free_names(body, include_callees=True))
        names.update(
            active_callees[key] for key in used_callees & active_callees.keys()
        )
        return names

    def replace(
        node: surface.LetExprNode,
        active: Mapping[str, surface.LetExprNode],
        active_callees: Mapping[str, str],
        active_indices: Mapping[str, surface.LetExprNode],
        *,
        in_index_slot: bool = False,
    ) -> surface.LetExprNode:
        if isinstance(node, surface.LetExprVar):
            table = active_indices if in_index_slot else active
            replaced = table.get(node.name)
            if replaced is not None:
                return replaced
            head, _, members = node.name.partition(".")
            if members and head in table:
                return _member_access(table[head], members, node)
            return node

        def rewrite(child: surface.LetExprNode) -> surface.LetExprNode:
            """Recurse into an ordinary value position, retaining active scopes."""
            return replace(child, active, active_callees, active_indices)

        if isinstance(
            node,
            surface.LetExprLiteral
            | surface.LetExprBool
            | surface.LetExprUnit
            | surface.LetExprString
            | LetExprHole,
        ):
            return node
        if isinstance(node, surface.LetExprBinOp):
            return node.with_(
                left=rewrite(node.left),
                right=rewrite(node.right),
            )
        if isinstance(node, surface.LetExprUnaryOp):
            return node.with_(operand=rewrite(node.operand))
        if isinstance(node, surface.LetExprCall):
            return node.with_(
                func=active_callees.get(node.func, node.func),
                args=tuple(map(rewrite, node.args)),
            )
        if isinstance(node, surface.LetExprIndex):
            return node.with_(
                array=rewrite(node.array),
                indices=tuple(
                    replace(
                        item, active, active_callees, active_indices, in_index_slot=True
                    )
                    for item in node.indices
                ),
            )
        if isinstance(node, surface.LetExprList | surface.LetExprTuple):
            return node.with_(items=tuple(map(rewrite, node.items)))
        if isinstance(node, surface.LetExprLambda):
            inner = {key: value for key, value in active.items() if key != node.param}
            inner_indices = (
                inner
                if active_indices is active
                else {
                    key: value
                    for key, value in active_indices.items()
                    if key != node.param
                }
            )
            inner_callees = {
                key: value for key, value in active_callees.items() if key != node.param
            }
            param = node.param
            body = node.body
            if param in replacement_names(inner, inner_indices, inner_callees, body):
                renamed = fresh(param)
                alpha = {
                    param: surface.LetExprVar(
                        name=renamed, line=node.line, col=node.col
                    )
                }
                body = replace(
                    body,
                    alpha,
                    {param: renamed},
                    alpha,
                )
                param = renamed
            return node.with_(
                param=param, body=replace(body, inner, inner_callees, inner_indices)
            )
        if isinstance(node, surface.LetExprFactor):
            bound = {binder.var for binder in node.binders}
            inner = {key: value for key, value in active.items() if key not in bound}
            inner_indices = (
                inner
                if active_indices is active
                else {
                    key: value
                    for key, value in active_indices.items()
                    if key not in bound
                }
            )
            inner_callees = {
                key: value for key, value in active_callees.items() if key not in bound
            }
            bodies = (() if node.body is None else (node.body,)) + tuple(
                case.value for case in node.cases
            )
            captures = {
                name
                for body in bodies
                for name in replacement_names(inner, inner_indices, inner_callees, body)
            }
            binders = list(node.binders)
            body = node.body
            cases = node.cases
            for position, binder in enumerate(binders):
                if binder.var not in captures:
                    continue
                renamed = fresh(binder.var)
                alpha = {
                    binder.var: surface.LetExprVar(
                        name=renamed,
                        line=binder.line,
                        col=binder.col,
                    )
                }
                alpha_callees = {binder.var: renamed}
                body = (
                    None if body is None else replace(body, alpha, alpha_callees, alpha)
                )
                cases = tuple(
                    case.with_(value=replace(case.value, alpha, alpha_callees, alpha))
                    for case in cases
                )
                binders[position] = binder.with_(var=renamed)
            return node.with_(
                binders=tuple(binders),
                body=None
                if body is None
                else replace(body, inner, inner_callees, inner_indices),
                cases=tuple(
                    case.with_(
                        value=replace(case.value, inner, inner_callees, inner_indices)
                    )
                    for case in cases
                ),
            )
        if isinstance(node, LetExprTabulation | LetExprReduction):
            bound = {binder.name for binder in node.binders}
            inner = {key: value for key, value in active.items() if key not in bound}
            inner_indices = (
                inner
                if active_indices is active
                else {
                    key: value
                    for key, value in active_indices.items()
                    if key not in bound
                }
            )
            inner_callees = {
                key: value for key, value in active_callees.items() if key not in bound
            }
            captures = replacement_names(inner, inner_indices, inner_callees, node.body)
            axis_binders = list(node.binders)
            body = node.body
            for position, binder in enumerate(axis_binders):
                if binder.name not in captures:
                    continue
                renamed = fresh(binder.name)
                alpha = {
                    binder.name: surface.LetExprVar(
                        name=renamed, line=binder.line, col=binder.col
                    )
                }
                body = replace(body, alpha, {binder.name: renamed}, alpha)
                axis_binders[position] = binder.with_(name=renamed)
            return node.with_(
                binders=tuple(axis_binders),
                body=replace(body, inner, inner_callees, inner_indices),
            )
        if isinstance(node, surface.LetExprMethodCall):
            return node.with_(
                receiver=rewrite(node.receiver),
                args=tuple(map(rewrite, node.args)),
            )
        if isinstance(node, surface.QiecConstructorValue):
            return node.with_(fields=tuple(map(rewrite, node.fields)))
        if isinstance(node, surface.QiecAnnotatedValue):
            return node.with_(value=rewrite(node.value))
        if isinstance(node, LetExprRecord):
            return node.with_(
                base=None if node.base is None else rewrite(node.base),
                fields=tuple(
                    field.with_(value=rewrite(field.value)) for field in node.fields
                ),
            )
        if isinstance(node, LetExprInjection):
            return node.with_(
                payload=None if node.payload is None else rewrite(node.payload)
            )
        if isinstance(node, LetExprProjection):
            return node.with_(record=rewrite(node.record))
        if isinstance(node, LetExprCaseValue):
            branches = []
            for branch in node.branches:
                if branch.binder is None:
                    branches.append(branch.with_(body=rewrite(branch.body)))
                    continue
                binder = branch.binder
                inner = {key: value for key, value in active.items() if key != binder}
                inner_indices = (
                    inner
                    if active_indices is active
                    else {
                        key: value
                        for key, value in active_indices.items()
                        if key != binder
                    }
                )
                inner_callees = {
                    key: value for key, value in active_callees.items() if key != binder
                }
                body = branch.body
                if binder in replacement_names(
                    inner, inner_indices, inner_callees, body
                ):
                    renamed = fresh(binder)
                    alpha = {
                        binder: surface.LetExprVar(
                            name=renamed, line=branch.line, col=branch.col
                        )
                    }
                    body = replace(body, alpha, {binder: renamed}, alpha)
                    binder = renamed
                branches.append(
                    branch.with_(
                        binder=binder,
                        body=replace(body, inner, inner_callees, inner_indices),
                    )
                )
            return node.with_(branches=tuple(branches))
        if extension is not None and (children := extension.children(node)) is not None:
            return extension.rebuild(node, tuple(map(rewrite, children)))
        raise TypeError(
            f"substitute_let_expr: unsupported let-expression variant "
            f"{type(node).__name__}"
        )

    return replace(expr, substitution, callee_map, index_map)

walk_let_expr

walk_let_expr(expr: LetExprNode, *, extension: LetExprExtension | None = None) -> Iterator[LetExprNode]

Yield expr and all descendants in preorder.

PARAMETER DESCRIPTION
expr

The root of the walk.

TYPE: LetExprNode

extension

Child/rebuild adapter for binder-free downstream IR nodes.

TYPE: LetExprExtension or None DEFAULT: None

YIELDS DESCRIPTION
LetExprNode

expr first, then each subexpression before its own children.

RAISES DESCRIPTION
TypeError

If the walk reaches an unsupported let-expression variant.

Source code in src/quivers/dsl/let_expr_traversal.py
def walk_let_expr(
    expr: surface.LetExprNode, *, extension: LetExprExtension | None = None
) -> Iterator[surface.LetExprNode]:
    """Yield ``expr`` and all descendants in preorder.

    Parameters
    ----------
    expr : LetExprNode
        The root of the walk.
    extension : LetExprExtension or None
        Child/rebuild adapter for binder-free downstream IR nodes.

    Yields
    ------
    LetExprNode
        ``expr`` first, then each subexpression before its own children.

    Raises
    ------
    TypeError
        If the walk reaches an unsupported let-expression variant.
    """
    yield expr
    for child in let_expr_children(expr, extension=extension):
        yield from walk_let_expr(child, extension=extension)

decode_structures

decode_structures(layer: StructureLayer) -> tuple[Statement, ...]

The statements a structure layer encodes, in order.

PARAMETER DESCRIPTION
layer

The declarations and the names their references use.

TYPE: StructureLayer

RETURNS DESCRIPTION
tuple[Statement, ...]

One statement per declaration.

RAISES DESCRIPTION
StructureEncodingError

If a term does not decode.

Source code in src/quivers/dsl/structure_terms.py
def decode_structures(layer: StructureLayer) -> tuple[Statement, ...]:
    """The statements a structure layer encodes, in order.

    Parameters
    ----------
    layer : StructureLayer
        The declarations and the names their references use.

    Returns
    -------
    tuple[Statement, ...]
        One statement per declaration.

    Raises
    ------
    StructureEncodingError
        If a term does not decode.
    """
    decoder = _Decoder(layer.names)
    return tuple(decoder.declaration(item) for item in layer.structures)

module_structure_layer

module_structure_layer(module: QiecModule) -> StructureLayer

A checked module's structure layer, with names read from the module.

PARAMETER DESCRIPTION
module

The checked module.

TYPE: QiecModule

RETURNS DESCRIPTION
StructureLayer

Its structure declarations, and the name of each.

Source code in src/quivers/dsl/structure_terms.py
def module_structure_layer(module: QiecModule) -> StructureLayer:
    """A checked module's structure layer, with names read from the module.

    Parameters
    ----------
    module : QiecModule
        The checked module.

    Returns
    -------
    StructureLayer
        Its structure declarations, and the name of each.
    """
    return StructureLayer(
        structures=module.structures,
        names={item.id: item.name for item in module.structures},
    )

split_statement

split_statement(statement: Statement) -> tuple[Statement, ...]

One statement per name a structure statement declares.

PARAMETER DESCRIPTION
statement

A structure statement.

TYPE: Statement

RETURNS DESCRIPTION
tuple[Statement, ...]

The statement itself, or, for a statement declaring several independent names, one copy per name.

Source code in src/quivers/dsl/structure_terms.py
def split_statement(statement: Statement) -> tuple[Statement, ...]:
    """One statement per name a structure statement declares.

    Parameters
    ----------
    statement : Statement
        A structure statement.

    Returns
    -------
    tuple[Statement, ...]
        The statement itself, or, for a statement declaring several
        independent names, one copy per name.
    """
    if type(statement) in _MULTI_NAME:
        names = _declared_names(statement)
        if len(names) > 1:
            return tuple(statement.with_(names=(name,)) for name in names)
    return (statement,)

structure_layer

structure_layer(module: Module, *, module_name: str) -> StructureLayer

Encode a module's structure statements as structure declarations.

PARAMETER DESCRIPTION
module

The parsed module.

TYPE: Module

module_name

The name every identity derives from.

TYPE: str

RETURNS DESCRIPTION
StructureLayer

One declaration per declared name of every structure statement, in source order, and the names of everything they refer to.

RAISES DESCRIPTION
StructureEncodingError

If a statement holds a value no structure term represents.

Source code in src/quivers/dsl/structure_terms.py
def structure_layer(module: Module, *, module_name: str) -> StructureLayer:
    """Encode a module's structure statements as structure declarations.

    Parameters
    ----------
    module : Module
        The parsed module.
    module_name : str
        The name every identity derives from.

    Returns
    -------
    StructureLayer
        One declaration per declared name of every structure statement, in
        source order, and the names of everything they refer to.

    Raises
    ------
    StructureEncodingError
        If a statement holds a value no structure term represents.
    """
    items: list[tuple[Statement, StructureKind, str]] = []
    exports = 0
    for statement in module.statements:
        kind = _KINDS.get(type(statement))
        if kind is None:
            continue
        for single in split_statement(statement):
            if kind == "export":
                items.append((single, kind, str(exports)))
                exports += 1
            else:
                items.append((single, kind, _declared_names(single)[0]))
    counts: dict[str, int] = {}
    for _, kind, name in items:
        if kind != "export":
            counts[name] = counts.get(name, 0) + 1
    occurrences: dict[tuple[str, str], int] = {}
    identities: list[tuple[Statement, StructureKind, str, int]] = []
    for statement, kind, name in items:
        occurrence = occurrences.get((kind, name), 0)
        occurrences[(kind, name)] = occurrence + 1
        identities.append((statement, kind, name, occurrence))
    environment: dict[str, StructureTarget] = {}
    names: dict[StructureTarget, str] = {}
    for statement, kind, name, occurrence in identities:
        if kind != "export" and counts[name] == 1:
            identity = StructureDecl.identity(module_name, kind, name, occurrence)
            environment[name] = identity
    names.update({target: name for name, target in environment.items()})
    operations = theory_operation_names(module)
    structures: list[StructureDecl] = []
    order = 0
    for statement, kind, name, occurrence in identities:
        encoder = _Encoder(
            environment,
            name,
            data_names=isinstance(statement, ProgramDecl),
            nominal=kind in NOMINAL_KINDS,
            operations=operations,
        )
        term = encoder.statement(statement, _DECLARED_FIELD.get(type(statement)))
        structures.append(
            StructureDecl(
                id=StructureDecl.identity(module_name, kind, name, occurrence),
                kind=kind,
                name=name,
                term=term,
                order=order if kind == "export" else None,
            )
        )
        if kind == "export":
            order += 1
    return StructureLayer(structures=tuple(structures), names=names)

structured_module

structured_module(source: Module, layer: StructureLayer) -> Module

A module whose structure statements are read from a structure layer.

PARAMETER DESCRIPTION
source

The module the layer encodes, for the statements the layer does not record and for their order.

TYPE: Module

layer

Its structure layer.

TYPE: StructureLayer

RETURNS DESCRIPTION
Module

The module with every structure statement replaced by the statements its declarations decode to, in place; a statement that declares several names becomes one statement per name.

RAISES DESCRIPTION
StructureEncodingError

If the layer does not record exactly the module's structure statements in order.

Source code in src/quivers/dsl/structure_terms.py
def structured_module(source: Module, layer: StructureLayer) -> Module:
    """A module whose structure statements are read from a structure layer.

    Parameters
    ----------
    source : Module
        The module the layer encodes, for the statements the layer does not
        record and for their order.
    layer : StructureLayer
        Its structure layer.

    Returns
    -------
    Module
        The module with every structure statement replaced by the
        statements its declarations decode to, in place; a statement that
        declares several names becomes one statement per name.

    Raises
    ------
    StructureEncodingError
        If the layer does not record exactly the module's structure
        statements in order.
    """
    decoded = iter(decode_structures(layer))
    statements: list[Statement] = []
    for statement in source.statements:
        if type(statement) not in _KINDS:
            statements.append(statement)
            continue
        for single in split_statement(statement):
            replacement = next(decoded, None)
            if replacement is None or type(replacement) is not type(single):
                raise StructureEncodingError(
                    "the structure layer does not record the module's structure "
                    f"statement at line {single.line}"
                )
            statements.append(replacement)
    if next(decoded, None) is not None:
        raise StructureEncodingError(
            "the structure layer records more statements than the module has"
        )
    return source.with_(statements=tuple(statements))

parse

parse(source: str | bytes, file_path: str = '<source>') -> Module

Parse .qvr source into a Module.

PARAMETER DESCRIPTION
source

The source text, or its UTF-8 bytes.

TYPE: str | bytes

file_path

The path recorded on diagnostics.

TYPE: str DEFAULT: '<source>'

RETURNS DESCRIPTION
Module

The module's statements in source order.

RAISES DESCRIPTION
ParseError

If the source has a syntax error or a node the AST cannot represent.

Source code in src/quivers/dsl/parser/core.py
def parse(source: str | bytes, file_path: str = "<source>") -> Module:
    """Parse `.qvr` source into a `Module`.

    Parameters
    ----------
    source : str | bytes
        The source text, or its UTF-8 bytes.
    file_path : str
        The path recorded on diagnostics.

    Returns
    -------
    Module
        The module's statements in source order.

    Raises
    ------
    ParseError
        If the source has a syntax error or a node the AST cannot
        represent.
    """
    tree = parse_tree(source, file_path)
    names = file_names(tree, file_path)
    tree.set_view(local_name_view(names))
    return walk_tree(tree, names, file_path)

parse_file

parse_file(path: str | Path) -> Module

Parse a .qvr file at path.

PARAMETER DESCRIPTION
path

The file to read.

TYPE: str | Path

RETURNS DESCRIPTION
Module

The file's statements in source order.

RAISES DESCRIPTION
OSError

If the file cannot be read.

ParseError

If the file does not parse.

Source code in src/quivers/dsl/parser/core.py
def parse_file(path: str | Path) -> Module:
    """Parse a `.qvr` file at `path`.

    Parameters
    ----------
    path : str | Path
        The file to read.

    Returns
    -------
    Module
        The file's statements in source order.

    Raises
    ------
    OSError
        If the file cannot be read.
    ParseError
        If the file does not parse.
    """
    p = Path(path)
    return parse(p.read_bytes(), str(p))

compose_deductions

compose_deductions(module: Module) -> Module

Interpret every composed deduction as one monolithic deduction.

PARAMETER DESCRIPTION
module

A flat module.

TYPE: Module

RETURNS DESCRIPTION
Module

The module itself when no statement is composed; otherwise the module with every deduction composed, and its deduction signatures, lexicon modules, and exports of them removed (they denote no code of their own).

RAISES DESCRIPTION
CompositionError

If a part is unknown, atoms or rules of different origins share a name, a lexicon entry's category uses an atom its signature lacks, a signature rule applies an atom the signature lacks, or a schema or its instantiation is ill-formed.

Source code in src/quivers/dsl/deduction_composition.py
def compose_deductions(module: Module) -> Module:
    """Interpret every composed deduction as one monolithic deduction.

    Parameters
    ----------
    module : Module
        A flat module.

    Returns
    -------
    Module
        The module itself when no statement is composed; otherwise the
        module with every deduction composed, and its deduction signatures,
        lexicon modules, and exports of them removed (they denote no code
        of their own).

    Raises
    ------
    CompositionError
        If a part is unknown, atoms or rules of different origins share a
        name, a lexicon entry's category uses an atom its signature lacks,
        a signature rule applies an atom the signature lacks, or a schema
        or its instantiation is ill-formed.
    """
    if not any(_needs_composition(statement) for statement in module.statements):
        return module
    signatures = {
        statement.name: statement
        for statement in module.statements
        if isinstance(statement, DeductionSignatureDecl)
    }
    lexicons = {
        statement.name: statement
        for statement in module.statements
        if isinstance(statement, LexiconDecl)
    }
    deductions = frozenset(
        statement.name
        for statement in module.statements
        if isinstance(statement, DeductionDecl)
    )
    sorts = {
        statement.name: statement
        for statement in module.statements
        if isinstance(statement, QiecIndexDecl)
    }
    for signature in signatures.values():
        _check_signature(signature, signatures, lexicons, deductions, sorts)
    removed = frozenset((*signatures, *lexicons))
    statements: list[Statement] = []
    for statement in module.statements:
        if isinstance(statement, DeductionSignatureDecl | LexiconDecl):
            continue
        if (
            isinstance(statement, ExportDecl)
            and isinstance(statement.expr, ExprIdent)
            and statement.expr.name in removed
        ):
            continue
        if isinstance(statement, DeductionDecl) and _needs_composition(statement):
            statement = _compose(statement, signatures, lexicons, deductions, sorts)
        statements.append(statement)
    try:
        return reify_cores(module.with_(statements=tuple(statements)))
    except ReificationError as error:
        raise CompositionError(str(error), error.line, error.col) from error

classify_extension

classify_extension(module: Module, deduction: DeductionDecl, signature: str) -> ExtensionVerdict

Classify a composed deduction's extension of one of its signatures.

PARAMETER DESCRIPTION
module

The composed module holding the deduction.

TYPE: Module

deduction

A composed deduction.

TYPE: DeductionDecl

signature

A signature it extends.

TYPE: str

RETURNS DESCRIPTION
ExtensionVerdict

The classification, with the reason or the witness.

Source code in src/quivers/dsl/deduction_conservativity.py
def classify_extension(
    module: Module, deduction: DeductionDecl, signature: str
) -> ExtensionVerdict:
    """Classify a composed deduction's extension of one of its signatures.

    Parameters
    ----------
    module : Module
        The composed module holding the deduction.
    deduction : DeductionDecl
        A composed deduction.
    signature : str
        A signature it extends.

    Returns
    -------
    ExtensionVerdict
        The classification, with the reason or the witness.
    """
    atoms = _core_atoms(deduction, signature)
    origins = _core_origins(deduction, signature)
    rule_origins = {origin.symbol: origin.origin for origin in deduction.rule_origins}
    core_rules = tuple(
        rule for rule in deduction.rules if rule_origins.get(rule.name) in origins
    )
    added = tuple(rule for rule in deduction.rules if rule not in core_rules)
    added_symbols = sorted(
        origin.symbol for origin in deduction.origins if origin.origin not in origins
    )
    base = ExtensionVerdict(
        deduction=deduction.name,
        signature=signature,
        classification="undetermined",
        reason="",
        line=deduction.line,
        col=deduction.col,
    )
    if not added and not added_symbols:
        return base.with_(
            classification="definitional",
            reason=f"{deduction.name} adds no rules and no symbols to {signature}",
        )
    if not added:
        return base.with_(
            classification="conservative",
            reason=(
                f"{deduction.name} adds symbols and no rules to {signature}, so "
                "from any axioms its rules derive what the signature's do"
            ),
        )
    all_atoms = frozenset(deduction.atoms)
    if all(_heads(rule.conclusion) - atoms for rule in added) and all(
        _keeps_variables(rule, all_atoms, position_slots(deduction))
        for rule in deduction.rules
    ):
        return base.with_(
            classification="conservative",
            reason=(
                f"every rule {deduction.name} adds concludes an item applying a "
                f"symbol {signature} lacks, and no rule forgets a premise variable"
            ),
        )
    words = tuple(
        dict.fromkeys(
            word
            for entry in deduction.lexicon
            if isinstance(entry.category, LexiconCategoryFixed)
            and _heads(entry.category.category) | _symbols(entry.category.category)
            <= atoms
            for word in entry.words
        )
    )
    if words:
        core = _system(module, deduction.with_(rules=core_rules, deriving=()))
        extended = _system(module, deduction.with_(deriving=()))
        for sentence in _sentences(words):
            known = {repr(item) for item, _ in core(list(sentence)).chart.items()}
            for item, weight in extended(list(sentence)).chart.items():
                if (
                    float(weight.detach()) != float("-inf")
                    and _in_language(item, atoms)
                    and repr(item) not in known
                ):
                    return base.with_(
                        classification="neither",
                        reason=(
                            f"on {' '.join(sentence)!r} the rules of "
                            f"{deduction.name} derive {item!r}, an item of "
                            f"{signature}'s language its own rules do not"
                        ),
                        sentence=sentence,
                        item=repr(item),
                    )
    return base.with_(
        reason=(
            f"no sufficient condition holds and no sentence of at most "
            f"{MAX_LENGTH} words over {signature}'s lexical entries refutes it"
        ),
    )

classify_extensions

classify_extensions(module: Module) -> tuple[ExtensionVerdict, ...]

Classify every extension of a signature by a deduction of a module.

PARAMETER DESCRIPTION
module

A module; its deductions are composed first.

TYPE: Module

RETURNS DESCRIPTION
tuple[ExtensionVerdict, ...]

One verdict per deduction and signature it extends, in order.

Source code in src/quivers/dsl/deduction_conservativity.py
def classify_extensions(module: Module) -> tuple[ExtensionVerdict, ...]:
    """Classify every extension of a signature by a deduction of a module.

    Parameters
    ----------
    module : Module
        A module; its deductions are composed first.

    Returns
    -------
    tuple[ExtensionVerdict, ...]
        One verdict per deduction and signature it extends, in order.
    """
    composed = compose_deductions(module)
    return tuple(
        classify_extension(composed, statement, core.name)
        for statement in composed.statements
        if isinstance(statement, DeductionDecl)
        for core in statement.cores
    )

extension_notes

extension_notes(module: Module) -> tuple[ExtensionVerdict, ...]

The extensions whose generic results do not carry over from the core.

PARAMETER DESCRIPTION
module

A module.

TYPE: Module

RETURNS DESCRIPTION
tuple[ExtensionVerdict, ...]

Every verdict that is neither definitional nor conservative: for those deductions, a result of generic code typed against Deduction extends S holds for S only.

Source code in src/quivers/dsl/deduction_conservativity.py
def extension_notes(module: Module) -> tuple[ExtensionVerdict, ...]:
    """The extensions whose generic results do not carry over from the core.

    Parameters
    ----------
    module : Module
        A module.

    Returns
    -------
    tuple[ExtensionVerdict, ...]
        Every verdict that is neither definitional nor conservative: for
        those deductions, a result of generic code typed against
        ``Deduction extends S`` holds for ``S`` only.
    """
    return tuple(
        verdict
        for verdict in classify_extensions(module)
        if verdict.classification not in ("definitional", "conservative")
    )

reify_cores

reify_cores(module: Module) -> Module

Generate the core families, inclusions, folds, and laws of a module.

PARAMETER DESCRIPTION
module

A module whose deductions are composed.

TYPE: Module

RETURNS DESCRIPTION
Module

The module itself when no extended signature derives a class; otherwise the module with each such signature's item family and its classes, each extension's inclusion and copaired classes, and the naturality law of each fold.

RAISES DESCRIPTION
ReificationError

If two extensions type a core constructor differently, or a fold names more than one target type.

Source code in src/quivers/dsl/deduction_reification.py
def reify_cores(module: Module) -> Module:
    """Generate the core families, inclusions, folds, and laws of a module.

    Parameters
    ----------
    module : Module
        A module whose deductions are composed.

    Returns
    -------
    Module
        The module itself when no extended signature derives a class;
        otherwise the module with each such signature's item family and
        its classes, each extension's inclusion and copaired classes, and
        the naturality law of each fold.

    Raises
    ------
    ReificationError
        If two extensions type a core constructor differently, or a fold
        names more than one target type.
    """
    if not any(
        isinstance(statement, DeductionDecl)
        and any(core.deriving for core in statement.cores)
        for statement in module.statements
    ):
        return module
    families: dict[str, tuple[QiecFamilyDecl, str]] = {}
    generated: list[Statement] = []
    laws: list[TestDecl] = []
    statements: list[Statement] = []
    for statement in module.statements:
        if not (
            isinstance(statement, DeductionDecl)
            and any(core.deriving for core in statement.cores)
        ):
            statements.append(statement)
            continue
        deduction = statement
        sorts = slot_sorts(deduction)
        origins = _origin_names(deduction)
        cores = {core.name for core in deduction.cores}
        introducing = {
            symbol: (
                f"deduction {source_spelling(origin)}"
                if origin == deduction.name
                else f"deduction signature {source_spelling(origin)}"
                if origin in cores
                else f"lexicon module {source_spelling(origin)}"
            )
            for symbol, origin in origins.items()
        }
        binders = frozenset(deduction.binders)
        # Each constructor's declaring parts; the bound-variable item
        # belongs to every part declaring a binder, and its description
        # names the first.
        declaring: dict[str, tuple[str, ...]] = {
            symbol: (origin,) for symbol, origin in origins.items()
        }
        if deduction.binders:
            binding = tuple(
                dict.fromkeys(origins[binder] for binder in deduction.binders)
            )
            declaring[BOUND_SYMBOL] = binding
            introducing[BOUND_SYMBOL] = introducing[deduction.binders[0]]
        own_constructors = {
            member_name(deduction.name, symbol): (
                f"{source_spelling(member_name(deduction.name, symbol))}, which "
                f"{description} introduces"
            )
            for symbol, description in introducing.items()
        }
        renaming = {
            spelled: member_name(deduction.name, symbol)
            for symbol, parts in declaring.items()
            for part in _paths(
                parts,
                deduction.name,
                tuple(
                    core.name
                    for core in deduction.cores
                    if _reaches(core, symbol, binders)
                ),
            )
            for spelled in _spellings(part, symbol)
        }
        derived = {_class_key(item): item for item in deduction.deriving}
        inherited: dict[str, list[str]] = {}
        prefixes: dict[str, str] = {}
        for core in reversed(deduction.cores):
            if not core.deriving:
                continue
            prefix = _instantiation(core, deduction, sorts)
            prefixes[core.name] = prefix
            family = _family(core, sorts, deduction, prefix)
            known = families.get(prefix)
            if known is not None and _shape(known[0]) != _shape(family):
                # One instantiation fixes the sort of every slot the core's
                # rules leave open; the others are fixed by those rules, so
                # an extension typing one otherwise is no extension of them.
                shown = source_spelling(core.name)
                raise ReificationError(
                    f"deductions {source_spelling(known[1])} and "
                    f"{source_spelling(deduction.name)} both extend {shown} and "
                    f"give its open slots the same sorts, but type a slot {shown}'s "
                    "rules fix differently",
                    deduction.line,
                    deduction.col,
                )
            if known is None:
                families[prefix] = (family, deduction.name)
                generated.append(family)
                below = tuple(
                    part for part in deduction.cores if part.name in core.includes
                )
                core_constructors = {
                    member_name(prefix, symbol): (
                        f"{source_spelling(member_name(core.name, symbol))}, which "
                        "deduction signature "
                        f"{source_spelling(declaring[symbol][0])} introduces"
                    )
                    for symbol in _core_constructors(core, deduction)
                }
                core_renaming = {
                    spelled: member_name(prefix, symbol)
                    for symbol in _core_constructors(core, deduction)
                    for spelled in (
                        *(
                            spelled
                            for part in _paths(
                                declaring[symbol],
                                core.name,
                                tuple(
                                    part.name
                                    for part in below
                                    if _reaches(part, symbol, binders)
                                ),
                            )
                            for spelled in _spellings(part, symbol)
                        ),
                        member_name(prefix, symbol),
                    )
                }
                core_classes: list[DerivingClass] = []
                for position, item in enumerate(core.deriving):
                    if not item.morphisms:
                        core_classes.append(item)
                        continue
                    algebra = _algebra(
                        item,
                        item.morphisms,
                        prefix,
                        core_renaming,
                        core_constructors,
                        _shown_family(core.name),
                        position,
                        deduction,
                    )
                    generated.extend(algebra)
                    head = algebra[0]
                    assert isinstance(head, MetaDecl)
                    core_classes.append(item.with_(morphisms=(head.declaration.name,)))
                # The core's fold concerns the signature, so it is derived,
                # and refused, where the signature derives it.
                generated.append(
                    DerivingDecl(
                        classes=tuple(core_classes),
                        family=member_name(prefix, "Item"),
                        shown=_shown_family(core.name),
                        line=core_classes[0].line if core_classes else deduction.line,
                        col=core_classes[0].col if core_classes else deduction.col,
                    )
                )
            generated.append(_inclusion(core, sorts, deduction, prefix))
            for item in core.deriving:
                inherited.setdefault(_class_key(item), []).extend(item.morphisms)
        classes: list[DerivingClass] = []
        for position, (key, morphisms) in enumerate(inherited.items()):
            own = derived.pop(key, None)
            # An inherited class is derived for the deduction's items, so it
            # is derived, and refused, where the deduction is declared.
            template = (
                own
                if own is not None
                else next(
                    item
                    for core in deduction.cores
                    for item in core.deriving
                    if _class_key(item) == key
                ).with_(line=deduction.line, col=deduction.col)
            )
            if not morphisms and (own is None or not own.morphisms):
                classes.append(template.with_(morphisms=()))
                continue
            parts = (*(own.morphisms if own is not None else ()), *morphisms)
            algebra = _algebra(
                template,
                parts,
                deduction.name,
                renaming,
                own_constructors,
                _shown_family(deduction.name),
                position,
                deduction,
            )
            generated.extend(algebra)
            first = algebra[0]
            assert isinstance(first, MetaDecl)
            classes.append(template.with_(morphisms=(first.declaration.name,)))
            if split_module(deduction.name)[0] is not None:
                # A flat program's tests are its root module's; an imported
                # deduction's laws are tests of the module declaring it.
                continue
            for core in deduction.cores:
                # A core whose every constructor holds an item has no finite
                # item at all, so its law holds vacuously and has no case to
                # test.
                if any(
                    _class_key(item) == key and item.morphisms for item in core.deriving
                ) and any(
                    "item" not in sorts.get(symbol, ())
                    for symbol in _core_constructors(core, deduction)
                ):
                    laws.append(
                        _naturality(template, core, deduction, prefixes[core.name])
                    )
        classes.extend(derived.values())
        statements.append(
            deduction.with_(
                deriving=tuple(classes),
                cores=tuple(core.with_(deriving=()) for core in deduction.cores),
            )
        )
    first = next(
        index
        for index, statement in enumerate(statements)
        if isinstance(statement, DeductionDecl) and statement.cores
    )
    statements[first + 1 : first + 1] = generated
    return module.with_(statements=tuple(statements), tests=(*module.tests, *laws))

slot_sorts

slot_sorts(decl: DeductionDecl) -> dict[str, tuple[str, ...]]

Each symbol of a deduction and the sorts of its slots.

A slot is Int where it holds a chart position (position_slots) or a bound variable's number, and an item otherwise. This is the item family the deduction's elaboration declares.

PARAMETER DESCRIPTION
decl

A composed deduction.

TYPE: DeductionDecl

RETURNS DESCRIPTION
dict[str, tuple[str, ...]]

"int" or "item" per slot, by symbol: atoms in declaration order, then binders, then the bound-variable item.

Source code in src/quivers/dsl/deduction_reification.py
def slot_sorts(decl: DeductionDecl) -> dict[str, tuple[str, ...]]:
    """Each symbol of a deduction and the sorts of its slots.

    A slot is ``Int`` where it holds a chart position (`position_slots`)
    or a bound variable's number, and an item otherwise. This is the item
    family the deduction's elaboration declares.

    Parameters
    ----------
    decl : DeductionDecl
        A composed deduction.

    Returns
    -------
    dict[str, tuple[str, ...]]
        ``"int"`` or ``"item"`` per slot, by symbol: atoms in declaration
        order, then binders, then the bound-variable item.
    """
    flags = position_slots(decl)
    sorts: dict[str, tuple[str, ...]] = {}
    for symbol, arity in _arities(decl).items():
        if symbol == BOUND_SYMBOL and decl.binders:
            sorts[symbol] = ("int",)
            continue
        marks = flags.get(symbol, [])
        sorts[symbol] = tuple(
            "int" if position < len(marks) and marks[position] else "item"
            for position in range(arity)
        )
    return sorts

open_atoms

open_atoms(decl: DeductionDecl) -> frozenset[str]

The atoms a deduction signature's rules never mention.

Nothing in the signature fixes such an atom's arity or the sorts of its slots: each extension fixes them (_instantiation), and generic code over the signature requires what its own uses fix.

PARAMETER DESCRIPTION
decl

A deduction signature's atoms, binders, and rules, as a deduction with no lexicon.

TYPE: DeductionDecl

RETURNS DESCRIPTION
frozenset[str]

The atoms no rule writes, applied or bare.

Source code in src/quivers/dsl/deduction_reification.py
def open_atoms(decl: DeductionDecl) -> frozenset[str]:
    """The atoms a deduction signature's rules never mention.

    Nothing in the signature fixes such an atom's arity or the sorts of
    its slots: each extension fixes them (`_instantiation`), and generic
    code over the signature requires what its own uses fix.

    Parameters
    ----------
    decl : DeductionDecl
        A deduction signature's atoms, binders, and rules, as a deduction
        with no lexicon.

    Returns
    -------
    frozenset[str]
        The atoms no rule writes, applied or bare.
    """
    mentioned: set[str] = set()

    def visit(expr: ObjectExpr) -> None:
        if isinstance(expr, TypeName):
            mentioned.add(expr.name)
        symbol = pattern_symbol(expr)
        if symbol is None:
            return
        mentioned.add(symbol)
        for argument in pattern_arguments(expr):
            visit(argument)

    for rule in decl.rules:
        for pattern in (*rule.premises, rule.conclusion):
            visit(pattern)
    return frozenset(atom for atom in decl.atoms if atom not in mentioned)

slot_classes

slot_classes(decl: DeductionDecl) -> dict[str, tuple[str, ...]]

The slot sorts a deduction signature fixes, and those it leaves open.

A signature has no lexicon of its own, so whether a slot holds a chart position may be decided only by the deduction extending it: span's first two slots are positions in a deduction that reads a sentence through a lexicon and items in one that takes its axioms as input. A slot is

  • "int" when the signature's rules make it a position (a numeral fills it, or a variable shared with such a slot);
  • "item" when they fill it with an atom or an application (which no position slot holds), when it is a binder's bound variable, or when a variable connects it with such a slot;
  • "slot<k>" otherwise: one of the open classes, numbered in order of appearance, of slots the rules connect by shared variables. Every slot of a class has one sort in any deduction extending the signature, since a shared variable fills them all, and that sort is the extension's to fix.
PARAMETER DESCRIPTION
decl

A deduction signature's atoms, binders, and rules (schema instances included), as a deduction with no lexicon.

TYPE: DeductionDecl

RETURNS DESCRIPTION
dict[str, tuple[str, ...]]

The sort or class of each slot, by symbol, ordered as slot_sorts.

Source code in src/quivers/dsl/deduction_reification.py
def slot_classes(decl: DeductionDecl) -> dict[str, tuple[str, ...]]:
    """The slot sorts a deduction signature fixes, and those it leaves open.

    A signature has no lexicon of its own, so whether a slot holds a chart
    position may be decided only by the deduction extending it: ``span``'s
    first two slots are positions in a deduction that reads a sentence
    through a lexicon and items in one that takes its axioms as input. A
    slot is

    * ``"int"`` when the signature's rules make it a position (a numeral
      fills it, or a variable shared with such a slot);
    * ``"item"`` when they fill it with an atom or an application (which
      no position slot holds), when it is a binder's bound variable, or
      when a variable connects it with such a slot;
    * ``"slot<k>"`` otherwise: one of the open classes, numbered in order
      of appearance, of slots the rules connect by shared variables. Every
      slot of a class has one sort in any deduction extending the
      signature, since a shared variable fills them all, and that sort is
      the extension's to fix.

    Parameters
    ----------
    decl : DeductionDecl
        A deduction signature's atoms, binders, and rules (schema
        instances included), as a deduction with no lexicon.

    Returns
    -------
    dict[str, tuple[str, ...]]
        The sort or class of each slot, by symbol, ordered as `slot_sorts`.
    """
    arities = _arities(decl)
    flags = position_slots(decl)
    atoms = frozenset(decl.atoms) | frozenset(decl.binders)
    parent: dict[tuple[str, int], tuple[str, int]] = {}

    def find(slot: tuple[str, int]) -> tuple[str, int]:
        while parent.setdefault(slot, slot) != slot:
            slot = parent[slot]
        return slot

    def union(left: tuple[str, int], right: tuple[str, int]) -> None:
        parent[find(left)] = find(right)

    forced: dict[tuple[str, int], str] = {}
    for symbol, marks in flags.items():
        for position, positional in enumerate(marks):
            if positional:
                forced[(symbol, position)] = "int"
    for binder in decl.binders:
        if arities.get(binder, 0):
            forced.setdefault((binder, 0), "item")
    for rule in decl.rules:
        variables: dict[str, tuple[str, int]] = {}

        def visit(expr: ObjectExpr) -> None:
            symbol = pattern_symbol(expr)
            if symbol is None:
                return
            for position, argument in enumerate(pattern_arguments(expr)):
                slot = (symbol, position)
                find(slot)
                if isinstance(argument, TypeName) and argument.name not in atoms:
                    if argument.name.isdigit():
                        forced[slot] = "int"
                    elif argument.name in variables:
                        union(slot, variables[argument.name])
                    else:
                        variables[argument.name] = slot
                    continue
                forced.setdefault(slot, "item")
                visit(argument)

        for pattern in (*rule.premises, rule.conclusion):
            visit(pattern)
    decided: dict[tuple[str, int], str] = {}
    for slot, sort in forced.items():
        root = find(slot)
        if decided.get(root) != "int":
            decided[root] = sort
    classes: dict[tuple[str, int], str] = {}
    out: dict[str, tuple[str, ...]] = {}
    for symbol, arity in arities.items():
        if symbol == BOUND_SYMBOL and decl.binders:
            out[symbol] = ("int",)
            continue
        sorts: list[str] = []
        for position in range(arity):
            root = find((symbol, position))
            sort = decided.get(root)
            if sort is None:
                sort = classes.setdefault(root, f"slot{len(classes)}")
            sorts.append(sort)
        out[symbol] = tuple(sorts)
    return out

assignments

assignments(rule: SequentRule, instantiation: RuleInstantiation, sorts: Mapping[str, QiecIndexDecl], restrictions: tuple[SchemaConstraint, ...] = ()) -> Iterator[tuple[SchemaValue, ...]]

Every assignment of a schema's parameters an instantiation admits.

PARAMETER DESCRIPTION
rule

The schema.

TYPE: SequentRule

instantiation

The rules entry.

TYPE: RuleInstantiation

sorts

The module's index sorts.

TYPE: Mapping[str, QiecIndexDecl]

restrictions

Further constraints from an extends S[...] restriction; each applies only when the schema has every parameter it mentions.

TYPE: tuple[SchemaConstraint, ...] DEFAULT: ()

YIELDS DESCRIPTION
tuple[SchemaValue, ...]

One value per parameter, in telescope order, in the order of the domains (numerals ascending, index values in declaration order).

RAISES DESCRIPTION
SchemaError

If a constraint names no parameter, a domain is infinite or unknown, or a condition is ill-formed.

Source code in src/quivers/dsl/deduction_schemata.py
def assignments(
    rule: SequentRule,
    instantiation: RuleInstantiation,
    sorts: Mapping[str, QiecIndexDecl],
    restrictions: tuple[SchemaConstraint, ...] = (),
) -> Iterator[tuple[SchemaValue, ...]]:
    """Every assignment of a schema's parameters an instantiation admits.

    Parameters
    ----------
    rule : SequentRule
        The schema.
    instantiation : RuleInstantiation
        The ``rules`` entry.
    sorts : Mapping[str, QiecIndexDecl]
        The module's index sorts.
    restrictions : tuple[SchemaConstraint, ...]
        Further constraints from an ``extends S[...]`` restriction; each
        applies only when the schema has every parameter it mentions.

    Yields
    ------
    tuple[SchemaValue, ...]
        One value per parameter, in telescope order, in the order of the
        domains (numerals ascending, index values in declaration order).

    Raises
    ------
    SchemaError
        If a constraint names no parameter, a domain is infinite or
        unknown, or a condition is ill-formed.
    """
    parameters = schema_parameters(rule)
    names = [binder.name for binder in parameters]
    where = (instantiation.schema, instantiation.line, instantiation.col)
    for constraint in instantiation.constraints:
        mentioned = constraint_names(constraint)
        unknown = sorted(mentioned - set(names) - index_values(sorts))
        if (
            isinstance(constraint, SchemaMembership)
            and constraint.parameter not in names
        ):
            unknown = [constraint.parameter]
        if unknown:
            raise SchemaError(
                f"rules {instantiation.schema}: schema {rule.name!r} has no "
                f"parameter {unknown[0]!r}; its parameters are {', '.join(names)}",
                *constraint_location(constraint, instantiation.line, instantiation.col),
            )
    applicable = tuple(
        constraint
        for constraint in restrictions
        if (constraint_names(constraint) - index_values(sorts)) <= set(names)
    )
    constraints = (*instantiation.constraints, *applicable)
    domains: list[tuple[SchemaValue, ...]] = []
    for binder in parameters:
        domain = _domain(
            rule, binder, sorts, _nat_bound(binder.name, constraints), instantiation
        )
        for constraint in constraints:
            if not (
                isinstance(constraint, SchemaMembership)
                and constraint.parameter == binder.name
            ):
                continue
            if constraint.domain:
                if split_module(constraint.domain)[1] != _sort_name(binder):
                    raise SchemaError(
                        f"rules {instantiation.schema}: parameter {binder.name!r} "
                        f"ranges over {_sort_name(binder)}, not "
                        f"{constraint.domain!r}",
                        constraint.line,
                        constraint.col,
                    )
                continue
            outside = [
                element
                for element in constraint.elements
                if element not in {render_value(value) for value in domain}
            ]
            if outside:
                raise SchemaError(
                    f"rules {instantiation.schema}: {outside[0]!r} is no value of "
                    f"parameter {binder.name!r}, which ranges over "
                    f"{_sort_name(binder)}",
                    constraint.line,
                    constraint.col,
                )
            domain = tuple(
                value for value in domain if render_value(value) in constraint.elements
            )
        domains.append(domain)
    values = index_values(sorts)
    conditions = [
        constraint.condition
        for constraint in constraints
        if isinstance(constraint, SchemaCondition)
    ]
    if instantiation.condition is not None:
        conditions.append(instantiation.condition)
    for assignment in product(*domains):
        environment = dict(zip(names, assignment, strict=True))
        admitted = True
        for condition in conditions:
            verdict = evaluate_condition(condition, environment, values, where)
            if not isinstance(verdict, bool):
                raise SchemaError(
                    f"rules {instantiation.schema}: a constraint is "
                    f"{render_value(verdict)!r}, not a condition",
                    instantiation.line,
                    instantiation.col,
                )
            if not verdict:
                admitted = False
                break
        if admitted:
            yield assignment

canonical_rule

canonical_rule(rule: SequentRule, atoms: frozenset[str]) -> str

A rule's premises and conclusion up to the names of its variables.

PARAMETER DESCRIPTION
rule

A rule.

TYPE: SequentRule

atoms

The deduction's atoms; every other identifier (not a numeral) of a pattern is a variable.

TYPE: frozenset[str]

RETURNS DESCRIPTION
str

The patterns with every variable renamed by first occurrence; two rules with equal renderings derive the same items.

Source code in src/quivers/dsl/deduction_schemata.py
def canonical_rule(rule: SequentRule, atoms: frozenset[str]) -> str:
    """A rule's premises and conclusion up to the names of its variables.

    Parameters
    ----------
    rule : SequentRule
        A rule.
    atoms : frozenset[str]
        The deduction's atoms; every other identifier (not a numeral) of a
        pattern is a variable.

    Returns
    -------
    str
        The patterns with every variable renamed by first occurrence; two
        rules with equal renderings derive the same items.
    """
    renaming: dict[str, str] = {}

    def render(pattern: ObjectExpr) -> str:
        if isinstance(pattern, TypeName):
            if pattern.name not in atoms and not pattern.name.isdigit():
                renaming.setdefault(pattern.name, f"_{len(renaming)}")
                return renaming[pattern.name]
            return pattern.name
        if isinstance(pattern, ObjectEffectApply):
            return (
                pattern.effect
                + "("
                + ", ".join(render(argument) for argument in pattern.args)
                + ")"
            )
        return type(pattern).__name__

    premises = ", ".join(render(premise) for premise in rule.premises)
    return f"{premises} |- {render(rule.conclusion)}"

constraint_location

constraint_location(constraint: SchemaConstraint, line: int, col: int) -> tuple[int, int]

Where a constraint is written, or the given location if unknown.

PARAMETER DESCRIPTION
constraint

The constraint.

TYPE: SchemaConstraint

line

The location to report when the constraint carries none.

TYPE: int

col

The location to report when the constraint carries none.

TYPE: int

RETURNS DESCRIPTION
tuple[int, int]

The line and the column.

Source code in src/quivers/dsl/deduction_schemata.py
def constraint_location(
    constraint: SchemaConstraint, line: int, col: int
) -> tuple[int, int]:
    """Where a constraint is written, or the given location if unknown.

    Parameters
    ----------
    constraint : SchemaConstraint
        The constraint.
    line, col : int
        The location to report when the constraint carries none.

    Returns
    -------
    tuple[int, int]
        The line and the column.
    """
    if isinstance(constraint, SchemaMembership | SchemaCondition) and constraint.line:
        return constraint.line, constraint.col
    return line, col

constraint_names

constraint_names(constraint: SchemaConstraint) -> set[str]

The names a constraint mentions.

PARAMETER DESCRIPTION
constraint

A constraint.

TYPE: SchemaConstraint

RETURNS DESCRIPTION
set[str]

The parameter of a membership; every variable of a condition.

Source code in src/quivers/dsl/deduction_schemata.py
def constraint_names(constraint: SchemaConstraint) -> set[str]:
    """The names a constraint mentions.

    Parameters
    ----------
    constraint : SchemaConstraint
        A constraint.

    Returns
    -------
    set[str]
        The parameter of a membership; every variable of a condition.
    """
    if isinstance(constraint, SchemaMembership):
        return {constraint.parameter}
    if isinstance(constraint, SchemaCondition):
        found: set[str] = set()
        stack: list[LetExprNode] = [constraint.condition]
        while stack:
            node = stack.pop()
            if isinstance(node, LetExprVar):
                found.add(node.name)
            elif isinstance(node, LetExprBinOp):
                stack.extend((node.left, node.right))
            elif isinstance(node, LetExprUnaryOp):
                stack.append(node.operand)
        return found
    return set()

evaluate_condition

evaluate_condition(node: LetExprNode, environment: Mapping[str, SchemaValue], values: frozenset[str], where: tuple[str, int, int]) -> SchemaValue

Evaluate a constraint over one assignment.

PARAMETER DESCRIPTION
node

The expression.

TYPE: LetExprNode

environment

The parameters' values.

TYPE: Mapping[str, SchemaValue]

values

The index values in scope, which a name may spell.

TYPE: frozenset[str]

where

The schema's name and the instantiation's location, for refusals.

TYPE: tuple[str, int, int]

RETURNS DESCRIPTION
SchemaValue

The expression's value.

RAISES DESCRIPTION
SchemaError

If the expression uses a name that is neither a parameter nor an index value, an operator outside comparisons, arithmetic, and the Boolean connectives, or operands of the wrong kind.

Source code in src/quivers/dsl/deduction_schemata.py
def evaluate_condition(
    node: LetExprNode,
    environment: Mapping[str, SchemaValue],
    values: frozenset[str],
    where: tuple[str, int, int],
) -> SchemaValue:
    """Evaluate a constraint over one assignment.

    Parameters
    ----------
    node : LetExprNode
        The expression.
    environment : Mapping[str, SchemaValue]
        The parameters' values.
    values : frozenset[str]
        The index values in scope, which a name may spell.
    where : tuple[str, int, int]
        The schema's name and the instantiation's location, for refusals.

    Returns
    -------
    SchemaValue
        The expression's value.

    Raises
    ------
    SchemaError
        If the expression uses a name that is neither a parameter nor an
        index value, an operator outside comparisons, arithmetic, and the
        Boolean connectives, or operands of the wrong kind.
    """
    schema, line, col = where

    def fail(message: str) -> SchemaError:
        return SchemaError(f"rules {schema}: {message}", line, col)

    if isinstance(node, LetExprLiteral):
        if not node.integral:
            raise fail(f"the numeral {node.value!r} is not a natural number")
        return int(node.value)
    if isinstance(node, LetExprBool):
        return bool(node.value)
    if isinstance(node, LetExprVar):
        if node.name in environment:
            return environment[node.name]
        if node.name in values:
            return node.name
        raise fail(
            f"{node.name!r} is neither a parameter of the schema nor a value of "
            "one of its index sorts"
        )
    if isinstance(node, LetExprUnaryOp):
        operand = evaluate_condition(node.operand, environment, values, where)
        if node.op == "not":
            if not isinstance(operand, bool):
                raise fail("`not` applies to a Boolean")
            return not operand
        if isinstance(operand, bool) or not isinstance(operand, int):
            raise fail("`-` applies to a number")
        return -operand
    if isinstance(node, LetExprBinOp):
        left = evaluate_condition(node.left, environment, values, where)
        right = evaluate_condition(node.right, environment, values, where)
        if node.op in ("&&", "||"):
            if not isinstance(left, bool) or not isinstance(right, bool):
                raise fail(f"`{node.op}` joins Boolean conditions")
            return (left and right) if node.op == "&&" else (left or right)
        if node.op in ("==", "!="):
            if type(left) is not type(right):
                raise fail(
                    f"`{node.op}` compares {render_value(left)!r} with "
                    f"{render_value(right)!r}, values of different sorts"
                )
            return (left == right) if node.op == "==" else (left != right)
        numeric = (
            isinstance(left, int)
            and not isinstance(left, bool)
            and isinstance(right, int)
            and not isinstance(right, bool)
        )
        if not numeric:
            raise fail(f"`{node.op}` applies to numbers")
        assert isinstance(left, int) and isinstance(right, int)
        operations: dict[str, Callable[[int, int], SchemaValue]] = {
            "<": lambda a, b: a < b,
            "<=": lambda a, b: a <= b,
            ">": lambda a, b: a > b,
            ">=": lambda a, b: a >= b,
            "+": lambda a, b: a + b,
            "-": lambda a, b: a - b,
            "*": lambda a, b: a * b,
        }
        operation = operations.get(node.op)
        if operation is None:
            raise fail(f"the operator `{node.op}` has no meaning on parameters")
        return operation(left, right)
    raise fail(f"a {node.kind} expression has no meaning on parameters")

family_parameter_key

family_parameter_key(key: str) -> str

The agenda engine's parameter key of a shared weight family's index.

PARAMETER DESCRIPTION
key

A shared_weight_key (F or F[a,b]).

TYPE: str

RETURNS DESCRIPTION
str

An injective spelling without dots: _ doubled, [ as _L, ] as _R, , as _C.

Source code in src/quivers/dsl/deduction_schemata.py
def family_parameter_key(key: str) -> str:
    """The agenda engine's parameter key of a shared weight family's index.

    Parameters
    ----------
    key : str
        A `shared_weight_key` (``F`` or ``F[a,b]``).

    Returns
    -------
    str
        An injective spelling without dots: ``_`` doubled, ``[`` as
        ``_L``, ``]`` as ``_R``, ``,`` as ``_C``.
    """
    return (
        key.replace("_", "__").replace("[", "_L").replace("]", "_R").replace(",", "_C")
    )

index_values

index_values(sorts: Mapping[str, QiecIndexDecl]) -> frozenset[str]

Every nullary index constructor of the module.

PARAMETER DESCRIPTION
sorts

The module's index sorts.

TYPE: Mapping[str, QiecIndexDecl]

RETURNS DESCRIPTION
frozenset[str]

The names a constraint may use as values.

Source code in src/quivers/dsl/deduction_schemata.py
def index_values(sorts: Mapping[str, QiecIndexDecl]) -> frozenset[str]:
    """Every nullary index constructor of the module.

    Parameters
    ----------
    sorts : Mapping[str, QiecIndexDecl]
        The module's index sorts.

    Returns
    -------
    frozenset[str]
        The names a constraint may use as values.
    """
    return frozenset(
        split_module(item.name)[1]
        for declared in sorts.values()
        for item in declared.constructors
        if not item.arguments
    )

instantiate

instantiate(rule: SequentRule, assignment: tuple[SchemaValue, ...]) -> SequentRule

The instance of a schema at one assignment.

PARAMETER DESCRIPTION
rule

The schema.

TYPE: SequentRule

assignment

One value per parameter, in telescope order.

TYPE: tuple[SchemaValue, ...]

RETURNS DESCRIPTION
SequentRule

The rule, with no parameters, named r_v1_..._vk.

RAISES DESCRIPTION
SchemaError

If a numeral or a Boolean heads an application or stands for a slash, a spine's or a name sequence's length is no numeral, two of them over one sequence variable differ in length, a name sequence is not the first of an application's two arguments, or a sequence variable's names would capture a name the rule already uses.

Source code in src/quivers/dsl/deduction_schemata.py
def instantiate(
    rule: SequentRule,
    assignment: tuple[SchemaValue, ...],
) -> SequentRule:
    """The instance of a schema at one assignment.

    Parameters
    ----------
    rule : SequentRule
        The schema.
    assignment : tuple[SchemaValue, ...]
        One value per parameter, in telescope order.

    Returns
    -------
    SequentRule
        The rule, with no parameters, named ``r_v1_..._vk``.

    Raises
    ------
    SchemaError
        If a numeral or a Boolean heads an application or stands for a
        slash, a spine's or a name sequence's length is no numeral, two of
        them over one sequence variable differ in length, a name sequence
        is not the first of an application's two arguments, or a sequence
        variable's names would capture a name the rule already uses.
    """
    parameters = schema_parameters(rule)
    environment = {
        binder.name: value for binder, value in zip(parameters, assignment, strict=True)
    }
    used: set[str] = set()
    for pattern in (*rule.premises, rule.conclusion):
        used |= _names(pattern)
    lengths: dict[str, str] = {}
    for pattern in (*rule.premises, rule.conclusion):
        for spine in _spines(pattern):
            known = lengths.setdefault(spine.argument, spine.length)
            if known != spine.length:
                raise SchemaError(
                    f"rule schema {rule.name!r}: the sequence variable "
                    f"{spine.argument!r} has length {known!r} in one place and "
                    f"{spine.length!r} in another",
                    spine.line,
                    spine.col,
                )
    for pattern in (*rule.premises, rule.conclusion):
        plain = _plain_names(pattern)
        clash = sorted(plain & set(lengths))
        if clash:
            raise SchemaError(
                f"rule schema {rule.name!r}: {clash[0]!r} is a sequence variable "
                "and cannot also be an ordinary pattern variable",
                rule.line,
                rule.col,
            )

    def value_of(name: str, line: int, col: int) -> SchemaValue:
        if name in environment:
            return environment[name]
        if name.isdigit():
            return int(name)
        return name

    def atom(name: str, role: str, line: int, col: int) -> str:
        value = value_of(name, line, col)
        if isinstance(value, bool) or isinstance(value, int):
            raise SchemaError(
                f"rule schema {rule.name!r}: {name!r} is "
                f"{render_value(value)!r} here, which cannot be {role}; only a "
                "value of an index sort can",
                line,
                col,
            )
        return value

    def names_of(sequence: ObjectSpine | ObjectSequence) -> tuple[TypeName, ...]:
        """The names ``z_1`` through ``z_n`` a sequence variable stands for."""
        length = value_of(sequence.length, sequence.line, sequence.col)
        if isinstance(length, bool) or not isinstance(length, int):
            raise SchemaError(
                f"rule schema {rule.name!r}: the length {sequence.length!r} of "
                f"the sequence variable {sequence.argument!r} is not a natural "
                "number",
                sequence.line,
                sequence.col,
            )
        names: list[TypeName] = []
        for position in range(1, length + 1):
            variable = f"{sequence.argument}_{position}"
            if variable in used:
                raise SchemaError(
                    f"rule schema {rule.name!r}: the sequence variable "
                    f"{sequence.argument!r} stands for the name {variable!r}, "
                    "which the rule already uses; rename one of them",
                    sequence.line,
                    sequence.col,
                )
            names.append(TypeName(name=variable, line=sequence.line, col=sequence.col))
        return tuple(names)

    def substitute(pattern: ObjectExpr) -> ObjectExpr:
        if isinstance(pattern, TypeName):
            if pattern.name in environment:
                return pattern.with_(name=render_value(environment[pattern.name]))
            return pattern
        if isinstance(pattern, ObjectEffectApply):
            head = atom(
                pattern.effect, "the head of an application", pattern.line, pattern.col
            )
            for position, argument in enumerate(pattern.args):
                if isinstance(argument, ObjectSequence) and (
                    position != 0 or len(pattern.args) != 2
                ):
                    raise SchemaError(
                        f"rule schema {rule.name!r}: the name sequence "
                        f"`{argument.argument} ... {argument.length}` must be the "
                        f"first of two arguments, as `{pattern.effect}("
                        f"{argument.argument} ... {argument.length}, B)`, which "
                        f"applies {pattern.effect!r} once per name",
                        argument.line,
                        argument.col,
                    )
            first = pattern.args[0] if pattern.args else None
            if isinstance(first, ObjectSequence):
                result = substitute(pattern.args[1])
                for name in reversed(names_of(first)):
                    result = pattern.with_(effect=head, args=(name, result))
                return result
            return pattern.with_(
                effect=head,
                args=tuple(substitute(argument) for argument in pattern.args),
            )
        if isinstance(pattern, ObjectSpine):
            slash = atom(pattern.slash, "a slash", pattern.line, pattern.col)
            result = substitute(pattern.head)
            for name in names_of(pattern):
                result = ObjectEffectApply(
                    effect=slash,
                    args=(result, name),
                    line=pattern.line,
                    col=pattern.col,
                )
            return result
        if isinstance(pattern, ObjectSequence):
            raise SchemaError(
                f"rule schema {rule.name!r}: the name sequence "
                f"`{pattern.argument} ... {pattern.length}` stands for several "
                "names, so it is written only as the first argument of an "
                "application, as `Lam(z ... n, B)`",
                pattern.line,
                pattern.col,
            )
        return pattern

    options = tuple(
        _substitute_option(entry, environment, rule) for entry in rule.options
    )
    return SequentRule(
        name="_".join((rule.name, *(render_value(value) for value in assignment))),
        premises=tuple(substitute(premise) for premise in rule.premises),
        conclusion=substitute(rule.conclusion),
        options=options,
        line=rule.line,
        col=rule.col,
    )

render_value

render_value(value: SchemaValue) -> str

The spelling of a parameter value in names and patterns.

PARAMETER DESCRIPTION
value

The value.

TYPE: SchemaValue

RETURNS DESCRIPTION
str

true/false, the numeral, or the index value's name.

Source code in src/quivers/dsl/deduction_schemata.py
def render_value(value: SchemaValue) -> str:
    """The spelling of a parameter value in names and patterns.

    Parameters
    ----------
    value : SchemaValue
        The value.

    Returns
    -------
    str
        ``true``/``false``, the numeral, or the index value's name.
    """
    if isinstance(value, bool):
        return "true" if value else "false"
    return str(value)

schema_parameters

schema_parameters(rule: SequentRule) -> tuple[QiecIndexBinder, ...]

A schema's parameters, refusing a binder that is not over an index sort.

PARAMETER DESCRIPTION
rule

A rule; a rule with no telescope has no parameters.

TYPE: SequentRule

RETURNS DESCRIPTION
tuple[QiecIndexBinder, ...]

Its parameters, in telescope order.

RAISES DESCRIPTION
SchemaError

If the telescope binds a type, an effect, or a row: a schema's parameters range over finite static domains.

Source code in src/quivers/dsl/deduction_schemata.py
def schema_parameters(rule: SequentRule) -> tuple[QiecIndexBinder, ...]:
    """A schema's parameters, refusing a binder that is not over an index sort.

    Parameters
    ----------
    rule : SequentRule
        A rule; a rule with no telescope has no parameters.

    Returns
    -------
    tuple[QiecIndexBinder, ...]
        Its parameters, in telescope order.

    Raises
    ------
    SchemaError
        If the telescope binds a type, an effect, or a row: a schema's
        parameters range over finite static domains.
    """
    parameters: list[QiecIndexBinder] = []
    for binder in rule.parameters:
        if not isinstance(binder, QiecIndexBinder):
            raise SchemaError(
                f"rule schema {rule.name!r}: its telescope binds a type, an effect, "
                "or a row; a schema's parameters range over Nat, Bool, or an index "
                "sort",
                rule.line,
                rule.col,
            )
        parameters.append(binder)
    return tuple(parameters)

shared_weight_key

shared_weight_key(rule: SequentRule) -> str | None

The weight-family index a rule's shared pragma reads, if any.

PARAMETER DESCRIPTION
rule

A rule with no parameters.

TYPE: SequentRule

RETURNS DESCRIPTION
str | None

F or F[a,b] (the family and its index, numerals as integers), or None for a rule without the pragma.

RAISES DESCRIPTION
SchemaError

If the pragma's value is not a family name or a family applied to numerals and names, or still names a parameter.

Source code in src/quivers/dsl/deduction_schemata.py
def shared_weight_key(rule: SequentRule) -> str | None:
    """The weight-family index a rule's ``shared`` pragma reads, if any.

    Parameters
    ----------
    rule : SequentRule
        A rule with no parameters.

    Returns
    -------
    str | None
        ``F`` or ``F[a,b]`` (the family and its index, numerals as
        integers), or ``None`` for a rule without the pragma.

    Raises
    ------
    SchemaError
        If the pragma's value is not a family name or a family applied to
        numerals and names, or still names a parameter.
    """
    for entry in rule.options:
        if entry.key != SHARED_OPTION:
            continue
        value = entry.value
        if isinstance(value, OptionName):
            return value.value
        if isinstance(value, OptionCall):
            rendered: list[str] = []
            parameters = {binder.name for binder in schema_parameters(rule)}
            for argument in value.args:
                if (
                    isinstance(argument, OptionName)
                    and argument.value not in parameters
                ):
                    rendered.append(argument.value)
                elif isinstance(argument, OptionNumber) and argument.value == int(
                    argument.value
                ):
                    rendered.append(str(int(argument.value)))
                else:
                    raise SchemaError(
                        f"rule {rule.name!r}: the shared weight family "
                        f"{value.func!r} is indexed by names and numerals",
                        entry.line or rule.line,
                        entry.col or rule.col,
                    )
            return f"{value.func}[{','.join(rendered)}]"
        raise SchemaError(
            f"rule {rule.name!r}: `shared` names a weight family, as `shared = F` "
            "or `shared = F(p, ...)`",
            entry.line or rule.line,
            entry.col or rule.col,
        )
    return None

extract_deduction_schema

extract_deduction_schema(compiler: Compiler) -> Schema

Produce a panproto.Schema for the compiler's deduction-system environment.

Walks the compiler's _deductions registry and emits one panproto vertex per deduction system, one per rule, one per atom, and per-premise / per-conclusion pattern vertices. The returned schema validates against QVR_DEDUCTION_PROTOCOL and is suitable for panproto.diff_schemas and panproto.auto_generate_lens operations over deduction systems.

PARAMETER DESCRIPTION
compiler

A compiler whose _deductions registry is populated.

TYPE: Compiler

RETURNS DESCRIPTION
Schema

A schema in the qvr_deduction protocol.

Source code in src/quivers/dsl/program_theory.py
def extract_deduction_schema(compiler: Compiler) -> panproto.Schema:
    """Produce a `panproto.Schema` for the compiler's
    deduction-system environment.

    Walks the compiler's ``_deductions`` registry and emits one
    panproto vertex per deduction system, one per rule, one per
    atom, and per-premise / per-conclusion pattern vertices. The
    returned schema validates against
    `QVR_DEDUCTION_PROTOCOL` and is suitable for
    `panproto.diff_schemas` and
    `panproto.auto_generate_lens` operations over deduction
    systems.

    Parameters
    ----------
    compiler : Compiler
        A compiler whose ``_deductions`` registry is populated.

    Returns
    -------
    panproto.Schema
        A schema in the ``qvr_deduction`` protocol.
    """
    builder = QVR_DEDUCTION_PROTOCOL.schema()
    deductions = getattr(compiler, "_deductions", {})
    for name, system in deductions.items():
        sys_vid = f"deduction:{name}"
        builder.vertex(sys_vid, "deduction_system")
        builder.constraint(sys_vid, "name", name)
        builder.constraint(sys_vid, "semiring", system.semiring.__class__.__name__)
        for claim in system.semiring.claims():
            builder.constraint(sys_vid, "law", f"{claim.law.name}:{claim.status.value}")
        presentation = system.presentation
        presented = presentation.rules if presentation is not None else ()
        for rule_idx, rule in enumerate(system.rules):
            rule_vid = f"{sys_vid}/rule:{rule.name}"
            builder.vertex(rule_vid, "deduction_rule")
            builder.constraint(rule_vid, "name", rule.name)
            source = presented[rule_idx] if presented else None
            if source is not None:
                builder.constraint(rule_vid, "identity", str(source.id))
                if isinstance(source.weight, ComputedRuleWeight):
                    builder.constraint(
                        rule_vid, "weight-computation", source.weight.operation
                    )
                elif source.weight is not None:
                    builder.constraint(rule_vid, "weight", str(source.weight))
                if source.side_condition is not None:
                    guard = source.side_condition
                    builder.constraint(
                        rule_vid, "guard-computation", str(guard.computation)
                    )
                    for position, argument in enumerate(guard.arguments):
                        builder.constraint(
                            rule_vid, "guard-argument", f"{position}:{argument}"
                        )
            builder.edge(sys_vid, rule_vid, "decl")
            for prem_idx, premise in enumerate(rule.premises):
                p_vid = f"{rule_vid}/premise:{prem_idx}"
                builder.vertex(p_vid, "deduction_premise")
                builder.constraint(p_vid, "pattern", repr(premise))
                if source is not None:
                    builder.constraint(
                        p_vid,
                        "judgment",
                        repr(source.premises[prem_idx].judgment),
                    )
                builder.edge(rule_vid, p_vid, "premise")
            conc_vid = f"{rule_vid}/conclusion"
            builder.vertex(conc_vid, "deduction_conclusion")
            builder.constraint(conc_vid, "pattern", repr(rule.conclusion))
            if source is not None:
                builder.constraint(conc_vid, "judgment", repr(source.conclusion))
            builder.edge(rule_vid, conc_vid, "conclusion")
    return builder.build()

extract_program_schema

extract_program_schema(compiler: Compiler) -> Schema

Produce a panproto.Schema for a compiled program.

Walks the compiler's resolved environment (objects, spaces, morphisms) and its checked kernel module (effects, instances, handlers, computations, and program entry points) and emits a graph of vertices and edges in the QVR_PROGRAM_PROTOCOL protocol. The returned schema validates against that protocol and is suitable for panproto.diff_schemas, panproto.auto_generate_lens, and the rest of panproto's schema-level operations.

PARAMETER DESCRIPTION
compiler

A quivers.dsl.compiler.Compiler after compile_env (or compile) has populated the resolved environments.

TYPE: Compiler

RETURNS DESCRIPTION
Schema

A program-level Schema in the qvr_program protocol.

Source code in src/quivers/dsl/program_theory.py
def extract_program_schema(compiler: Compiler) -> panproto.Schema:
    """Produce a `panproto.Schema` for a compiled program.

    Walks the compiler's resolved environment (objects, spaces, morphisms)
    and its checked kernel module (effects, instances, handlers,
    computations, and program entry points) and emits a graph of
    vertices and edges in the `QVR_PROGRAM_PROTOCOL` protocol. The
    returned schema validates against that protocol and is suitable for
    `panproto.diff_schemas`, `panproto.auto_generate_lens`, and the rest
    of panproto's schema-level operations.

    Parameters
    ----------
    compiler : Compiler
        A [`quivers.dsl.compiler.Compiler`][quivers.dsl.compiler.Compiler] after `compile_env`
        (or `compile`) has populated the resolved environments.

    Returns
    -------
    panproto.Schema
        A program-level Schema in the ``qvr_program`` protocol.
    """
    builder = QVR_PROGRAM_PROTOCOL.schema()
    writer = _SchemaWriter(builder)

    builder.vertex("program", "program")
    if compiler._algebra is not None:
        builder.constraint("program", "algebra", type(compiler._algebra).__name__)

    # object decls
    for name, obj in compiler._objects.items():
        decl_vid = f"object_decl::{name}"
        builder.vertex(decl_vid, "object_decl")
        builder.constraint(decl_vid, "name", name)
        builder.edge("program", decl_vid, "decl")
        target_vid = writer.write_set_object(obj)
        builder.edge(decl_vid, target_vid, "binds_to")

    # space decls
    for name, space in compiler._spaces.items():
        decl_vid = f"space_decl::{name}"
        builder.vertex(decl_vid, "space_decl")
        builder.constraint(decl_vid, "name", name)
        builder.edge("program", decl_vid, "decl")
        target_vid = writer.write_space(space)
        builder.edge(decl_vid, target_vid, "binds_to")

    # morphism decls: the compiler's _morphisms env holds named primitive
    # morphisms; we record them as morphism_decl vertices with domain/codomain.
    # Composite morphisms (let-bindings, output) are derived rather than
    # recorded directly; the structural Diff-able layer is the named decls.
    for name, morphism in compiler._morphisms.items():
        kind = _classify_morphism_kind(morphism)

        decl_vid = f"{kind}::{name}"
        builder.vertex(decl_vid, kind)
        builder.constraint(decl_vid, "name", name)
        builder.edge("program", decl_vid, "decl")

        dom = getattr(morphism, "domain", None)
        cod = getattr(morphism, "codomain", None)
        if dom is not None:
            dom_vid = writer.write_any(dom)
            builder.edge(decl_vid, dom_vid, "domain")
        if cod is not None:
            cod_vid = writer.write_any(cod)
            builder.edge(decl_vid, cod_vid, "codomain")

    # output decl: the compiler's `_output_expr` holds the AST expression
    # whose compilation produces the program's root morphism. We record an
    # output_decl vertex carrying the expression's source-text form (when
    # available) as a name constraint; the structural diff cares about
    # presence/absence of an output, not its detailed shape.
    if compiler._output_expr is not None:
        out_vid = "output_decl"
        builder.vertex(out_vid, "output_decl")
        # ExprIdent / ExprIdentity carry a single name; composite expressions
        # don't have a single canonical name, so mark them as "<composite>".
        expr = compiler._output_expr
        if isinstance(expr, ExprIdent):
            label = expr.name
        elif isinstance(expr, ExprIdentity):
            label = f"identity({expr.object_name})"
        else:
            label = "<composite>"
        builder.constraint(out_vid, "name", label)
        builder.edge("program", out_vid, "output")

    if compiler.qiec_module is not None:
        _KernelWriter(builder, compiler.qiec_module).write()

    return builder.build()

expression_of

expression_of(source: str) -> LetExprNode

Parse one pure expression.

PARAMETER DESCRIPTION
source

The expression's source, on one line.

TYPE: str

RETURNS DESCRIPTION
LetExprNode

Its syntax.

RAISES DESCRIPTION
ValueError

If the source is not one expression.

Source code in src/quivers/dsl/row_inference.py
def expression_of(source: str) -> surface.LetExprNode:
    """Parse one pure expression.

    Parameters
    ----------
    source : str
        The expression's source, on one line.

    Returns
    -------
    surface.LetExprNode
        Its syntax.

    Raises
    ------
    ValueError
        If the source is not one expression.
    """
    module = parse(
        f"define __expression() : Unit !{{}} =\n    let __value = {source}\n    return unit\n"
    )
    for statement in module.statements:
        if isinstance(statement, surface.QiecComputationDecl):
            body = statement.body
            if isinstance(body, surface.QiecPureBinding):
                return body.value
    raise ValueError(f"not one expression: {source!r}")

principal_type

principal_type(expression: LetExprNode, environment: Mapping[str, TypeExpr] | None = None) -> TypeScheme

The principal type of a pure expression.

PARAMETER DESCRIPTION
expression

The expression: records, variants, case functions, lambdas, applications of names in scope, field reads, and arithmetic and Boolean operators.

TYPE: LetExprNode

environment

The types of the names it may read.

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

RETURNS DESCRIPTION
TypeScheme

The type with its unsolved type variables named a, b, ... and its unsolved row variables r, s, ..., in order of first occurrence, and the combination predicates relating them.

RAISES DESCRIPTION
InferenceError

If the expression is ill-typed, joins rows that both have a label, or is of a form inference does not cover.

Source code in src/quivers/dsl/row_inference.py
def principal_type(
    expression: surface.LetExprNode,
    environment: Mapping[str, TypeExpr] | None = None,
) -> TypeScheme:
    """The principal type of a pure expression.

    Parameters
    ----------
    expression : surface.LetExprNode
        The expression: records, variants, ``case`` functions, lambdas,
        applications of names in scope, field reads, and arithmetic and
        Boolean operators.
    environment : Mapping[str, TypeExpr] or None
        The types of the names it may read.

    Returns
    -------
    TypeScheme
        The type with its unsolved type variables named ``a``, ``b``, ...
        and its unsolved row variables ``r``, ``s``, ..., in order of first
        occurrence, and the combination predicates relating them.

    Raises
    ------
    InferenceError
        If the expression is ill-typed, joins rows that both have a label,
        or is of a form inference does not cover.
    """
    inference = _Inference()
    type_ = inference.infer(expression, environment or {})
    predicates = inference.settle(expression)
    type_ = inference.resolve(type_)
    names: dict[StaticVariableId, TypeVariable] = {}
    binders: list[TypeBinder] = []
    letters = {"type": "abcdefgh", "row": "rstuvwxyz"}
    counts = {"type": 0, "row": 0}

    def name(variable: TypeVariable) -> TypeVariable:
        assert variable.identity is not None
        existing = names.get(variable.identity)
        if existing is not None:
            return existing
        family = "row" if variable.kind == DATA_ROW else "type"
        position = counts[family]
        counts[family] += 1
        pool = letters[family]
        label = pool[position] if position < len(pool) else f"{pool[0]}{position}"
        named = TypeVariable(name=label, kind=variable.kind)
        names[variable.identity] = named
        binders.append(TypeBinder(name=label, kind=variable.kind))
        return named

    def generalize(term: TypeExpr) -> TypeExpr:
        if inference.is_meta(term):
            return name(term)  # type: ignore[arg-type]
        if isinstance(term, FunctionType):
            return term.with_(
                parameter=generalize(term.parameter), result=generalize(term.result)
            )
        if isinstance(term, RecordType | VariantType):
            return term.with_(row=generalize_row(term.row))
        if isinstance(term, TypeApplication):
            return term.with_(
                arguments=tuple(
                    generalize(argument)
                    if isinstance(
                        argument,
                        TypeVariable
                        | TypeApplication
                        | FunctionType
                        | RecordType
                        | VariantType,
                    )
                    else argument
                    for argument in term.arguments
                )
            )
        return term

    def generalize_row(row: TypeRow) -> TypeRow:
        return TypeRow(
            fields=tuple(
                RowField(label=field.label, type=generalize(field.type))
                for field in row.fields
            ),
            tail=None if row.tail is None else name(row.tail),
        )

    general = generalize(type_)
    return TypeScheme(
        binders=tuple(binders),
        predicates=tuple(
            RowCombination(
                left=generalize_row(inference.resolve_row(item.left)),
                right=generalize_row(inference.resolve_row(item.right)),
                result=generalize_row(inference.resolve_row(item.result)),
            )
            for item in predicates
        ),
        type=general,
    )

has_qiec_surface

has_qiec_surface(module: Module) -> bool

Return whether a parsed module has anything to elaborate through QIEC.

PARAMETER DESCRIPTION
module

The parsed module to inspect.

TYPE: Module

RETURNS DESCRIPTION
bool

True when at least one statement belongs to the QIEC surface or is a program or deduction the elaboration turns into computations. Callers use this to decide whether the QIEC route runs at all, so a module of other declarations pays nothing for it.

Source code in src/quivers/dsl/qiec_lowering.py
def has_qiec_surface(module: surface.Module) -> bool:
    """Return whether a parsed module has anything to elaborate through QIEC.

    Parameters
    ----------
    module : surface.Module
        The parsed module to inspect.

    Returns
    -------
    bool
        True when at least one statement belongs to the QIEC surface or
        is a program or deduction the elaboration turns into
        computations. Callers
        use this to decide whether the QIEC route runs at all, so a
        module of other declarations pays nothing for it.
    """

    return any(
        isinstance(
            statement,
            (
                *QIEC_STATEMENT_TYPES,
                surface.DeductionDecl,
                surface.SyntaxDecl,
                surface.EncoderDecl,
                surface.DecoderDecl,
                surface.LossDecl,
            ),
        )
        or (
            isinstance(statement, surface.DefineDecl)
            and isinstance(statement.expr, surface.ExprParser)
        )
        or (
            isinstance(statement, surface.ProgramDecl)
            and (
                statement.type_params is None
                or all(
                    isinstance(parameter, surface.ScalarParam | surface.ObjectParam)
                    for parameter in statement.type_params
                )
            )
        )
        for statement in module.statements
    )

lower_qvr_to_qiec

lower_qvr_to_qiec(module: Module, *, module_name: str | None = None, file_path: str = '<source>', source_version: str = QVR_SOURCE_VERSION, target_version: str = QIEC_ABI, elaborate_programs: bool = True, families: FamilyCatalog | None = None) -> QiecModule

Check and lower the QIEC projection of one parsed QVR module.

PARAMETER DESCRIPTION
module

The parsed module, which may mix QIEC and ordinary declarations.

TYPE: Module

module_name

Name the stable identities derive from. None takes it from file_path, so two files of the same stem produce the same identities and a rename is a deliberate act.

TYPE: str or None DEFAULT: None

file_path

Path recorded on diagnostics.

TYPE: str DEFAULT: '<source>'

source_version

The source protocol the module is written against.

TYPE: str DEFAULT: QVR_SOURCE_VERSION

target_version

The kernel ABI to lower to.

TYPE: str DEFAULT: QIEC_ABI

elaborate_programs

Whether program declarations become computations.

TYPE: bool DEFAULT: True

families

Compilation-local custom distribution contracts and native bindings. Only the semantic contracts are retained in the checked module.

TYPE: FamilyCatalog or None DEFAULT: None

RETURNS DESCRIPTION
QiecModule

The checked, lowered module.

RAISES DESCRIPTION
QiecDiagnosticError

If the source is rejected, with a stable code and a position. The code qiec-program-gap names a program construct, such as a parsing chart or a network-parameterized morphism, whose elaboration is not yet defined; a caller may lower the module again without its programs. The code qiec-module-graph names an import, open, hole, or link: a module that uses the module system is lowered through its module graph (quivers.dsl.lower_flat_to_qiec).

KernelError

If the lowered module fails its independent recheck.

Source code in src/quivers/dsl/qiec_lowering.py
def lower_qvr_to_qiec(
    module: surface.Module,
    *,
    module_name: str | None = None,
    file_path: str = "<source>",
    source_version: str = QVR_SOURCE_VERSION,
    target_version: str = QIEC_ABI,
    elaborate_programs: bool = True,
    families: FamilyCatalog | None = None,
) -> QiecModule:
    """Check and lower the QIEC projection of one parsed QVR module.

    Parameters
    ----------
    module : surface.Module
        The parsed module, which may mix QIEC and ordinary declarations.
    module_name : str or None
        Name the stable identities derive from. None takes it from
        `file_path`, so two files of the same stem produce the same
        identities and a rename is a deliberate act.
    file_path : str
        Path recorded on diagnostics.
    source_version : str
        The source protocol the module is written against.
    target_version : str
        The kernel ABI to lower to.
    elaborate_programs : bool
        Whether ``program`` declarations become computations.
    families : FamilyCatalog or None
        Compilation-local custom distribution contracts and native bindings.
        Only the semantic contracts are retained in the checked module.

    Returns
    -------
    QiecModule
        The checked, lowered module.

    Raises
    ------
    QiecDiagnosticError
        If the source is rejected, with a stable code and a position. The
        code ``qiec-program-gap`` names a program construct, such as a
        parsing chart or a network-parameterized morphism, whose
        elaboration is not yet defined; a caller may lower the module
        again without its programs. The code ``qiec-module-graph`` names
        an ``import``, ``open``, ``hole``, or ``link``: a module that
        uses the module system is lowered through its module graph
        (`quivers.dsl.lower_flat_to_qiec`).
    KernelError
        If the lowered module fails its independent recheck.
    """

    return _lower_qvr_with_companions(
        module,
        module_name=module_name,
        file_path=file_path,
        source_version=source_version,
        target_version=target_version,
        elaborate_programs=elaborate_programs,
        families=families,
    ).module

non_qiec_projection

non_qiec_projection(module: Module) -> Module

Project declarations consumed by the categorical/probabilistic compiler.

PARAMETER DESCRIPTION
module

The parsed module to project.

TYPE: Module

RETURNS DESCRIPTION
Module

A module of everything outside the QIEC surface, in source order.

Source code in src/quivers/dsl/qiec_lowering.py
def non_qiec_projection(module: surface.Module) -> surface.Module:
    """Project declarations consumed by the categorical/probabilistic compiler.

    Parameters
    ----------
    module : surface.Module
        The parsed module to project.

    Returns
    -------
    surface.Module
        A module of everything outside the QIEC surface, in source
        order.
    """

    return surface.Module(
        statements=tuple(
            statement
            for statement in module.statements
            if not isinstance(statement, QIEC_STATEMENT_TYPES)
        )
    )

qiec_projection

qiec_projection(module: Module) -> Module

Project QIEC declarations from a module with multiple neighborhoods.

PARAMETER DESCRIPTION
module

The parsed module to project.

TYPE: Module

RETURNS DESCRIPTION
Module

A module of the QIEC statements alone, in source order. The complement is non_qiec_projection, and the two partition the input, so nothing is dropped between the two routes.

Source code in src/quivers/dsl/qiec_lowering.py
def qiec_projection(module: surface.Module) -> surface.Module:
    """Project QIEC declarations from a module with multiple neighborhoods.

    Parameters
    ----------
    module : surface.Module
        The parsed module to project.

    Returns
    -------
    surface.Module
        A module of the QIEC statements alone, in source order. The
        complement is `non_qiec_projection`, and the two partition the
        input, so nothing is dropped between the two routes.
    """

    return surface.Module(
        statements=tuple(
            statement
            for statement in module.statements
            if isinstance(statement, (*QIEC_STATEMENT_TYPES, *PROGRAM_CONTEXT_TYPES))
        )
    )

check_module_language

check_module_language(flat: FlatProgram, *, module_name: str = 'source', file_path: str = '<source>', data: dict | None = None) -> QiecModule | None

Check a flat program's module layer through its checking program.

The checking program keeps the abstract families of functor parameters and sealed modules abstract, includes every functor's body once at its parameters' signatures, and witnesses every signature match with generated code (see FlatProgram.checking). Compiling it checks generic code against signatures alone, client code against sealed signatures alone, and every match. A program without signatures, functors, sealing, or module parameters has no checking program.

PARAMETER DESCRIPTION
flat

The interpreted module graph.

TYPE: FlatProgram

module_name

The compiled module's name.

TYPE: str DEFAULT: 'source'

file_path

The root module's file.

TYPE: str DEFAULT: '<source>'

data

Bindings for from_data("KEY") initializers.

TYPE: dict | None DEFAULT: None

RETURNS DESCRIPTION
QiecModule | None

The checked core of the checking program, which holds every functor body once (typed holes included), or None when the program has no checking program.

RAISES DESCRIPTION
ModuleError

With code signature-mismatch when a witnessed match fails, or module-abstraction when code uses an abstract family of a functor parameter or a sealed module as a concrete type.

CompileError

If the checking program fails to compile for another reason.

QiecDiagnosticError

If QIEC elaboration of the checking program fails for another reason.

Source code in src/quivers/dsl/__init__.py
def check_module_language(
    flat: FlatProgram,
    *,
    module_name: str = "source",
    file_path: str = "<source>",
    data: dict | None = None,
) -> QiecModule | None:
    """Check a flat program's module layer through its checking program.

    The checking program keeps the abstract families of functor parameters
    and sealed modules abstract, includes every functor's body once at its
    parameters' signatures, and witnesses every signature match with
    generated code (see `FlatProgram.checking`). Compiling it checks
    generic code against signatures alone, client code against sealed
    signatures alone, and every match. A program without signatures,
    functors, sealing, or module parameters has no checking program.

    Parameters
    ----------
    flat : FlatProgram
        The interpreted module graph.
    module_name : str
        The compiled module's name.
    file_path : str
        The root module's file.
    data : dict | None
        Bindings for ``from_data("KEY")`` initializers.

    Returns
    -------
    QiecModule | None
        The checked core of the checking program, which holds every
        functor body once (typed holes included), or None when the program
        has no checking program.

    Raises
    ------
    ModuleError
        With code ``signature-mismatch`` when a witnessed match fails, or
        ``module-abstraction`` when code uses an abstract family of a
        functor parameter or a sealed module as a concrete type.
    CompileError
        If the checking program fails to compile for another reason.
    QiecDiagnosticError
        If QIEC elaboration of the checking program fails for another
        reason.
    """
    if flat.checking is None:
        return None
    compiler = Compiler(flat.checking, module_name=module_name, file_path=file_path)
    if data is not None:
        compiler.bind_data(data)
    try:
        # Checking, not compiling for use: generic code with typed holes is
        # checked around them, and the run-time program is what refuses them.
        compiler.check()
    except (CompileError, QiecDiagnosticError) as error:
        if isinstance(error, QiecDiagnosticError):
            line, column = error.line, error.column
            message = f"[{error.code}] {error.message}"
        else:
            line, column = error.line, error.col
            message = str(error).removeprefix(f"line {line}, col {column}: ")
        for site in flat.checks:
            if site.line == line:
                raise ModuleError(
                    ModuleDiagnostic(
                        code="signature-mismatch",
                        message=f"{site.message}: {message}",
                        location=site.location,
                    )
                ) from error
        located = flat.source_map.locate(line, column)
        location = located or SourceLocation(file=file_path, line=line, column=column)
        if mentions_abstract_item(message):
            raise ModuleError(
                ModuleDiagnostic(
                    code="module-abstraction",
                    message="an abstract family of a functor parameter or a sealed "
                    "module is used as a concrete type (abstract items are "
                    f"spelled `module#item`): {message}",
                    location=location,
                )
            ) from error
        if (
            isinstance(error, QiecDiagnosticError)
            or located is None
            or flat.source_map.module_at(line) == flat.root
        ):
            raise
        raise CompileError(
            f"{located.file}: {message}", located.line, located.column
        ) from error
    return compiler.qiec_module

check_signature_laws

check_signature_laws(flat: FlatProgram, module: QiecModule) -> tuple[LawReport, ...]

Check each module that matches a signature with laws as a model of them.

A signature's equations form a theory over its abstract families (sorts) and its computations over them (operations), composed and checked like a theory declaration; each matching module is checked as a finite model of it by quivers.dsl.theories.check_instance when its families are finite, and its obligation is recorded as assumed otherwise.

PARAMETER DESCRIPTION
flat

The interpreted module graph.

TYPE: FlatProgram

module

The compiled run-time program's checked module.

TYPE: QiecModule

RETURNS DESCRIPTION
tuple[LawReport, ...]

One report per obligation, in match order.

RAISES DESCRIPTION
ModuleError

With code signature-mismatch when a law fails (naming the law, the assignment, and both sides' values) or is ill-formed.

Source code in src/quivers/dsl/__init__.py
def check_signature_laws(
    flat: FlatProgram, module: QiecModule
) -> tuple[LawReport, ...]:
    """Check each module that matches a signature with laws as a model of them.

    A signature's ``equations`` form a theory over its abstract families
    (sorts) and its computations over them (operations), composed and
    checked like a ``theory`` declaration; each matching module is checked
    as a finite model of it by `quivers.dsl.theories.check_instance` when
    its families are finite, and its obligation is recorded as assumed
    otherwise.

    Parameters
    ----------
    flat : FlatProgram
        The interpreted module graph.
    module : QiecModule
        The compiled run-time program's checked module.

    Returns
    -------
    tuple[LawReport, ...]
        One report per obligation, in match order.

    Raises
    ------
    ModuleError
        With code ``signature-mismatch`` when a law fails (naming the law,
        the assignment, and both sides' values) or is ill-formed.
    """
    reports: list[LawReport] = []
    theories: dict[str, TheoryValue] = {}
    for obligation in flat.laws:
        location = obligation.location
        try:
            theory = theories.get(obligation.signature)
            if theory is None:
                theory = signature_theory(
                    obligation.signature,
                    obligation.sorts,
                    [
                        (item.name, item.inputs, item.output)
                        for item in obligation.operations
                    ],
                    obligation.equations,
                    {},
                    line=location.line,
                    col=location.column,
                )
                theories[obligation.signature] = theory
            carriers = [
                item.value
                for item in obligation.interpretations
                if item.symbol in obligation.sorts
            ]
            try:
                for carrier in carriers:
                    finite_values(named_type(carrier, module), module)
            except CarrierError as error:
                reports.append(
                    LawReport(
                        signature=obligation.signature,
                        instance=obligation.instance,
                        status="assumed",
                        reason=str(error),
                    )
                )
                continue
            check_instance(
                theory,
                obligation.instance,
                {item.symbol: item.value for item in obligation.interpretations},
                module,
                line=location.line,
                col=location.column,
            )
        except TheoryError as error:
            raise ModuleError(
                ModuleDiagnostic(
                    code="signature-mismatch",
                    message=f"module {obligation.instance} does not satisfy the laws "
                    f"of signature {obligation.signature}: {error.message}",
                    location=location,
                )
            ) from error
        reports.append(
            LawReport(
                signature=obligation.signature,
                instance=obligation.instance,
                status="checked",
            )
        )
    return tuple(reports)

loads

loads(source: str | bytes, *, data: dict | None = None, modules: Mapping[str, str] | None = None, roots: tuple[str | Path, ...] = ()) -> Program

Compile .qvr source text into a trainable Program.

The source is the root module. Its imports are found in modules first and then below roots; the module graph is interpreted into one flat program, which is compiled.

PARAMETER DESCRIPTION
source

The .qvr source as text or UTF-8 bytes.

TYPE: str or bytes

data

Maps string keys to tensors (or tensor-like objects) for any from_data("KEY") initializers in the source. The compiler looks each key up at compile time; an unknown key raises CompileError.

TYPE: dict DEFAULT: None

modules

Module sources by dotted module path, for imports.

TYPE: Mapping[str, str] DEFAULT: None

roots

Directories imported module paths are relative to.

TYPE: tuple[str | Path, ...] DEFAULT: ()

RETURNS DESCRIPTION
Program

The compiled program.

RAISES DESCRIPTION
ParseError

If source or a module it imports does not parse.

ModuleError

If an import names no module, the imports form a cycle, or a name does not resolve.

CompileError

If the flat program does not compile.

Source code in src/quivers/dsl/__init__.py
def loads(
    source: str | bytes,
    *,
    data: dict | None = None,
    modules: Mapping[str, str] | None = None,
    roots: tuple[str | Path, ...] = (),
) -> Program:
    """Compile .qvr source text into a trainable Program.

    The source is the root module. Its imports are found in ``modules``
    first and then below ``roots``; the module graph is interpreted into
    one flat program, which is compiled.

    Parameters
    ----------
    source : str or bytes
        The ``.qvr`` source as text or UTF-8 bytes.
    data : dict, optional
        Maps string keys to tensors (or tensor-like objects) for
        any ``from_data("KEY")`` initializers in the source. The
        compiler looks each key up at compile time; an unknown key
        raises `CompileError`.
    modules : Mapping[str, str], optional
        Module sources by dotted module path, for imports.
    roots : tuple[str | Path, ...]
        Directories imported module paths are relative to.

    Returns
    -------
    Program
        The compiled program.

    Raises
    ------
    ParseError
        If ``source`` or a module it imports does not parse.
    ModuleError
        If an import names no module, the imports form a cycle, or a name
        does not resolve.
    CompileError
        If the flat program does not compile.
    """
    flat = interpret_source(
        source.decode("utf-8") if isinstance(source, bytes) else source,
        loader=MappingLoader(modules) if modules else None,
        roots=roots,
    )
    return _compile_flat(flat, module_name="source", file_path="<source>", data=data)

load

load(path: str | Path, *, data: dict | None = None, roots: tuple[str | Path, ...] | None = None) -> Program

Load and compile a .qvr file into a trainable Program.

The file is the root module. Its imports are found below roots (the file's own directory by default); the module graph is interpreted into one flat program, which is compiled.

PARAMETER DESCRIPTION
path

The .qvr file. Its stem names the compiled module.

TYPE: str | Path

data

Maps string keys to tensors for any from_data("KEY") initializers in the file, as in loads.

TYPE: dict DEFAULT: None

roots

Directories module paths are relative to.

TYPE: tuple[str | Path, ...] DEFAULT: None

RETURNS DESCRIPTION
Program

The compiled program.

RAISES DESCRIPTION
OSError

If the file cannot be read.

ParseError

If the file or a module it imports does not parse.

ModuleError

If an import names no module, the imports form a cycle, or a name does not resolve.

CompileError

If the flat program does not compile.

Source code in src/quivers/dsl/__init__.py
def load(
    path: str | Path,
    *,
    data: dict | None = None,
    roots: tuple[str | Path, ...] | None = None,
) -> Program:
    """Load and compile a .qvr file into a trainable Program.

    The file is the root module. Its imports are found below ``roots``
    (the file's own directory by default); the module graph is
    interpreted into one flat program, which is compiled.

    Parameters
    ----------
    path : str | Path
        The ``.qvr`` file. Its stem names the compiled module.
    data : dict, optional
        Maps string keys to tensors for any ``from_data("KEY")``
        initializers in the file, as in `loads`.
    roots : tuple[str | Path, ...], optional
        Directories module paths are relative to.

    Returns
    -------
    Program
        The compiled program.

    Raises
    ------
    OSError
        If the file cannot be read.
    ParseError
        If the file or a module it imports does not parse.
    ModuleError
        If an import names no module, the imports form a cycle, or a name
        does not resolve.
    CompileError
        If the flat program does not compile.
    """
    flat = interpret_file(path, roots=roots)
    return _compile_flat(
        flat, module_name=Path(path).stem, file_path=str(path), data=data
    )

lower_flat_to_qiec

lower_flat_to_qiec(flat: FlatProgram, *, module_name: str = 'source', file_path: str = '<source>', elaborate_programs: bool = True, families: FamilyCatalog | None = None) -> QiecModule

Check and lower an interpreted module graph to one QIEC module.

This is the QIEC route of loads and load: the module layer is checked through the checking program, the flat program is lowered by lower_qvr_to_qiec, and the laws of every matched signature are checked against the lowered module.

PARAMETER DESCRIPTION
flat

The interpreted module graph (quivers.dsl.modules.interpret_source or quivers.dsl.modules.interpret_file).

TYPE: FlatProgram

module_name

Name the stable identities derive from.

TYPE: str DEFAULT: 'source'

file_path

The root module's file, recorded on diagnostics.

TYPE: str DEFAULT: '<source>'

elaborate_programs

Whether program declarations become computations.

TYPE: bool DEFAULT: True

families

Compilation-local custom distribution contracts and native bindings.

TYPE: FamilyCatalog | None DEFAULT: None

RETURNS DESCRIPTION
QiecModule

The checked, lowered module.

RAISES DESCRIPTION
ModuleError

With code hole-unfilled if the program needs a hole no link fills, or a module-layer code from check_module_language and check_signature_laws.

QiecDiagnosticError

If lowering rejects the flat program; a diagnostic in an imported module names that module's file and line.

CompileError

If the checking program fails to compile.

Source code in src/quivers/dsl/__init__.py
def lower_flat_to_qiec(
    flat: FlatProgram,
    *,
    module_name: str = "source",
    file_path: str = "<source>",
    elaborate_programs: bool = True,
    families: FamilyCatalog | None = None,
) -> QiecModule:
    """Check and lower an interpreted module graph to one QIEC module.

    This is the QIEC route of `loads` and `load`: the module layer is
    checked through the checking program, the flat program is lowered by
    `lower_qvr_to_qiec`, and the laws of every matched signature are
    checked against the lowered module.

    Parameters
    ----------
    flat : FlatProgram
        The interpreted module graph (`quivers.dsl.modules.interpret_source`
        or `quivers.dsl.modules.interpret_file`).
    module_name : str
        Name the stable identities derive from.
    file_path : str
        The root module's file, recorded on diagnostics.
    elaborate_programs : bool
        Whether ``program`` declarations become computations.
    families : FamilyCatalog | None
        Compilation-local custom distribution contracts and native bindings.

    Returns
    -------
    QiecModule
        The checked, lowered module.

    Raises
    ------
    ModuleError
        With code ``hole-unfilled`` if the program needs a hole no link
        fills, or a module-layer code from `check_module_language` and
        `check_signature_laws`.
    QiecDiagnosticError
        If lowering rejects the flat program; a diagnostic in an imported
        module names that module's file and line.
    CompileError
        If the checking program fails to compile.
    """
    check_module_language(flat, module_name=module_name, file_path=file_path)
    _refuse_unfilled(flat, file_path)
    try:
        module = lower_qvr_to_qiec(
            flat.module,
            module_name=module_name,
            file_path=file_path,
            elaborate_programs=elaborate_programs,
            families=families,
        )
    except QiecDiagnosticError as error:
        located = flat.source_map.locate(error.line, error.column)
        if located is None or flat.source_map.module_at(error.line) == flat.root:
            raise
        raise QiecDiagnosticError(
            error.message,
            code=error.code,
            file=located.file,
            line=located.line,
            column=located.column,
            program=error.program,
        ) from error
    check_signature_laws(flat, module)
    return module