Skip to content

Compiler

Compiler compiles a parsed QVR module to an executable Program (compilation pipeline). It resolves names, checks that domains and codomains agree, builds the runtime morphisms (correspondences), and attaches the module's checked Quivers Indexed Effect Core (QIEC) form. The resulting program can be run or passed to an inference procedure, and CompileError reports a rejected module.

For interactive inspection, compile_env(defer_unresolved=True) compiles declarations whose dependencies have known finite sizes and retains the remaining declarations with their authored types. deferred_statements lists this dependency closure in source order. The compiler preserves the complete checked QIEC module; unresolved sizes do not hide errors in independent declarations. Ordinary compilation still requires evidence for each inferred size.

compiler

quivers.dsl.compiler: AST -> Program compiler.

Re-exports the public surface from the package's submodules.

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}")