Skip to content

Structure terms

The exact encoding of a module's structure statements as the structure declarations of its checked core, and the decoding the compiled runtime and the transpile plans read them back through. The roles names take in a term are described in the QIEC developer guide.

structure_terms

Structure terms: the declarations the compiled runtime reads, as checked core.

Every statement of a module that is not a computation of the checked core (objects, morphisms, defines, exports, programs, deductions, syntax declarations, encoders, decoders, losses, categories, rules, schemas, bundles, contractions, compositions, judgments) and every relation, relation composition, relation transform, and string graph becomes one StructureDecl of the checked module. A statement that declares several names at once (object A, B : FinSet 3) declares each independently, so it becomes one structure declaration per name.

The encoding is total and exact: every field of every record a statement holds is either content or metadata, and decoding a structure term gives back the statement it encodes. The compiled runtime and the transpile plans read the decoded statements, so what they build is a function of the checked core and nothing else.

Each string a statement holds plays one of five roles, which decide how it enters the term and so its content identity:

  • metadata: source positions and documentation, kept for diagnostics, never content;
  • declared: the statement's own name, the structure declaration's name, which is metadata, except for the kinds in NOMINAL_KINDS, whose name is content;
  • binder: a name the declaration binds (a deduction's atoms and rule names, a rule's schematic variables, the names its logical forms' binders bind, a program's locals and parameters, an encoder rule's variables), which scopes over the whole declaration;
  • literal: a string literal, a field label, or a keyword argument name, always content;
  • identifier: any other name. An identifier bound in the declaration is a bound name; one naming another declaration of the module is a reference to it by identity; any other identifier (a builtin family, a semiring, an operator) is content. In a program, a free variable is a data name of the program, which, like a program parameter of the checked core, is a free name rather than content.

A deduction rule's schematic variables are not declared by a binder field: every identifier of a rule's premises and conclusion that is not one of the deduction's atoms binds as a schematic variable of the deduction.

STRUCTURE_STATEMENT_TYPES module-attribute

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

The statement classes recorded as structure declarations.

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.

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)

theory_operation_names

theory_operation_names(module: Module) -> frozenset[str]

Every name a theory of a module may give an operation.

A theory's equations may name the operations of the theories it includes, which only elaboration resolves, so a bare name in a theory equation is read as a variable only when no theory of the module declares an operation of that name or renames a symbol to it. The module is the flat program, so imported theories count.

PARAMETER DESCRIPTION
module

The module.

TYPE: Module

RETURNS DESCRIPTION
frozenset[str]

The operation names its theories declare and the targets of every renaming written in it.

Source code in src/quivers/dsl/structure_terms.py
def theory_operation_names(module: Module) -> frozenset[str]:
    """Every name a theory of a module may give an operation.

    A theory's equations may name the operations of the theories it
    includes, which only elaboration resolves, so a bare name in a theory
    equation is read as a variable only when no theory of the module
    declares an operation of that name or renames a symbol to it. The
    module is the flat program, so imported theories count.

    Parameters
    ----------
    module : Module
        The module.

    Returns
    -------
    frozenset[str]
        The operation names its theories declare and the targets of every
        renaming written in it.
    """
    found: set[str] = set()
    pending: list[HeldValue] = list(module.statements)
    while pending:
        value = pending.pop()
        if isinstance(value, TheoryDecl):
            found.update(operation.name for operation in value.operations)
        if isinstance(value, TheoryRenaming):
            found.update(rename.target for rename in value.renames)
        if isinstance(value, dx.Model):
            pending.extend(getattr(value, f) for f in type(value).__field_specs__)
        elif isinstance(value, tuple):
            pending.extend(value)
    return frozenset(found)

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)

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

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