Skip to content

Structure declarations

The structure declarations of a checked module: the objects, programs, deductions, relations, losses, encoders, decoders, and every other declaration the compiled runtime reads beside the computations, each as a stable identity and a structure term. What the core records and checks is described in the QIEC developer guide.

structures

Structure declarations: the checked core of a program's non-computational parts.

A QVR module says more than its computations. It declares the objects its programs map between and their sizes, the domain and codomain of every program and deduction, the rules of a deduction with their weights and learnability, the arcs of a weighted relation, losses, encoders, decoders, contractions, categories, schemas, bundles, and signatures. The compiled runtime and every transpile target read these declarations, so they are part of what the module means, and the checked core records them.

Each such declaration is one StructureDecl: a stable identity, the declaration's kind and name, and a structure term holding its whole content. A structure term is a first-order tree:

  • a TermNode is a record of the declaration language, with a head naming the record's form, labelled content fields, and labelled metadata fields (source positions and documentation, which never affect meaning);
  • a TermRef refers to another declaration of the module by its stable identity, so a reference survives a renaming and denotes exactly one declaration;
  • a TermBinder binds a name within the declaration (a rule's schematic variable, a deduction's atom, a program's local), and a TermName is an occurrence of a bound name or a free data name of a program;
  • TermSelf is the declaration's own name;
  • the remaining forms are literal content: text, integers, reals, booleans, the absent value, sequences, and keyed mappings.

The term is total over the declaration language: every field of a declared record is either content or metadata, so a structure term records everything the declaration says. Its interpretation (the compiled objects, morphisms, deduction systems, relations, and losses) is computed from the term, never from a second copy of the source, which is what makes a mismatch between the runtime and the checked core impossible.

The core checks that structure identities are distinct and derive from the module, that every reference names a declaration of the module, and that each term is well formed: field labels are distinct within a record and every name occurrence is a valid identifier spelling.

STRUCTURE_KINDS module-attribute

STRUCTURE_KINDS: tuple[StructureKind, ...] = ('object', 'morphism', 'define', 'export', 'program', 'deduction', 'syntax', 'encoder', 'decoder', 'loss', 'category', 'rule', 'schema', 'bundle', 'contraction', 'composition', 'judgment', 'relation', 'relation-composition', 'relation-transform', 'string-graph', 'theory', 'view', 'model', 'semiring')

Every structure kind, in the order a module lists them.

StructureKind

StructureKind = Literal['object', 'morphism', 'define', 'export', 'program', 'deduction', 'syntax', 'encoder', 'decoder', 'loss', 'category', 'rule', 'schema', 'bundle', 'contraction', 'composition', 'judgment', 'relation', 'relation-composition', 'relation-transform', 'string-graph', 'theory', 'view', 'model', 'semiring']

What a structure declaration declares.

StructureTarget

StructureTarget = StructureId

What a structure term may refer to: another structure declaration of the module. Computations, families, and constructors are named by content, since a module derived from a checked one (a target's selected scope, its first-order translation) may drop computations its structures mention.

StructureTerm

A structure term: the content of one structure declaration.

StructureId didactic-model

StructureId(*, digest: str)

Bases: StableId

Stable identity of a structure declaration.

TermText didactic-model

TermText(*, value: str, tag: Literal['text'] = 'text')

Bases: QiecModel

Literal text content: a string literal, a keyword, or a builtin name.

PARAMETER DESCRIPTION
value

The text.

TYPE: str

TermInt didactic-model

TermInt(*, value: int, tag: Literal['int'] = 'int')

Bases: QiecModel

An integer literal.

PARAMETER DESCRIPTION
value

The integer.

TYPE: int

TermReal didactic-model

TermReal(*, value: float, tag: Literal['real'] = 'real')

Bases: QiecModel

A real literal.

PARAMETER DESCRIPTION
value

The real, finite.

TYPE: float

TermNonFinite didactic-model

TermNonFinite(*, value: Literal['infinity', 'negative-infinity', 'nan'], tag: Literal['non_finite'] = 'non_finite')

Bases: QiecModel

A real literal with no finite value.

A declaration may hold one, as a weight the checker goes on to refuse, and the wire format admits only finite numbers, so the three non-finite reals are a form of their own.

PARAMETER DESCRIPTION
value

Which non-finite real.

TYPE: ('infinity', 'negative-infinity', 'nan') DEFAULT: "infinity"

TermBool didactic-model

TermBool(*, value: bool, tag: Literal['bool'] = 'bool')

Bases: QiecModel

A boolean literal.

PARAMETER DESCRIPTION
value

The boolean.

TYPE: bool

TermNone didactic-model

TermNone(*, tag: Literal['none'] = 'none')

Bases: QiecModel

The absent value of an optional field.

PARAMETER DESCRIPTION
tag

The serialization discriminator.

TYPE: Literal['none'] DEFAULT: 'none'

TermBinder didactic-model

TermBinder(*, spelling: str, tag: Literal['binder'] = 'binder')

Bases: QiecModel

A binding occurrence of a name within the declaration.

PARAMETER DESCRIPTION
spelling

The bound name.

TYPE: str

TermName didactic-model

TermName(*, spelling: str, bound: bool = False, tag: Literal['name'] = 'name')

Bases: QiecModel

An occurrence of a name: one the declaration binds, or a free data name.

PARAMETER DESCRIPTION
spelling

The name.

TYPE: str

bound

Whether the declaration binds the name. A deduction rule's schematic variables are bound by occurring in the rule, with no separate binding occurrence, so a bound name need not have a TermBinder.

TYPE: bool DEFAULT: False

TermRef didactic-model

TermRef(*, target: StructureTarget = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['ref'] = 'ref')

Bases: QiecModel

A reference to another declaration of the module.

PARAMETER DESCRIPTION
target

The referenced declaration's identity.

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

TermSelf didactic-model

TermSelf(*, tag: Literal['self'] = 'self')

Bases: QiecModel

The declaration's own name.

PARAMETER DESCRIPTION
tag

The serialization discriminator.

TYPE: Literal['self'] DEFAULT: 'self'

TermSequence didactic-model

TermSequence(*, items: tuple[StructureTerm, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['sequence'] = 'sequence')

Bases: QiecModel

An ordered sequence of terms.

PARAMETER DESCRIPTION
items

The items, in order.

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

TermEntry didactic-model

TermEntry(*, key: str, value: StructureTerm = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['entry'] = 'entry')

Bases: QiecModel

One entry of a keyed mapping.

PARAMETER DESCRIPTION
key

The entry's key, which is content.

TYPE: str

value

Its value.

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

TermMapping didactic-model

TermMapping(*, entries: tuple[TermEntry, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['mapping'] = 'mapping')

Bases: QiecModel

A mapping from text keys to terms, in key order.

PARAMETER DESCRIPTION
entries

The entries, sorted by key with no key repeated.

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

TermField didactic-model

TermField(*, label: str, value: StructureTerm = field(opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['field'] = 'field')

Bases: QiecModel

One labelled field of a record.

PARAMETER DESCRIPTION
label

The field's label.

TYPE: str

value

Its value.

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

TermNode didactic-model

TermNode(*, head: str, fields: tuple[TermField, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), metadata: tuple[TermField, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), tag: Literal['node'] = 'node')

Bases: QiecModel

A record of the declaration language.

Fields equal to the record form's default are omitted, so one record has one term.

PARAMETER DESCRIPTION
head

The record's form.

TYPE: str

fields

Its content fields, in the form's field order.

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

metadata

Its metadata fields: source positions and documentation. They are kept so the declaration can be reported where it was written, and never enter its content identity.

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

StructureDecl didactic-model

StructureDecl(*, id: StructureId = field(opaque=True, extras=OPAQUE_BY_VALUE), kind: StructureKind, name: str, term: StructureTerm = field(opaque=True, extras=OPAQUE_BY_VALUE), order: int | None = None, tag: Literal['structure_decl'] = 'structure_decl')

Bases: QiecModel

One structure declaration of a module.

PARAMETER DESCRIPTION
id

Its identity, derived from the module, kind, name, and the number of earlier declarations of the same kind and name.

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

kind

What it declares.

TYPE: StructureKind

name

Its name; an export, which declares no name, is named by its position among the module's exports.

TYPE: str

term

Its content.

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

order

Its position among the module's exports, for an export, whose order is meaning (the first export is the module's primary entry); None for every other kind, whose position is not.

TYPE: int or None DEFAULT: None

identity classmethod

identity(module: str, kind: StructureKind, name: str, occurrence: int) -> StructureId

The identity of a structure declaration.

PARAMETER DESCRIPTION
module

The module's name.

TYPE: str

kind

The declaration's kind.

TYPE: StructureKind

name

Its name.

TYPE: str

occurrence

How many declarations of the same kind and name precede it.

TYPE: int

RETURNS DESCRIPTION
StructureId

The derived identity.

Source code in src/quivers/qiec/structures.py
@classmethod
def identity(
    cls, module: str, kind: StructureKind, name: str, occurrence: int
) -> StructureId:
    """The identity of a structure declaration.

    Parameters
    ----------
    module : str
        The module's name.
    kind : StructureKind
        The declaration's kind.
    name : str
        Its name.
    occurrence : int
        How many declarations of the same kind and name precede it.

    Returns
    -------
    StructureId
        The derived identity.
    """
    return StructureId.derive(module, "structure", kind, name, occurrence)

term_children

term_children(term: StructureTerm) -> tuple[StructureTerm, ...]

The terms directly inside a term, metadata included.

PARAMETER DESCRIPTION
term

The term.

TYPE: StructureTerm

RETURNS DESCRIPTION
tuple of StructureTerm

Its immediate subterms, in order.

Source code in src/quivers/qiec/structures.py
def term_children(term: StructureTerm) -> tuple[StructureTerm, ...]:
    """The terms directly inside a term, metadata included.

    Parameters
    ----------
    term : StructureTerm
        The term.

    Returns
    -------
    tuple of StructureTerm
        Its immediate subterms, in order.
    """
    if isinstance(term, TermSequence):
        return term.items
    if isinstance(term, TermMapping):
        return tuple(entry.value for entry in term.entries)
    if isinstance(term, TermNode):
        return tuple(field.value for field in (*term.fields, *term.metadata))
    return ()

walk_term

walk_term(term: StructureTerm) -> Iterator[StructureTerm]

Every term inside a term, the term included, in preorder.

PARAMETER DESCRIPTION
term

The term.

TYPE: StructureTerm

YIELDS DESCRIPTION
StructureTerm

Each subterm.

Source code in src/quivers/qiec/structures.py
def walk_term(term: StructureTerm) -> Iterator[StructureTerm]:
    """Every term inside a term, the term included, in preorder.

    Parameters
    ----------
    term : StructureTerm
        The term.

    Yields
    ------
    StructureTerm
        Each subterm.
    """
    pending: list[StructureTerm] = [term]
    while pending:
        current = pending.pop()
        yield current
        pending.extend(reversed(term_children(current)))

structure_references

structure_references(term: StructureTerm) -> tuple[StructureTarget, ...]

The declarations a structure term refers to, in preorder.

PARAMETER DESCRIPTION
term

The term.

TYPE: StructureTerm

RETURNS DESCRIPTION
tuple of StructureTarget

The target of every reference, repeats included.

Source code in src/quivers/qiec/structures.py
def structure_references(term: StructureTerm) -> tuple[StructureTarget, ...]:
    """The declarations a structure term refers to, in preorder.

    Parameters
    ----------
    term : StructureTerm
        The term.

    Returns
    -------
    tuple of StructureTarget
        The target of every reference, repeats included.
    """
    return tuple(item.target for item in walk_term(term) if isinstance(item, TermRef))

validate_structures

validate_structures(module: str, structures: tuple[StructureDecl, ...]) -> None

Check a module's structure declarations against the module.

PARAMETER DESCRIPTION
module

The module's name.

TYPE: str

structures

Its structure declarations, in source order.

TYPE: tuple of StructureDecl

RAISES DESCRIPTION
ValueError

If an identity repeats or was not derived from the module, a kind and name occur in an order other than the identities record, the exports are not numbered in order from zero, or a reference names a structure declaration the module does not have.

Source code in src/quivers/qiec/structures.py
def validate_structures(module: str, structures: tuple[StructureDecl, ...]) -> None:
    """Check a module's structure declarations against the module.

    Parameters
    ----------
    module : str
        The module's name.
    structures : tuple of StructureDecl
        Its structure declarations, in source order.

    Raises
    ------
    ValueError
        If an identity repeats or was not derived from the module, a kind
        and name occur in an order other than the identities record, the
        exports are not numbered in order from zero, or a reference names a
        structure declaration the module does not have.
    """
    identities = {item.id for item in structures}
    if len(identities) != len(structures):
        raise ValueError("structure declaration identities must be distinct")
    occurrences: dict[tuple[str, str], int] = {}
    exports = 0
    for item in structures:
        key = (item.kind, item.name)
        occurrence = occurrences.get(key, 0)
        occurrences[key] = occurrence + 1
        if item.id != StructureDecl.identity(module, item.kind, item.name, occurrence):
            raise ValueError(
                f"structure {item.kind} {item.name!r} has an identity not derived "
                f"from module {module!r}"
            )
        if item.kind == "export":
            if item.order != exports:
                raise ValueError("exports must be numbered in order from zero")
            exports += 1
    for item in structures:
        for target in structure_references(item.term):
            if target not in identities:
                raise ValueError(
                    f"structure {item.kind} {item.name!r} refers to {target}, "
                    "which the module does not declare"
                )