Skip to content

QIEC lowering

lower_qvr_to_qiec translates a parsed module into the Quivers Indexed Effect Core (QIEC), the typed core language that checking, execution, and transpilation share. It rewrites source syntax into explicit operations, checks the result, and raises a diagnostic naming any construct it cannot represent.

qiec_lowering

Exact QVR to QIEC lowering.

Quivers owns this adapter. Didactic orders and negotiates its stages and checks the first-order indexed-family projection. Name resolution, stable identity, effect elaboration, runtime checking, and the QIEC ABI remain source-language responsibilities.

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.

RESUME module-attribute

RESUME = 'resume'

The name a traversal's lambda invokes a clause's continuation by.

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: ()

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

DeclaredFamilies didactic-model

DeclaredFamilies(*, families: tuple[FamilyDecl, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), constructors: tuple[ConstructorDecl, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), deduction_items: Mapping[str, str] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE), computations: tuple[str, ...] = ())

Bases: QiecModel

The families a module declares and generates, before any body is read.

PARAMETER DESCRIPTION
families

Every family: declared in source, or generated by a declaration.

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

constructors

Every constructor of those families.

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

deduction_items

Each deduction's name mapped to the name of the item family it generates.

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

computations

The computations the declarations generate, such as a signature sort's Sig.S.show, by name.

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

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
    )

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

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

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

declared_families

declared_families(module: Module, *, module_name: str | None = None, file_path: str = '<source>') -> DeclaredFamilies

Declare a module's families without checking any computation body.

PARAMETER DESCRIPTION
module

The parsed module.

TYPE: Module

module_name

The name identities derive from; None takes it from file_path.

TYPE: str or None DEFAULT: None

file_path

The path recorded on diagnostics.

TYPE: str DEFAULT: '<source>'

RETURNS DESCRIPTION
DeclaredFamilies

The declared and generated families and their constructors.

RAISES DESCRIPTION
QiecDiagnosticError

If a declaration is rejected, or with code qiec-module-graph if the module uses the module system uninterpreted.

Source code in src/quivers/dsl/qiec_lowering.py
def declared_families(
    module: surface.Module,
    *,
    module_name: str | None = None,
    file_path: str = "<source>",
) -> DeclaredFamilies:
    """Declare a module's families without checking any computation body.

    Parameters
    ----------
    module : surface.Module
        The parsed module.
    module_name : str or None
        The name identities derive from; None takes it from `file_path`.
    file_path : str
        The path recorded on diagnostics.

    Returns
    -------
    DeclaredFamilies
        The declared and generated families and their constructors.

    Raises
    ------
    QiecDiagnosticError
        If a declaration is rejected, or with code ``qiec-module-graph`` if
        the module uses the module system uninterpreted.
    """
    _refuse_module_statements(module, file_path)
    source = QvrQiecSource(
        syntax=qiec_projection(module),
        module_name=module_name if module_name is not None else _module_name(file_path),
        file_path=file_path,
        elaborate_programs=False,
    )
    elaborator = _Elaborator(source)
    elaborator.declare_data_layer()
    return DeclaredFamilies(
        families=tuple(elaborator.families.values()),
        constructors=tuple(elaborator.constructors.values()),
        deduction_items=dict(elaborator.deduction_item_families()),
        computations=tuple(sorted(elaborator.computation_signatures)),
    )