Skip to content

Meta phase

The meta phase of a module: check-time evaluation of meta declarations, static assertions, splices of generated declarations, and deriving, together with the reflection between checked families, quoted syntax, and source syntax. The meta-phase reference describes the surface, and the semantics states the rules.

meta

The meta phase of QVR: check-time evaluation, generated declarations, deriving.

A module's meta phase holds its meta declarations, static assert statements, splices ($gen(args)), and deriving requests. It is checked and evaluated by the reference machine while the module is checked; the declarations it generates are spliced into the run-time module and checked like hand-written ones.

  • expand_meta runs the meta phase of a parsed module.
  • persisting_meta_library keeps the checked library in an artifact store, so a later process reuses it.
  • quivers.dsl.meta.reflect relates checked families, quoted syntax, and source syntax.
  • quivers.dsl.meta.universe builds and reads meta-phase values.
  • quivers.dsl.meta.library loads the meta-phase prelude and the built-in deriving handlers, both written in QVR.
  • quivers.dsl.meta.provenance digests a generated declaration together with its meta inputs.

LIBRARY_DIRECTORY module-attribute

LIBRARY_DIRECTORY = Path(__file__).resolve().parent

The directory the library's source files live in.

LIBRARY_FILES module-attribute

LIBRARY_FILES: tuple[str, ...] = ('prelude.qvr', 'deriving.qvr', 'ornaments.qvr')

The library sources, in the order their declarations enter the meta phase.

LIBRARY_NAMESPACE module-attribute

LIBRARY_NAMESPACE = 'meta-library'

The store namespace of checked meta-phase libraries.

META_FUEL module-attribute

META_FUEL = 20000000

The reference-machine steps one meta evaluation may take.

SCALAR_TYPES module-attribute

SCALAR_TYPES: Mapping[str, TypeExpr] = {'Bool': BOOL, 'Int': INT, 'Real': REAL, 'String': STRING}

The primitive types meta-phase fields are built from, by name.

SyntaxValue

SyntaxValue = Model | tuple[SyntaxValue, ...] | str | int | float | bool | None

A syntax node, a tuple of them, or a leaf of a syntax tree.

MetaField

MetaField = RuntimeConstructor | str | int | float | bool | Tensor

One field of a runtime value of a meta-phase family.

MetaLibrary didactic-model

MetaLibrary(*, statements: tuple[Statement, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), names: frozenset[str] = field(opaque=True, extras=OPAQUE_BY_VALUE), computations: frozenset[str] = field(opaque=True, extras=OPAQUE_BY_VALUE), digest: str)

Bases: ValueModel

The parsed meta-phase library.

PARAMETER DESCRIPTION
statements

Every library declaration, in file order.

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

names

Every name the library declares in any namespace: families, constructors, computations, effect instances, and handlers.

TYPE: frozenset[str] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

computations

The names of the library's computations.

TYPE: frozenset[str] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

digest

The content-hash-domain digest, of kind meta-library, of the library's source files, which enters the provenance of every declaration the meta phase generates.

TYPE: str

GeneratedDeclaration didactic-model

GeneratedDeclaration(*, name: str, statement: Statement | TestDecl = field(opaque=True, extras=OPAQUE_BY_VALUE), provenance: MetaProvenance)

Bases: ValueModel

One declaration the meta phase generated and spliced.

PARAMETER DESCRIPTION
name

The declaration's name.

TYPE: str

statement

The declaration, as source syntax, or a generated property, which the run-time module keeps among its tests.

TYPE: Statement | TestDecl DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

provenance

Where it came from and the digest of everything it depends on.

TYPE: MetaProvenance

LibraryStore

Bases: Protocol

A content-addressed store the checked library can persist in.

ArtifactStore is one.

root property

root: Path

The store's directory.

get

get(namespace: str, key: str) -> bytes | None

Read an entry's payload, or None when there is no entry.

PARAMETER DESCRIPTION
namespace

The namespace.

TYPE: str

key

The key.

TYPE: str

RETURNS DESCRIPTION
bytes | None

The payload.

Source code in src/quivers/dsl/meta/phase.py
def get(self, namespace: str, key: str) -> bytes | None:
    """Read an entry's payload, or ``None`` when there is no entry.

    Parameters
    ----------
    namespace : str
        The namespace.
    key : str
        The key.

    Returns
    -------
    bytes | None
        The payload.
    """
    ...

put

put(namespace: str, key: str, payload: bytes, *, label: str = '') -> Model

Write an entry.

PARAMETER DESCRIPTION
namespace

The namespace.

TYPE: str

key

The key.

TYPE: str

payload

The payload.

TYPE: bytes

label

A description of the entry.

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION
Model

The written entry's record.

Source code in src/quivers/dsl/meta/phase.py
def put(
    self, namespace: str, key: str, payload: bytes, *, label: str = ""
) -> dx.Model:
    """Write an entry.

    Parameters
    ----------
    namespace : str
        The namespace.
    key : str
        The key.
    payload : bytes
        The payload.
    label : str
        A description of the entry.

    Returns
    -------
    dx.Model
        The written entry's record.
    """
    ...

MetaExpansion didactic-model

MetaExpansion(*, module: Module = field(opaque=True, extras=OPAQUE_BY_VALUE), generated: tuple[GeneratedDeclaration, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), assertions: tuple[StaticAssertion, ...] = ())

Bases: ValueModel

The run-time module that remains once the meta phase has run.

PARAMETER DESCRIPTION
module

The run-time module: the source's run-time declarations, their deriving clauses discharged, with the generated declarations spliced in where they were requested. It has no meta phase of its own.

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

generated

Every generated declaration, in splice order.

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

assertions

Every static assertion, each of which held.

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

locate

Name the generator of a generated declaration a diagnostic is in.

PARAMETER DESCRIPTION
error

A diagnostic from checking the run-time module.

TYPE: QiecDiagnosticError

RETURNS DESCRIPTION
QiecDiagnosticError

The same diagnostic when it is not located at a splice site; otherwise a diagnostic at the site whose message also names the generator and its location, and the generated declarations.

Source code in src/quivers/dsl/meta/phase.py
def locate(self, error: QiecDiagnosticError) -> QiecDiagnosticError:
    """Name the generator of a generated declaration a diagnostic is in.

    Parameters
    ----------
    error : QiecDiagnosticError
        A diagnostic from checking the run-time module.

    Returns
    -------
    QiecDiagnosticError
        The same diagnostic when it is not located at a splice site;
        otherwise a diagnostic at the site whose message also names the
        generator and its location, and the generated declarations.
    """
    sites = [
        item
        for item in self.generated
        if (item.provenance.site_line, item.provenance.site_col)
        == (error.line, error.column)
    ]
    if not sites:
        return error
    origin = sites[0].provenance
    names = ", ".join(item.name for item in sites)
    return QiecDiagnosticError(
        f"{error.message} (in the declaration{'s' if len(sites) > 1 else ''} "
        f"{names} generated by {origin.generator} at line "
        f"{origin.generator_line}, col {origin.generator_col}, "
        f"spliced at line {origin.site_line}, col {origin.site_col})",
        code=error.code,
        file=error.file,
        line=error.line,
        column=error.column,
        program=error.program,
    )

StaticAssertion didactic-model

StaticAssertion(*, source: str, line: int, col: int, holds: bool)

Bases: Model

The outcome of one static assert.

PARAMETER DESCRIPTION
source

The asserted condition as written.

TYPE: str

line

The assertion's 1-based source line.

TYPE: int

col

The assertion's 0-based source column.

TYPE: int

holds

Whether the condition evaluated to true.

TYPE: bool

MetaProvenance didactic-model

MetaProvenance(*, generator: str, generator_line: int, generator_col: int, site_line: int, site_col: int, digest: str)

Bases: Model

Where a generated declaration came from and what it depends on.

PARAMETER DESCRIPTION
generator

The meta computation that produced it: a splice's generator or a deriving handler.

TYPE: str

generator_line

The generator's declaration line.

TYPE: int

generator_col

The generator's declaration column.

TYPE: int

site_line

The line of the splice or deriving class that requested it.

TYPE: int

site_col

The column of that site.

TYPE: int

digest

The content-hash-domain digest of the meta inputs and the declaration.

TYPE: str

ReflectionError

Bases: ValueError

A declaration or a quoted value has no reflection in the other stratum.

MetaUniverse

MetaUniverse(module: QiecModule)

The checked meta module, seen as a universe of buildable values.

PARAMETER DESCRIPTION
module

The checked meta-phase module, which contains the meta prelude.

TYPE: QiecModule

Source code in src/quivers/dsl/meta/universe.py
def __init__(self, module: QiecModule) -> None:
    self.module = module
    self.families: dict[str, FamilyDecl] = {
        family.name: family for family in module.families
    }
    self.constructors: dict[str, ConstructorDecl] = {
        constructor.name: constructor for constructor in module.constructors
    }
    self._names = {
        constructor.id: constructor.name for constructor in module.constructors
    }
    self._families_by_id = {family.id: family for family in module.families}

family_type

family_type(name: str, arguments: tuple[StaticArgument, ...] = ()) -> TypeApplication

The type of a family of the universe at static arguments.

PARAMETER DESCRIPTION
name

The family's name.

TYPE: str

arguments

Its parameters, in order.

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

RETURNS DESCRIPTION
TypeApplication

The applied family type.

RAISES DESCRIPTION
MetaValueError

If the module declares no family of that name.

Source code in src/quivers/dsl/meta/universe.py
def family_type(
    self, name: str, arguments: tuple[StaticArgument, ...] = ()
) -> TypeApplication:
    """The type of a family of the universe at static arguments.

    Parameters
    ----------
    name : str
        The family's name.
    arguments : tuple[StaticArgument, ...]
        Its parameters, in order.

    Returns
    -------
    TypeApplication
        The applied family type.

    Raises
    ------
    MetaValueError
        If the module declares no family of that name.
    """
    family = self.families.get(name)
    if family is None:
        raise MetaValueError(f"the meta module declares no family {name!r}")
    return TypeApplication(constructor=family.type_constructor, arguments=arguments)

seq_type

seq_type(element: TypeExpr) -> TypeApplication

The type Seq[element].

PARAMETER DESCRIPTION
element

The element type.

TYPE: TypeExpr

RETURNS DESCRIPTION
TypeApplication

The sequence type.

Source code in src/quivers/dsl/meta/universe.py
def seq_type(self, element: TypeExpr) -> TypeApplication:
    """The type ``Seq[element]``.

    Parameters
    ----------
    element : TypeExpr
        The element type.

    Returns
    -------
    TypeApplication
        The sequence type.
    """
    return self.family_type("Seq", (element,))

make

make(constructor: str, fields: Sequence[MetaField] = (), static_arguments: tuple[StaticArgument, ...] = ()) -> RuntimeConstructor

Build a runtime value of one constructor.

PARAMETER DESCRIPTION
constructor

The constructor's name.

TYPE: str

fields

Its field values in declaration order. Host strings stay strings; integers, reals, and truth values become the scalar tensors the reference machine computes with.

TYPE: Sequence[MetaField] DEFAULT: ()

static_arguments

The family's parameters, for a constructor of a parameterized family such as SeqCons.

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

RETURNS DESCRIPTION
RuntimeConstructor

The value.

RAISES DESCRIPTION
MetaValueError

If the constructor is unknown or the number of fields or static arguments is wrong.

Source code in src/quivers/dsl/meta/universe.py
def make(
    self,
    constructor: str,
    fields: Sequence[MetaField] = (),
    static_arguments: tuple[StaticArgument, ...] = (),
) -> RuntimeConstructor:
    """Build a runtime value of one constructor.

    Parameters
    ----------
    constructor : str
        The constructor's name.
    fields : Sequence[MetaField]
        Its field values in declaration order. Host strings stay
        strings; integers, reals, and truth values become the scalar
        tensors the reference machine computes with.
    static_arguments : tuple[StaticArgument, ...]
        The family's parameters, for a constructor of a parameterized
        family such as ``SeqCons``.

    Returns
    -------
    RuntimeConstructor
        The value.

    Raises
    ------
    MetaValueError
        If the constructor is unknown or the number of fields or static
        arguments is wrong.
    """
    declaration = self.constructors.get(constructor)
    if declaration is None:
        raise MetaValueError(
            f"the meta module declares no constructor {constructor!r}"
        )
    family = self._families_by_id[declaration.family]
    if len(static_arguments) != len(family.parameters) + len(declaration.telescope):
        raise MetaValueError(
            f"constructor {constructor!r} takes "
            f"{len(family.parameters) + len(declaration.telescope)} static "
            f"arguments, got {len(static_arguments)}"
        )
    if len(fields) != len(declaration.fields):
        raise MetaValueError(
            f"constructor {constructor!r} takes {len(declaration.fields)} "
            f"fields, got {len(fields)}"
        )
    return RuntimeConstructor(
        constructor=declaration.id,
        static_arguments=static_arguments,
        fields=tuple(_runtime_field(value) for value in fields),
        result_type=TypeApplication(
            constructor=family.type_constructor,
            arguments=static_arguments[: len(family.parameters)],
        ),
    )

seq

seq(items: Sequence[MetaField], element: TypeExpr) -> RuntimeConstructor

Build Seq[element] holding the items in order.

PARAMETER DESCRIPTION
items

The elements.

TYPE: Sequence[MetaField]

element

Their type.

TYPE: TypeExpr

RETURNS DESCRIPTION
RuntimeConstructor

The sequence.

Source code in src/quivers/dsl/meta/universe.py
def seq(self, items: Sequence[MetaField], element: TypeExpr) -> RuntimeConstructor:
    """Build ``Seq[element]`` holding the items in order.

    Parameters
    ----------
    items : Sequence[MetaField]
        The elements.
    element : TypeExpr
        Their type.

    Returns
    -------
    RuntimeConstructor
        The sequence.
    """
    result = self.make("SeqNil", (), (element,))
    for item in reversed(items):
        result = self.make("SeqCons", (item, result), (element,))
    return result

strings

strings(items: Sequence[str]) -> RuntimeConstructor

Build Seq[String].

PARAMETER DESCRIPTION
items

The strings.

TYPE: Sequence[str]

RETURNS DESCRIPTION
RuntimeConstructor

The sequence.

Source code in src/quivers/dsl/meta/universe.py
def strings(self, items: Sequence[str]) -> RuntimeConstructor:
    """Build ``Seq[String]``.

    Parameters
    ----------
    items : Sequence[str]
        The strings.

    Returns
    -------
    RuntimeConstructor
        The sequence.
    """
    return self.seq(tuple(items), STRING)

name_of

name_of(value: object) -> str

The constructor a runtime value of the universe was built by.

PARAMETER DESCRIPTION
value

The value.

TYPE: object

RETURNS DESCRIPTION
str

Its constructor's name.

RAISES DESCRIPTION
MetaValueError

If the value is not a constructor value of this module.

Source code in src/quivers/dsl/meta/universe.py
def name_of(self, value: object) -> str:
    """The constructor a runtime value of the universe was built by.

    Parameters
    ----------
    value : object
        The value.

    Returns
    -------
    str
        Its constructor's name.

    Raises
    ------
    MetaValueError
        If the value is not a constructor value of this module.
    """
    if not isinstance(value, RuntimeConstructor):
        raise MetaValueError(f"expected a constructor value, got {value!r}")
    name = self._names.get(value.constructor)
    if name is None:
        raise MetaValueError(
            "a constructor value of another module reached the checker"
        )
    return name

fields_of

fields_of(value: object, expected: str, arity: int) -> tuple[object, ...]

The fields of a value built by an expected constructor.

PARAMETER DESCRIPTION
value

The value.

TYPE: object

expected

The constructor it must have been built by.

TYPE: str

arity

The number of fields that constructor has.

TYPE: int

RETURNS DESCRIPTION
tuple[object, ...]

The fields.

RAISES DESCRIPTION
MetaValueError

If the value was built by another constructor.

Source code in src/quivers/dsl/meta/universe.py
def fields_of(self, value: object, expected: str, arity: int) -> tuple[object, ...]:
    """The fields of a value built by an expected constructor.

    Parameters
    ----------
    value : object
        The value.
    expected : str
        The constructor it must have been built by.
    arity : int
        The number of fields that constructor has.

    Returns
    -------
    tuple[object, ...]
        The fields.

    Raises
    ------
    MetaValueError
        If the value was built by another constructor.
    """
    name = self.name_of(value)
    if name != expected:
        raise MetaValueError(f"expected a {expected} value, got {name}")
    assert isinstance(value, RuntimeConstructor)
    if len(value.fields) != arity:
        raise MetaValueError(
            f"{expected} has {arity} fields, got {len(value.fields)}"
        )
    return value.fields

read_seq

read_seq(value: object) -> tuple[object, ...]

The elements of a Seq value, in order.

PARAMETER DESCRIPTION
value

The sequence.

TYPE: object

RETURNS DESCRIPTION
tuple[object, ...]

Its elements.

RAISES DESCRIPTION
MetaValueError

If the value is not a sequence.

Source code in src/quivers/dsl/meta/universe.py
def read_seq(self, value: object) -> tuple[object, ...]:
    """The elements of a ``Seq`` value, in order.

    Parameters
    ----------
    value : object
        The sequence.

    Returns
    -------
    tuple[object, ...]
        Its elements.

    Raises
    ------
    MetaValueError
        If the value is not a sequence.
    """
    items: list[object] = []
    current = value
    while True:
        name = self.name_of(current)
        if name == "SeqNil":
            return tuple(items)
        head, tail = self.fields_of(current, "SeqCons", 2)
        items.append(head)
        current = tail

MetaValueError

Bases: ValueError

A runtime value does not have the shape its meta-phase family requires.

declared_names

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

The names a declaration introduces in any namespace.

PARAMETER DESCRIPTION
statement

The declaration.

TYPE: Statement

RETURNS DESCRIPTION
tuple[str, ...]

A family's name and its constructors' names, an index sort's name and its constructors' names, or the name of a computation, effect instance, handler, or pattern synonym. Other statements contribute no names.

Source code in src/quivers/dsl/meta/library.py
def declared_names(statement: Statement) -> tuple[str, ...]:
    """The names a declaration introduces in any namespace.

    Parameters
    ----------
    statement : Statement
        The declaration.

    Returns
    -------
    tuple[str, ...]
        A family's name and its constructors' names, an index sort's name and
        its constructors' names, or the name of a computation, effect
        instance, handler, or pattern synonym. Other statements contribute
        no names.
    """
    if isinstance(statement, QiecFamilyDecl):
        return (statement.name, *(c.name for c in statement.constructors))
    if isinstance(statement, QiecIndexDecl):
        return (statement.name, *(c.name for c in statement.constructors))
    if isinstance(
        statement,
        QiecComputationDecl
        | QiecEffectInstanceDecl
        | QiecHandlerDecl
        | QiecPatternSynonymDecl,
    ):
        return (statement.name,)
    return ()

meta_library cached

meta_library() -> MetaLibrary

Parse the meta-phase library once per process.

RETURNS DESCRIPTION
MetaLibrary

The library's declarations, names, and digest.

Source code in src/quivers/dsl/meta/library.py
@cache
def meta_library() -> MetaLibrary:
    """Parse the meta-phase library once per process.

    Returns
    -------
    MetaLibrary
        The library's declarations, names, and digest.
    """
    statements: list[Statement] = []
    sources: dict[str, CoreJson] = {}
    for name in LIBRARY_FILES:
        path = LIBRARY_DIRECTORY / name
        source = path.read_bytes()
        sources[name] = source.decode("utf-8")
        module: Module = parse(source, file_path=str(path))
        statements.extend(module.statements)
    names = frozenset(
        name for statement in statements for name in declared_names(statement)
    )
    computations = frozenset(
        statement.name
        for statement in statements
        if isinstance(statement, QiecComputationDecl)
    )
    return MetaLibrary(
        statements=tuple(statements),
        names=names,
        computations=computations,
        digest=tagged_digest("meta-library", sources),
    )

checked_library

checked_library() -> QiecModule

The meta-phase library, checked once per process.

Inside a persisting_meta_library block the library is read from the block's store when an earlier process wrote it there, and written there otherwise.

RETURNS DESCRIPTION
QiecModule

The library alone, checked under META_MODULE.

RAISES DESCRIPTION
StoreError

If the store's entry does not match its recorded digest.

TypeError

If the store's entry holds something other than a QIEC module.

Source code in src/quivers/dsl/meta/phase.py
def checked_library() -> QiecModule:
    """The meta-phase library, checked once per process.

    Inside a `persisting_meta_library` block the library is read from the
    block's store when an earlier process wrote it there, and written there
    otherwise.

    Returns
    -------
    QiecModule
        The library alone, checked under `META_MODULE`.

    Raises
    ------
    StoreError
        If the store's entry does not match its recorded digest.
    TypeError
        If the store's entry holds something other than a QIEC module.
    """
    persistence = _LIBRARY_STORE.get()
    digest = meta_library().digest
    checked = _LIBRARY_CHECKS.get(digest)
    if persistence is None:
        if checked is None:
            checked = _check_library()
            _LIBRARY_CHECKS[digest] = checked
        return checked
    store, engine = persistence
    key = library_key(engine)
    if (store.root, key) in _LIBRARY_PERSISTED and checked is not None:
        return checked
    payload = store.get(LIBRARY_NAMESPACE, key)
    if payload is None:
        if checked is None:
            checked = _check_library()
        store.put(
            LIBRARY_NAMESPACE,
            key,
            dumps(checked).encode("utf-8"),
            label="checked meta-phase library",
        )
    elif checked is None:
        checked = _decode_library(payload)
    _LIBRARY_CHECKS[digest] = checked
    _LIBRARY_PERSISTED.add((store.root, key))
    return checked

expand_meta

expand_meta(module: Module, *, module_name: str, file_path: str) -> MetaExpansion

Run the meta phase of a parsed module.

The module's quotations are elaborated through its notations first (expand_notation), so meta code may quote terms, and the expanded module carries no notation statements.

PARAMETER DESCRIPTION
module

The parsed module.

TYPE: Module

module_name

The module's name, from which the meta module's identities derive.

TYPE: str

file_path

The path recorded on diagnostics.

TYPE: str

RETURNS DESCRIPTION
MetaExpansion

The run-time module, the generated declarations, and the assertions' outcomes.

RAISES DESCRIPTION
QiecDiagnosticError

If a meta declaration does not check, a run-time declaration names a meta declaration (qiec-phase), a name collides with the meta-phase library (qiec-meta-name), a static assertion is false (qiec-static-assert), a splice or deriving handler refuses or returns something other than declarations (qiec-splice, qiec-deriving), or a meta evaluation fails.

Source code in src/quivers/dsl/meta/phase.py
def expand_meta(module: Module, *, module_name: str, file_path: str) -> MetaExpansion:
    """Run the meta phase of a parsed module.

    The module's quotations are elaborated through its notations first
    ([`expand_notation`][quivers.dsl.notation.elaborate.expand_notation]),
    so meta code may quote terms, and the expanded module carries no
    notation statements.

    Parameters
    ----------
    module : Module
        The parsed module.
    module_name : str
        The module's name, from which the meta module's identities derive.
    file_path : str
        The path recorded on diagnostics.

    Returns
    -------
    MetaExpansion
        The run-time module, the generated declarations, and the
        assertions' outcomes.

    Raises
    ------
    QiecDiagnosticError
        If a meta declaration does not check, a run-time declaration names
        a meta declaration (``qiec-phase``), a name collides with the
        meta-phase library (``qiec-meta-name``), a static assertion is
        false (``qiec-static-assert``), a splice or deriving handler
        refuses or returns something other than declarations
        (``qiec-splice``, ``qiec-deriving``), or a meta evaluation fails.
    """
    try:
        module = compose_deductions(module)
    except CompositionError as error:
        raise QiecDiagnosticError(
            str(error),
            code="qiec-deduction",
            file=file_path,
            line=error.line,
            column=error.col,
        ) from error
    try:
        module = expand_lexical(
            module, module_name=module_name, file_path=file_path
        ).module
    except LexicalError as error:
        raise QiecDiagnosticError(
            error.message,
            code=LexicalError.code,
            file=file_path,
            line=error.line,
            column=error.col,
        ) from error
    if not has_meta_surface(module):
        return MetaExpansion(module=module)
    module = expand_notation(module, file_path=file_path)
    return _MetaPhase(module, module_name=module_name, file_path=file_path).run()

has_meta_surface

has_meta_surface(module: Module) -> bool

Whether a module has anything for the meta phase to do.

PARAMETER DESCRIPTION
module

The parsed module.

TYPE: Module

RETURNS DESCRIPTION
bool

True when it has a meta declaration, a static assertion, a splice, or a deriving clause.

Source code in src/quivers/dsl/meta/phase.py
def has_meta_surface(module: Module) -> bool:
    """Whether a module has anything for the meta phase to do.

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

    Returns
    -------
    bool
        True when it has a meta declaration, a static assertion, a splice,
        or a deriving clause.
    """
    return any(
        isinstance(statement, META_STATEMENT_TYPES)
        or (
            isinstance(statement, QiecFamilyDecl | DeductionDecl) and statement.deriving
        )
        for statement in module.statements
    )

library_key

library_key(engine: str) -> str

The store key of the checked meta-phase library.

PARAMETER DESCRIPTION
engine

The digest of the engine that checks the library.

TYPE: str

RETURNS DESCRIPTION
str

The content-hash-domain digest, of kind meta-library-check, of the library's source digest and the engine, so an edit to the library or a different engine misses every earlier entry.

Source code in src/quivers/dsl/meta/phase.py
def library_key(engine: str) -> str:
    """The store key of the checked meta-phase library.

    Parameters
    ----------
    engine : str
        The digest of the engine that checks the library.

    Returns
    -------
    str
        The content-hash-domain digest, of kind ``meta-library-check``, of the
        library's source digest and the engine, so an edit to the library or a
        different engine misses every earlier entry.
    """
    return tagged_digest(
        "meta-library-check",
        {"library": meta_library().digest, "engine": engine},
    )

persisting_meta_library

persisting_meta_library(store: LibraryStore, *, engine: str) -> Iterator[LibraryStore]

Persist the checked meta-phase library in a store while in the block.

Every meta phase run inside the block reads the checked library from the store, or checks it and writes it there, so a later process with the same store and engine reuses it instead of checking it again.

PARAMETER DESCRIPTION
store

The store, usually the project's (ArtifactStore.for_project).

TYPE: LibraryStore

engine

The digest of the engine that checks the library (engine_identity); an entry written under another engine is never read.

TYPE: str

YIELDS DESCRIPTION
LibraryStore

The store.

Source code in src/quivers/dsl/meta/phase.py
@contextmanager
def persisting_meta_library(
    store: LibraryStore, *, engine: str
) -> Iterator[LibraryStore]:
    """Persist the checked meta-phase library in a store while in the block.

    Every meta phase run inside the block reads the checked library from the
    store, or checks it and writes it there, so a later process with the same
    store and engine reuses it instead of checking it again.

    Parameters
    ----------
    store : LibraryStore
        The store, usually the project's
        ([`ArtifactStore.for_project`][quivers.incremental.store.ArtifactStore.for_project]).
    engine : str
        The digest of the engine that checks the library
        ([`engine_identity`][quivers.incremental.engine.engine_identity]);
        an entry written under another engine is never read.

    Yields
    ------
    LibraryStore
        The store.
    """
    token = _LIBRARY_STORE.set((store, engine))
    try:
        yield store
    finally:
        _LIBRARY_STORE.reset(token)

canonical_syntax

canonical_syntax(node: SyntaxValue) -> str

Render source syntax canonically, without positions or doc comments.

PARAMETER DESCRIPTION
node

A syntax node, a tuple of them, or a leaf.

TYPE: SyntaxValue

RETURNS DESCRIPTION
str

A rendering in which every node shows its class and its fields by name, so two syntax trees render alike exactly when they say the same thing, wherever they were written.

Source code in src/quivers/dsl/meta/provenance.py
def canonical_syntax(node: SyntaxValue) -> str:
    """Render source syntax canonically, without positions or doc comments.

    Parameters
    ----------
    node : SyntaxValue
        A syntax node, a tuple of them, or a leaf.

    Returns
    -------
    str
        A rendering in which every node shows its class and its fields by
        name, so two syntax trees render alike exactly when they say the
        same thing, wherever they were written.
    """
    if isinstance(node, tuple):
        return "(" + ", ".join(canonical_syntax(item) for item in node) + ")"
    if isinstance(node, dx.Model):
        fields = ", ".join(
            f"{name}={canonical_syntax(getattr(node, name))}"
            for name in type(node).__field_specs__
            if name not in _POSITION_FIELDS
        )
        return f"{type(node).__name__}({fields})"
    return repr(node)

provenance_digest

provenance_digest(*, library: str, closure: Sequence[str], inputs: Sequence[str], declaration: str) -> str

Digest a generated declaration together with its meta inputs.

PARAMETER DESCRIPTION
library

The digest of the meta-phase library's source.

TYPE: str

closure

The canonical source of each module meta declaration the generator reached, in name order.

TYPE: Sequence[str]

inputs

The rendered inputs the generator ran on, in order.

TYPE: Sequence[str]

declaration

The generated declaration's canonical source.

TYPE: str

RETURNS DESCRIPTION
str

The content-hash-domain digest, of kind meta-provenance, of the parts as one canonical JSON form.

Source code in src/quivers/dsl/meta/provenance.py
def provenance_digest(
    *,
    library: str,
    closure: Sequence[str],
    inputs: Sequence[str],
    declaration: str,
) -> str:
    """Digest a generated declaration together with its meta inputs.

    Parameters
    ----------
    library : str
        The digest of the meta-phase library's source.
    closure : Sequence[str]
        The canonical source of each module meta declaration the generator
        reached, in name order.
    inputs : Sequence[str]
        The rendered inputs the generator ran on, in order.
    declaration : str
        The generated declaration's canonical source.

    Returns
    -------
    str
        The content-hash-domain digest, of kind ``meta-provenance``, of the
        parts as one canonical JSON form.
    """
    return tagged_digest(
        "meta-provenance",
        {
            "library": library,
            "closure": list(closure),
            "inputs": list(inputs),
            "declaration": declaration,
        },
    )

describe_family

describe_family(universe: MetaUniverse, family: FamilyDecl, constructors: Sequence[ConstructorDecl], written: Mapping[str, tuple[QiecTypeExpr, ...]], records: Mapping[str, QiecRecordDecl]) -> RuntimeConstructor

The description of a checked family, as a Desc value.

A checked row lists its labels in alphabetical order, so a record or variant field type is quoted with its entries in the order its source writes them: the order of the record type written in the field, or of the record declaration the field names.

PARAMETER DESCRIPTION
universe

The meta universe the value is built in.

TYPE: MetaUniverse

family

The family, declared in source or generated by a declaration.

TYPE: FamilyDecl

constructors

Its constructors, in any order; they are described in the order the family lists them.

TYPE: Sequence[ConstructorDecl]

written

The field types each constructor's source declaration writes, by the constructor's declared name; empty for a family a declaration generates, whose checked fields are its declaration.

TYPE: Mapping[str, tuple[QiecTypeExpr, ...]]

records

The record declarations of the program, by name.

TYPE: Mapping[str, QiecRecordDecl]

RETURNS DESCRIPTION
RuntimeConstructor

Desc(name, parameters, indices, constructors).

RAISES DESCRIPTION
ReflectionError

If a constructor is missing, or a field type has no quoted form.

Source code in src/quivers/dsl/meta/reflect.py
def describe_family(
    universe: MetaUniverse,
    family: FamilyDecl,
    constructors: Sequence[ConstructorDecl],
    written: Mapping[str, tuple[QiecTypeExpr, ...]],
    records: Mapping[str, QiecRecordDecl],
) -> RuntimeConstructor:
    """The description of a checked family, as a ``Desc`` value.

    A checked row lists its labels in alphabetical order, so a record or
    variant field type is quoted with its entries in the order its source
    writes them: the order of the record type written in the field, or of
    the ``record`` declaration the field names.

    Parameters
    ----------
    universe : MetaUniverse
        The meta universe the value is built in.
    family : FamilyDecl
        The family, declared in source or generated by a declaration.
    constructors : Sequence[ConstructorDecl]
        Its constructors, in any order; they are described in the order
        the family lists them.
    written : Mapping[str, tuple[QiecTypeExpr, ...]]
        The field types each constructor's source declaration writes, by
        the constructor's declared name; empty for a family a declaration
        generates, whose checked fields are its declaration.
    records : Mapping[str, QiecRecordDecl]
        The ``record`` declarations of the program, by name.

    Returns
    -------
    RuntimeConstructor
        ``Desc(name, parameters, indices, constructors)``.

    Raises
    ------
    ReflectionError
        If a constructor is missing, or a field type has no quoted form.
    """
    by_id = {constructor.id: constructor for constructor in constructors}
    missing = [identity for identity in family.constructors if identity not in by_id]
    if missing:
        raise ReflectionError(
            f"family {family.name!r} lists constructors that were not given"
        )
    parameters = {
        binder.name for binder in family.parameters if isinstance(binder, TypeBinder)
    }
    binder_type = universe.family_type("SynBinder")
    described = tuple(
        _describe_constructor(
            universe,
            family,
            by_id[identity],
            parameters,
            written.get(split_module(by_id[identity].name)[1], ()),
            records,
        )
        for identity in family.constructors
    )
    return universe.make(
        "Desc",
        (
            family.name,
            universe.seq(_binders(universe, family.parameters), binder_type),
            universe.seq(_binders(universe, family.indices), binder_type),
            universe.seq(described, universe.family_type("CtorDesc")),
        ),
    )

read_declarations

read_declarations(universe: MetaUniverse, value: object, *, line: int, col: int) -> tuple[Statement | TestDecl, ...]

Read the declarations a meta computation returned.

PARAMETER DESCRIPTION
universe

The meta universe the value was built in.

TYPE: MetaUniverse

value

A SynDecl value or a Seq[SynDecl] value.

TYPE: object

line

The source line the declarations are checked at.

TYPE: int

col

The source column the declarations are checked at.

TYPE: int

RETURNS DESCRIPTION
tuple[Statement | TestDecl, ...]

The source declarations and properties, in order.

RAISES DESCRIPTION
ReflectionError

If the value is not quoted declarations.

Source code in src/quivers/dsl/meta/reflect.py
def read_declarations(
    universe: MetaUniverse, value: object, *, line: int, col: int
) -> tuple[Statement | TestDecl, ...]:
    """Read the declarations a meta computation returned.

    Parameters
    ----------
    universe : MetaUniverse
        The meta universe the value was built in.
    value : object
        A ``SynDecl`` value or a ``Seq[SynDecl]`` value.
    line : int
        The source line the declarations are checked at.
    col : int
        The source column the declarations are checked at.

    Returns
    -------
    tuple[Statement | TestDecl, ...]
        The source declarations and properties, in order.

    Raises
    ------
    ReflectionError
        If the value is not quoted declarations.
    """
    reader = _Reader(universe, line, col)
    try:
        if universe.name_of(value) in ("SeqNil", "SeqCons"):
            return tuple(reader.declaration(item) for item in reader.seq(value))
        return (reader.declaration(value),)
    except MetaValueError as error:
        raise ReflectionError(str(error)) from error

syn_static

syn_static(universe: MetaUniverse, argument: QiecStaticArgument) -> RuntimeConstructor

Quote a source static argument.

PARAMETER DESCRIPTION
universe

The meta universe.

TYPE: MetaUniverse

argument

The argument as written.

TYPE: QiecStaticArgument

RETURNS DESCRIPTION
RuntimeConstructor

The SynStatic value.

Source code in src/quivers/dsl/meta/reflect.py
def syn_static(
    universe: MetaUniverse, argument: QiecStaticArgument
) -> RuntimeConstructor:
    """Quote a source static argument.

    Parameters
    ----------
    universe : MetaUniverse
        The meta universe.
    argument : QiecStaticArgument
        The argument as written.

    Returns
    -------
    RuntimeConstructor
        The ``SynStatic`` value.
    """
    if isinstance(argument, QiecIndexLiteral):
        return universe.make(
            "StaticIndex", (universe.make("IndexLiteral", (argument.value,)),)
        )
    return universe.make("StaticType", (syn_type(universe, argument),))

syn_type

syn_type(universe: MetaUniverse, type_: QiecTypeExpr) -> RuntimeConstructor

Quote a source type as a SynType value.

PARAMETER DESCRIPTION
universe

The meta universe.

TYPE: MetaUniverse

type_

The type as written.

TYPE: QiecTypeExpr

RETURNS DESCRIPTION
RuntimeConstructor

The quoted type.

RAISES DESCRIPTION
ReflectionError

If the type has no quoted form.

Source code in src/quivers/dsl/meta/reflect.py
def syn_type(universe: MetaUniverse, type_: QiecTypeExpr) -> RuntimeConstructor:
    """Quote a source type as a ``SynType`` value.

    Parameters
    ----------
    universe : MetaUniverse
        The meta universe.
    type_ : QiecTypeExpr
        The type as written.

    Returns
    -------
    RuntimeConstructor
        The quoted type.

    Raises
    ------
    ReflectionError
        If the type has no quoted form.
    """
    if isinstance(type_, QiecTypeName):
        return universe.make("TypeName", (type_.name,))
    if isinstance(type_, QiecTypeApplication):
        return universe.make(
            "TypeApply",
            (
                type_.constructor,
                universe.seq(
                    tuple(syn_static(universe, a) for a in type_.static_arguments),
                    universe.family_type("SynStatic"),
                ),
                universe.seq(
                    tuple(_syn_index(universe, i) for i in type_.indices),
                    universe.family_type("SynIndex"),
                ),
            ),
        )
    if isinstance(type_, QiecProductType):
        return universe.make(
            "TypeProduct",
            (
                universe.seq(
                    tuple(syn_type(universe, c) for c in type_.components),
                    universe.family_type("SynType"),
                ),
            ),
        )
    if isinstance(type_, QiecFunctionType):
        parameter = syn_type(universe, type_.parameter)
        result = syn_type(universe, type_.result)
        if type_.row is None:
            return universe.make("TypeFunction", (parameter, result))
        entries = universe.strings(tuple(entry.instance for entry in type_.row.entries))
        quoted_row = (
            universe.make("RowClosed", (entries,))
            if type_.row.tail is None
            else universe.make("RowOpen", (entries, type_.row.tail))
        )
        return universe.make("TypeEffectful", (parameter, result, quoted_row))
    if isinstance(type_, QiecFinType):
        return universe.make("TypeFin", (_syn_index(universe, type_.extent),))
    if isinstance(type_, QiecTensorType):
        return universe.make(
            "TypeTensor",
            (
                syn_type(universe, type_.element),
                universe.seq(
                    tuple(syn_type(universe, axis) for axis in type_.axes),
                    universe.family_type("SynType"),
                ),
            ),
        )
    if isinstance(type_, QiecRecordType):
        return universe.make("TypeRecord", (_syn_row(universe, type_),))
    if isinstance(type_, QiecVariantType):
        return universe.make("TypeVariant", (_syn_row(universe, type_),))
    raise ReflectionError(f"type {type_!r} has no quoted form")

syn_type_of_kernel

syn_type_of_kernel(universe: MetaUniverse, type_: TypeExpr) -> RuntimeConstructor

Quote a checked type as a SynType value.

An argument whose binder is refinable, or which is a shape, is written in parentheses after the bracketed static arguments, as source writes Vec[A](n) and Real[Fin 3].

PARAMETER DESCRIPTION
universe

The meta universe.

TYPE: MetaUniverse

type_

The checked type.

TYPE: TypeExpr

RETURNS DESCRIPTION
RuntimeConstructor

The quoted type.

RAISES DESCRIPTION
ReflectionError

If the type has no quoted form.

Source code in src/quivers/dsl/meta/reflect.py
def syn_type_of_kernel(universe: MetaUniverse, type_: TypeExpr) -> RuntimeConstructor:
    """Quote a checked type as a ``SynType`` value.

    An argument whose binder is refinable, or which is a shape, is written
    in parentheses after the bracketed static arguments, as source writes
    ``Vec[A](n)`` and ``Real[Fin 3]``.

    Parameters
    ----------
    universe : MetaUniverse
        The meta universe.
    type_ : TypeExpr
        The checked type.

    Returns
    -------
    RuntimeConstructor
        The quoted type.

    Raises
    ------
    ReflectionError
        If the type has no quoted form.
    """
    if isinstance(type_, TypeVariable):
        return universe.make("TypeName", (type_.name,))
    if isinstance(type_, RecordType):
        return universe.make("TypeRecord", (_syn_row_of_kernel(universe, type_.row),))
    if isinstance(type_, VariantType):
        return universe.make("TypeVariant", (_syn_row_of_kernel(universe, type_.row),))
    if isinstance(type_, FunctionType):
        parameter = syn_type_of_kernel(universe, type_.parameter)
        result = syn_type_of_kernel(universe, type_.result)
        row = type_.effects
        if not row.entries and row.tail is None:
            return universe.make("TypeFunction", (parameter, result))
        if row.entries or row.tail is None:
            raise ReflectionError(
                "a field whose type is a function performing named instances has "
                "no quoted form"
            )
        quoted_row = universe.make("RowOpen", (universe.strings(()), row.tail.name))
        return universe.make("TypeEffectful", (parameter, result, quoted_row))
    if (
        isinstance(type_, TypeApplication)
        and type_.constructor.id == TENSOR_CONSTRUCTOR.id
    ):
        return _syn_tensor_of_kernel(universe, type_)
    if isinstance(type_, TypeApplication):
        constructor = type_.constructor
        components = _product_components(type_)
        if components is not None:
            return universe.make(
                "TypeProduct",
                (
                    universe.seq(
                        tuple(syn_type_of_kernel(universe, c) for c in components),
                        universe.family_type("SynType"),
                    ),
                ),
            )
        statics: list[RuntimeConstructor] = []
        indices: list[RuntimeConstructor] = []
        binders = constructor.telescope
        for position, argument in enumerate(type_.arguments):
            binder = binders[position] if position < len(binders) else None
            parenthesized = isinstance(argument, ShapeIndex) or (
                isinstance(binder, IndexBinder)
                and (binder.refinable or isinstance(binder.sort, ShapeSort))
            )
            if parenthesized:
                indices.append(_syn_index_of_kernel(universe, argument))
            else:
                statics.append(_syn_static_of_kernel(universe, argument))
        if not statics and not indices:
            return universe.make("TypeName", (constructor.name,))
        return universe.make(
            "TypeApply",
            (
                constructor.name,
                universe.seq(tuple(statics), universe.family_type("SynStatic")),
                universe.seq(tuple(indices), universe.family_type("SynIndex")),
            ),
        )
    raise ReflectionError(f"type {type_!r} has no quoted form")

read_bool

read_bool(value: object) -> bool

Read a Bool field.

PARAMETER DESCRIPTION
value

The field: a truth tensor of one element, or a host Boolean.

TYPE: object

RETURNS DESCRIPTION
bool

The truth value.

RAISES DESCRIPTION
MetaValueError

If the field is not a truth value.

Source code in src/quivers/dsl/meta/universe.py
def read_bool(value: object) -> bool:
    """Read a ``Bool`` field.

    Parameters
    ----------
    value : object
        The field: a truth tensor of one element, or a host Boolean.

    Returns
    -------
    bool
        The truth value.

    Raises
    ------
    MetaValueError
        If the field is not a truth value.
    """
    if (
        isinstance(value, torch.Tensor)
        and value.numel() == 1
        and value.dtype == torch.bool
    ):
        return bool(value.item())
    if isinstance(value, bool):
        return value
    raise MetaValueError(f"expected a truth value, got {value!r}")

read_int

read_int(value: object) -> int

Read an Int field.

PARAMETER DESCRIPTION
value

The field: an integer tensor of one element, or a host integer.

TYPE: object

RETURNS DESCRIPTION
int

The integer.

RAISES DESCRIPTION
MetaValueError

If the field is not an integer.

Source code in src/quivers/dsl/meta/universe.py
def read_int(value: object) -> int:
    """Read an ``Int`` field.

    Parameters
    ----------
    value : object
        The field: an integer tensor of one element, or a host integer.

    Returns
    -------
    int
        The integer.

    Raises
    ------
    MetaValueError
        If the field is not an integer.
    """
    if isinstance(value, torch.Tensor) and value.numel() == 1:
        if value.dtype.is_floating_point or value.dtype == torch.bool:
            raise MetaValueError(f"expected an integer, got {value!r}")
        return int(value.item())
    if isinstance(value, int) and not isinstance(value, bool):
        return value
    raise MetaValueError(f"expected an integer, got {value!r}")

read_real

read_real(value: object) -> float

Read a Real field.

PARAMETER DESCRIPTION
value

The field: a tensor of one element, or a host number.

TYPE: object

RETURNS DESCRIPTION
float

The number.

RAISES DESCRIPTION
MetaValueError

If the field is not a number.

Source code in src/quivers/dsl/meta/universe.py
def read_real(value: object) -> float:
    """Read a ``Real`` field.

    Parameters
    ----------
    value : object
        The field: a tensor of one element, or a host number.

    Returns
    -------
    float
        The number.

    Raises
    ------
    MetaValueError
        If the field is not a number.
    """
    if isinstance(value, torch.Tensor) and value.numel() == 1:
        return float(value.item())
    if isinstance(value, int | float) and not isinstance(value, bool):
        return float(value)
    raise MetaValueError(f"expected a real number, got {value!r}")

read_string

read_string(value: object) -> str

Read a String field.

PARAMETER DESCRIPTION
value

The field.

TYPE: object

RETURNS DESCRIPTION
str

The string.

RAISES DESCRIPTION
MetaValueError

If the field is not a string.

Source code in src/quivers/dsl/meta/universe.py
def read_string(value: object) -> str:
    """Read a ``String`` field.

    Parameters
    ----------
    value : object
        The field.

    Returns
    -------
    str
        The string.

    Raises
    ------
    MetaValueError
        If the field is not a string.
    """
    if not isinstance(value, str):
        raise MetaValueError(f"expected a string, got {value!r}")
    return value

reflect

Reflection between checked declarations, quoted syntax, and source syntax.

Three directions meet here:

  • a checked family, user-declared or generated, becomes a Desc value, the code of the sum of products the family is (describe_family);
  • a source type becomes a SynType value (syn_type), so a deriving class's static arguments reach its handler as data;
  • a SynDecl value a meta computation returns becomes source declarations (read_declarations), which are then checked like hand-written ones.

The quoted-syntax families are the single representation of quoted code: a typed quotation elaborates to their constructor trees, and an antiquotation is a value of the same families.

ReflectionError

Bases: ValueError

A declaration or a quoted value has no reflection in the other stratum.

describe_family

describe_family(universe: MetaUniverse, family: FamilyDecl, constructors: Sequence[ConstructorDecl], written: Mapping[str, tuple[QiecTypeExpr, ...]], records: Mapping[str, QiecRecordDecl]) -> RuntimeConstructor

The description of a checked family, as a Desc value.

A checked row lists its labels in alphabetical order, so a record or variant field type is quoted with its entries in the order its source writes them: the order of the record type written in the field, or of the record declaration the field names.

PARAMETER DESCRIPTION
universe

The meta universe the value is built in.

TYPE: MetaUniverse

family

The family, declared in source or generated by a declaration.

TYPE: FamilyDecl

constructors

Its constructors, in any order; they are described in the order the family lists them.

TYPE: Sequence[ConstructorDecl]

written

The field types each constructor's source declaration writes, by the constructor's declared name; empty for a family a declaration generates, whose checked fields are its declaration.

TYPE: Mapping[str, tuple[QiecTypeExpr, ...]]

records

The record declarations of the program, by name.

TYPE: Mapping[str, QiecRecordDecl]

RETURNS DESCRIPTION
RuntimeConstructor

Desc(name, parameters, indices, constructors).

RAISES DESCRIPTION
ReflectionError

If a constructor is missing, or a field type has no quoted form.

Source code in src/quivers/dsl/meta/reflect.py
def describe_family(
    universe: MetaUniverse,
    family: FamilyDecl,
    constructors: Sequence[ConstructorDecl],
    written: Mapping[str, tuple[QiecTypeExpr, ...]],
    records: Mapping[str, QiecRecordDecl],
) -> RuntimeConstructor:
    """The description of a checked family, as a ``Desc`` value.

    A checked row lists its labels in alphabetical order, so a record or
    variant field type is quoted with its entries in the order its source
    writes them: the order of the record type written in the field, or of
    the ``record`` declaration the field names.

    Parameters
    ----------
    universe : MetaUniverse
        The meta universe the value is built in.
    family : FamilyDecl
        The family, declared in source or generated by a declaration.
    constructors : Sequence[ConstructorDecl]
        Its constructors, in any order; they are described in the order
        the family lists them.
    written : Mapping[str, tuple[QiecTypeExpr, ...]]
        The field types each constructor's source declaration writes, by
        the constructor's declared name; empty for a family a declaration
        generates, whose checked fields are its declaration.
    records : Mapping[str, QiecRecordDecl]
        The ``record`` declarations of the program, by name.

    Returns
    -------
    RuntimeConstructor
        ``Desc(name, parameters, indices, constructors)``.

    Raises
    ------
    ReflectionError
        If a constructor is missing, or a field type has no quoted form.
    """
    by_id = {constructor.id: constructor for constructor in constructors}
    missing = [identity for identity in family.constructors if identity not in by_id]
    if missing:
        raise ReflectionError(
            f"family {family.name!r} lists constructors that were not given"
        )
    parameters = {
        binder.name for binder in family.parameters if isinstance(binder, TypeBinder)
    }
    binder_type = universe.family_type("SynBinder")
    described = tuple(
        _describe_constructor(
            universe,
            family,
            by_id[identity],
            parameters,
            written.get(split_module(by_id[identity].name)[1], ()),
            records,
        )
        for identity in family.constructors
    )
    return universe.make(
        "Desc",
        (
            family.name,
            universe.seq(_binders(universe, family.parameters), binder_type),
            universe.seq(_binders(universe, family.indices), binder_type),
            universe.seq(described, universe.family_type("CtorDesc")),
        ),
    )

syn_type_of_kernel

syn_type_of_kernel(universe: MetaUniverse, type_: TypeExpr) -> RuntimeConstructor

Quote a checked type as a SynType value.

An argument whose binder is refinable, or which is a shape, is written in parentheses after the bracketed static arguments, as source writes Vec[A](n) and Real[Fin 3].

PARAMETER DESCRIPTION
universe

The meta universe.

TYPE: MetaUniverse

type_

The checked type.

TYPE: TypeExpr

RETURNS DESCRIPTION
RuntimeConstructor

The quoted type.

RAISES DESCRIPTION
ReflectionError

If the type has no quoted form.

Source code in src/quivers/dsl/meta/reflect.py
def syn_type_of_kernel(universe: MetaUniverse, type_: TypeExpr) -> RuntimeConstructor:
    """Quote a checked type as a ``SynType`` value.

    An argument whose binder is refinable, or which is a shape, is written
    in parentheses after the bracketed static arguments, as source writes
    ``Vec[A](n)`` and ``Real[Fin 3]``.

    Parameters
    ----------
    universe : MetaUniverse
        The meta universe.
    type_ : TypeExpr
        The checked type.

    Returns
    -------
    RuntimeConstructor
        The quoted type.

    Raises
    ------
    ReflectionError
        If the type has no quoted form.
    """
    if isinstance(type_, TypeVariable):
        return universe.make("TypeName", (type_.name,))
    if isinstance(type_, RecordType):
        return universe.make("TypeRecord", (_syn_row_of_kernel(universe, type_.row),))
    if isinstance(type_, VariantType):
        return universe.make("TypeVariant", (_syn_row_of_kernel(universe, type_.row),))
    if isinstance(type_, FunctionType):
        parameter = syn_type_of_kernel(universe, type_.parameter)
        result = syn_type_of_kernel(universe, type_.result)
        row = type_.effects
        if not row.entries and row.tail is None:
            return universe.make("TypeFunction", (parameter, result))
        if row.entries or row.tail is None:
            raise ReflectionError(
                "a field whose type is a function performing named instances has "
                "no quoted form"
            )
        quoted_row = universe.make("RowOpen", (universe.strings(()), row.tail.name))
        return universe.make("TypeEffectful", (parameter, result, quoted_row))
    if (
        isinstance(type_, TypeApplication)
        and type_.constructor.id == TENSOR_CONSTRUCTOR.id
    ):
        return _syn_tensor_of_kernel(universe, type_)
    if isinstance(type_, TypeApplication):
        constructor = type_.constructor
        components = _product_components(type_)
        if components is not None:
            return universe.make(
                "TypeProduct",
                (
                    universe.seq(
                        tuple(syn_type_of_kernel(universe, c) for c in components),
                        universe.family_type("SynType"),
                    ),
                ),
            )
        statics: list[RuntimeConstructor] = []
        indices: list[RuntimeConstructor] = []
        binders = constructor.telescope
        for position, argument in enumerate(type_.arguments):
            binder = binders[position] if position < len(binders) else None
            parenthesized = isinstance(argument, ShapeIndex) or (
                isinstance(binder, IndexBinder)
                and (binder.refinable or isinstance(binder.sort, ShapeSort))
            )
            if parenthesized:
                indices.append(_syn_index_of_kernel(universe, argument))
            else:
                statics.append(_syn_static_of_kernel(universe, argument))
        if not statics and not indices:
            return universe.make("TypeName", (constructor.name,))
        return universe.make(
            "TypeApply",
            (
                constructor.name,
                universe.seq(tuple(statics), universe.family_type("SynStatic")),
                universe.seq(tuple(indices), universe.family_type("SynIndex")),
            ),
        )
    raise ReflectionError(f"type {type_!r} has no quoted form")

syn_type

syn_type(universe: MetaUniverse, type_: QiecTypeExpr) -> RuntimeConstructor

Quote a source type as a SynType value.

PARAMETER DESCRIPTION
universe

The meta universe.

TYPE: MetaUniverse

type_

The type as written.

TYPE: QiecTypeExpr

RETURNS DESCRIPTION
RuntimeConstructor

The quoted type.

RAISES DESCRIPTION
ReflectionError

If the type has no quoted form.

Source code in src/quivers/dsl/meta/reflect.py
def syn_type(universe: MetaUniverse, type_: QiecTypeExpr) -> RuntimeConstructor:
    """Quote a source type as a ``SynType`` value.

    Parameters
    ----------
    universe : MetaUniverse
        The meta universe.
    type_ : QiecTypeExpr
        The type as written.

    Returns
    -------
    RuntimeConstructor
        The quoted type.

    Raises
    ------
    ReflectionError
        If the type has no quoted form.
    """
    if isinstance(type_, QiecTypeName):
        return universe.make("TypeName", (type_.name,))
    if isinstance(type_, QiecTypeApplication):
        return universe.make(
            "TypeApply",
            (
                type_.constructor,
                universe.seq(
                    tuple(syn_static(universe, a) for a in type_.static_arguments),
                    universe.family_type("SynStatic"),
                ),
                universe.seq(
                    tuple(_syn_index(universe, i) for i in type_.indices),
                    universe.family_type("SynIndex"),
                ),
            ),
        )
    if isinstance(type_, QiecProductType):
        return universe.make(
            "TypeProduct",
            (
                universe.seq(
                    tuple(syn_type(universe, c) for c in type_.components),
                    universe.family_type("SynType"),
                ),
            ),
        )
    if isinstance(type_, QiecFunctionType):
        parameter = syn_type(universe, type_.parameter)
        result = syn_type(universe, type_.result)
        if type_.row is None:
            return universe.make("TypeFunction", (parameter, result))
        entries = universe.strings(tuple(entry.instance for entry in type_.row.entries))
        quoted_row = (
            universe.make("RowClosed", (entries,))
            if type_.row.tail is None
            else universe.make("RowOpen", (entries, type_.row.tail))
        )
        return universe.make("TypeEffectful", (parameter, result, quoted_row))
    if isinstance(type_, QiecFinType):
        return universe.make("TypeFin", (_syn_index(universe, type_.extent),))
    if isinstance(type_, QiecTensorType):
        return universe.make(
            "TypeTensor",
            (
                syn_type(universe, type_.element),
                universe.seq(
                    tuple(syn_type(universe, axis) for axis in type_.axes),
                    universe.family_type("SynType"),
                ),
            ),
        )
    if isinstance(type_, QiecRecordType):
        return universe.make("TypeRecord", (_syn_row(universe, type_),))
    if isinstance(type_, QiecVariantType):
        return universe.make("TypeVariant", (_syn_row(universe, type_),))
    raise ReflectionError(f"type {type_!r} has no quoted form")

syn_static

syn_static(universe: MetaUniverse, argument: QiecStaticArgument) -> RuntimeConstructor

Quote a source static argument.

PARAMETER DESCRIPTION
universe

The meta universe.

TYPE: MetaUniverse

argument

The argument as written.

TYPE: QiecStaticArgument

RETURNS DESCRIPTION
RuntimeConstructor

The SynStatic value.

Source code in src/quivers/dsl/meta/reflect.py
def syn_static(
    universe: MetaUniverse, argument: QiecStaticArgument
) -> RuntimeConstructor:
    """Quote a source static argument.

    Parameters
    ----------
    universe : MetaUniverse
        The meta universe.
    argument : QiecStaticArgument
        The argument as written.

    Returns
    -------
    RuntimeConstructor
        The ``SynStatic`` value.
    """
    if isinstance(argument, QiecIndexLiteral):
        return universe.make(
            "StaticIndex", (universe.make("IndexLiteral", (argument.value,)),)
        )
    return universe.make("StaticType", (syn_type(universe, argument),))

read_declarations

read_declarations(universe: MetaUniverse, value: object, *, line: int, col: int) -> tuple[Statement | TestDecl, ...]

Read the declarations a meta computation returned.

PARAMETER DESCRIPTION
universe

The meta universe the value was built in.

TYPE: MetaUniverse

value

A SynDecl value or a Seq[SynDecl] value.

TYPE: object

line

The source line the declarations are checked at.

TYPE: int

col

The source column the declarations are checked at.

TYPE: int

RETURNS DESCRIPTION
tuple[Statement | TestDecl, ...]

The source declarations and properties, in order.

RAISES DESCRIPTION
ReflectionError

If the value is not quoted declarations.

Source code in src/quivers/dsl/meta/reflect.py
def read_declarations(
    universe: MetaUniverse, value: object, *, line: int, col: int
) -> tuple[Statement | TestDecl, ...]:
    """Read the declarations a meta computation returned.

    Parameters
    ----------
    universe : MetaUniverse
        The meta universe the value was built in.
    value : object
        A ``SynDecl`` value or a ``Seq[SynDecl]`` value.
    line : int
        The source line the declarations are checked at.
    col : int
        The source column the declarations are checked at.

    Returns
    -------
    tuple[Statement | TestDecl, ...]
        The source declarations and properties, in order.

    Raises
    ------
    ReflectionError
        If the value is not quoted declarations.
    """
    reader = _Reader(universe, line, col)
    try:
        if universe.name_of(value) in ("SeqNil", "SeqCons"):
            return tuple(reader.declaration(item) for item in reader.seq(value))
        return (reader.declaration(value),)
    except MetaValueError as error:
        raise ReflectionError(str(error)) from error

universe

Building and reading the values of the meta-phase universe.

The meta prelude declares the families meta computations exchange with the checker: sequences, quoted syntax, family descriptions, and signature morphisms. A MetaUniverse wraps the checked meta module and builds runtime values of those families from host data, and reads runtime values of them back, so the checker can hand a description to a deriving handler and read the declarations it returns.

SCALAR_TYPES module-attribute

SCALAR_TYPES: Mapping[str, TypeExpr] = {'Bool': BOOL, 'Int': INT, 'Real': REAL, 'String': STRING}

The primitive types meta-phase fields are built from, by name.

MetaField

MetaField = RuntimeConstructor | str | int | float | bool | Tensor

One field of a runtime value of a meta-phase family.

MetaValueError

Bases: ValueError

A runtime value does not have the shape its meta-phase family requires.

MetaUniverse

MetaUniverse(module: QiecModule)

The checked meta module, seen as a universe of buildable values.

PARAMETER DESCRIPTION
module

The checked meta-phase module, which contains the meta prelude.

TYPE: QiecModule

Source code in src/quivers/dsl/meta/universe.py
def __init__(self, module: QiecModule) -> None:
    self.module = module
    self.families: dict[str, FamilyDecl] = {
        family.name: family for family in module.families
    }
    self.constructors: dict[str, ConstructorDecl] = {
        constructor.name: constructor for constructor in module.constructors
    }
    self._names = {
        constructor.id: constructor.name for constructor in module.constructors
    }
    self._families_by_id = {family.id: family for family in module.families}

family_type

family_type(name: str, arguments: tuple[StaticArgument, ...] = ()) -> TypeApplication

The type of a family of the universe at static arguments.

PARAMETER DESCRIPTION
name

The family's name.

TYPE: str

arguments

Its parameters, in order.

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

RETURNS DESCRIPTION
TypeApplication

The applied family type.

RAISES DESCRIPTION
MetaValueError

If the module declares no family of that name.

Source code in src/quivers/dsl/meta/universe.py
def family_type(
    self, name: str, arguments: tuple[StaticArgument, ...] = ()
) -> TypeApplication:
    """The type of a family of the universe at static arguments.

    Parameters
    ----------
    name : str
        The family's name.
    arguments : tuple[StaticArgument, ...]
        Its parameters, in order.

    Returns
    -------
    TypeApplication
        The applied family type.

    Raises
    ------
    MetaValueError
        If the module declares no family of that name.
    """
    family = self.families.get(name)
    if family is None:
        raise MetaValueError(f"the meta module declares no family {name!r}")
    return TypeApplication(constructor=family.type_constructor, arguments=arguments)

seq_type

seq_type(element: TypeExpr) -> TypeApplication

The type Seq[element].

PARAMETER DESCRIPTION
element

The element type.

TYPE: TypeExpr

RETURNS DESCRIPTION
TypeApplication

The sequence type.

Source code in src/quivers/dsl/meta/universe.py
def seq_type(self, element: TypeExpr) -> TypeApplication:
    """The type ``Seq[element]``.

    Parameters
    ----------
    element : TypeExpr
        The element type.

    Returns
    -------
    TypeApplication
        The sequence type.
    """
    return self.family_type("Seq", (element,))

make

make(constructor: str, fields: Sequence[MetaField] = (), static_arguments: tuple[StaticArgument, ...] = ()) -> RuntimeConstructor

Build a runtime value of one constructor.

PARAMETER DESCRIPTION
constructor

The constructor's name.

TYPE: str

fields

Its field values in declaration order. Host strings stay strings; integers, reals, and truth values become the scalar tensors the reference machine computes with.

TYPE: Sequence[MetaField] DEFAULT: ()

static_arguments

The family's parameters, for a constructor of a parameterized family such as SeqCons.

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

RETURNS DESCRIPTION
RuntimeConstructor

The value.

RAISES DESCRIPTION
MetaValueError

If the constructor is unknown or the number of fields or static arguments is wrong.

Source code in src/quivers/dsl/meta/universe.py
def make(
    self,
    constructor: str,
    fields: Sequence[MetaField] = (),
    static_arguments: tuple[StaticArgument, ...] = (),
) -> RuntimeConstructor:
    """Build a runtime value of one constructor.

    Parameters
    ----------
    constructor : str
        The constructor's name.
    fields : Sequence[MetaField]
        Its field values in declaration order. Host strings stay
        strings; integers, reals, and truth values become the scalar
        tensors the reference machine computes with.
    static_arguments : tuple[StaticArgument, ...]
        The family's parameters, for a constructor of a parameterized
        family such as ``SeqCons``.

    Returns
    -------
    RuntimeConstructor
        The value.

    Raises
    ------
    MetaValueError
        If the constructor is unknown or the number of fields or static
        arguments is wrong.
    """
    declaration = self.constructors.get(constructor)
    if declaration is None:
        raise MetaValueError(
            f"the meta module declares no constructor {constructor!r}"
        )
    family = self._families_by_id[declaration.family]
    if len(static_arguments) != len(family.parameters) + len(declaration.telescope):
        raise MetaValueError(
            f"constructor {constructor!r} takes "
            f"{len(family.parameters) + len(declaration.telescope)} static "
            f"arguments, got {len(static_arguments)}"
        )
    if len(fields) != len(declaration.fields):
        raise MetaValueError(
            f"constructor {constructor!r} takes {len(declaration.fields)} "
            f"fields, got {len(fields)}"
        )
    return RuntimeConstructor(
        constructor=declaration.id,
        static_arguments=static_arguments,
        fields=tuple(_runtime_field(value) for value in fields),
        result_type=TypeApplication(
            constructor=family.type_constructor,
            arguments=static_arguments[: len(family.parameters)],
        ),
    )

seq

seq(items: Sequence[MetaField], element: TypeExpr) -> RuntimeConstructor

Build Seq[element] holding the items in order.

PARAMETER DESCRIPTION
items

The elements.

TYPE: Sequence[MetaField]

element

Their type.

TYPE: TypeExpr

RETURNS DESCRIPTION
RuntimeConstructor

The sequence.

Source code in src/quivers/dsl/meta/universe.py
def seq(self, items: Sequence[MetaField], element: TypeExpr) -> RuntimeConstructor:
    """Build ``Seq[element]`` holding the items in order.

    Parameters
    ----------
    items : Sequence[MetaField]
        The elements.
    element : TypeExpr
        Their type.

    Returns
    -------
    RuntimeConstructor
        The sequence.
    """
    result = self.make("SeqNil", (), (element,))
    for item in reversed(items):
        result = self.make("SeqCons", (item, result), (element,))
    return result

strings

strings(items: Sequence[str]) -> RuntimeConstructor

Build Seq[String].

PARAMETER DESCRIPTION
items

The strings.

TYPE: Sequence[str]

RETURNS DESCRIPTION
RuntimeConstructor

The sequence.

Source code in src/quivers/dsl/meta/universe.py
def strings(self, items: Sequence[str]) -> RuntimeConstructor:
    """Build ``Seq[String]``.

    Parameters
    ----------
    items : Sequence[str]
        The strings.

    Returns
    -------
    RuntimeConstructor
        The sequence.
    """
    return self.seq(tuple(items), STRING)

name_of

name_of(value: object) -> str

The constructor a runtime value of the universe was built by.

PARAMETER DESCRIPTION
value

The value.

TYPE: object

RETURNS DESCRIPTION
str

Its constructor's name.

RAISES DESCRIPTION
MetaValueError

If the value is not a constructor value of this module.

Source code in src/quivers/dsl/meta/universe.py
def name_of(self, value: object) -> str:
    """The constructor a runtime value of the universe was built by.

    Parameters
    ----------
    value : object
        The value.

    Returns
    -------
    str
        Its constructor's name.

    Raises
    ------
    MetaValueError
        If the value is not a constructor value of this module.
    """
    if not isinstance(value, RuntimeConstructor):
        raise MetaValueError(f"expected a constructor value, got {value!r}")
    name = self._names.get(value.constructor)
    if name is None:
        raise MetaValueError(
            "a constructor value of another module reached the checker"
        )
    return name

fields_of

fields_of(value: object, expected: str, arity: int) -> tuple[object, ...]

The fields of a value built by an expected constructor.

PARAMETER DESCRIPTION
value

The value.

TYPE: object

expected

The constructor it must have been built by.

TYPE: str

arity

The number of fields that constructor has.

TYPE: int

RETURNS DESCRIPTION
tuple[object, ...]

The fields.

RAISES DESCRIPTION
MetaValueError

If the value was built by another constructor.

Source code in src/quivers/dsl/meta/universe.py
def fields_of(self, value: object, expected: str, arity: int) -> tuple[object, ...]:
    """The fields of a value built by an expected constructor.

    Parameters
    ----------
    value : object
        The value.
    expected : str
        The constructor it must have been built by.
    arity : int
        The number of fields that constructor has.

    Returns
    -------
    tuple[object, ...]
        The fields.

    Raises
    ------
    MetaValueError
        If the value was built by another constructor.
    """
    name = self.name_of(value)
    if name != expected:
        raise MetaValueError(f"expected a {expected} value, got {name}")
    assert isinstance(value, RuntimeConstructor)
    if len(value.fields) != arity:
        raise MetaValueError(
            f"{expected} has {arity} fields, got {len(value.fields)}"
        )
    return value.fields

read_seq

read_seq(value: object) -> tuple[object, ...]

The elements of a Seq value, in order.

PARAMETER DESCRIPTION
value

The sequence.

TYPE: object

RETURNS DESCRIPTION
tuple[object, ...]

Its elements.

RAISES DESCRIPTION
MetaValueError

If the value is not a sequence.

Source code in src/quivers/dsl/meta/universe.py
def read_seq(self, value: object) -> tuple[object, ...]:
    """The elements of a ``Seq`` value, in order.

    Parameters
    ----------
    value : object
        The sequence.

    Returns
    -------
    tuple[object, ...]
        Its elements.

    Raises
    ------
    MetaValueError
        If the value is not a sequence.
    """
    items: list[object] = []
    current = value
    while True:
        name = self.name_of(current)
        if name == "SeqNil":
            return tuple(items)
        head, tail = self.fields_of(current, "SeqCons", 2)
        items.append(head)
        current = tail

read_string

read_string(value: object) -> str

Read a String field.

PARAMETER DESCRIPTION
value

The field.

TYPE: object

RETURNS DESCRIPTION
str

The string.

RAISES DESCRIPTION
MetaValueError

If the field is not a string.

Source code in src/quivers/dsl/meta/universe.py
def read_string(value: object) -> str:
    """Read a ``String`` field.

    Parameters
    ----------
    value : object
        The field.

    Returns
    -------
    str
        The string.

    Raises
    ------
    MetaValueError
        If the field is not a string.
    """
    if not isinstance(value, str):
        raise MetaValueError(f"expected a string, got {value!r}")
    return value

read_int

read_int(value: object) -> int

Read an Int field.

PARAMETER DESCRIPTION
value

The field: an integer tensor of one element, or a host integer.

TYPE: object

RETURNS DESCRIPTION
int

The integer.

RAISES DESCRIPTION
MetaValueError

If the field is not an integer.

Source code in src/quivers/dsl/meta/universe.py
def read_int(value: object) -> int:
    """Read an ``Int`` field.

    Parameters
    ----------
    value : object
        The field: an integer tensor of one element, or a host integer.

    Returns
    -------
    int
        The integer.

    Raises
    ------
    MetaValueError
        If the field is not an integer.
    """
    if isinstance(value, torch.Tensor) and value.numel() == 1:
        if value.dtype.is_floating_point or value.dtype == torch.bool:
            raise MetaValueError(f"expected an integer, got {value!r}")
        return int(value.item())
    if isinstance(value, int) and not isinstance(value, bool):
        return value
    raise MetaValueError(f"expected an integer, got {value!r}")

read_real

read_real(value: object) -> float

Read a Real field.

PARAMETER DESCRIPTION
value

The field: a tensor of one element, or a host number.

TYPE: object

RETURNS DESCRIPTION
float

The number.

RAISES DESCRIPTION
MetaValueError

If the field is not a number.

Source code in src/quivers/dsl/meta/universe.py
def read_real(value: object) -> float:
    """Read a ``Real`` field.

    Parameters
    ----------
    value : object
        The field: a tensor of one element, or a host number.

    Returns
    -------
    float
        The number.

    Raises
    ------
    MetaValueError
        If the field is not a number.
    """
    if isinstance(value, torch.Tensor) and value.numel() == 1:
        return float(value.item())
    if isinstance(value, int | float) and not isinstance(value, bool):
        return float(value)
    raise MetaValueError(f"expected a real number, got {value!r}")

read_bool

read_bool(value: object) -> bool

Read a Bool field.

PARAMETER DESCRIPTION
value

The field: a truth tensor of one element, or a host Boolean.

TYPE: object

RETURNS DESCRIPTION
bool

The truth value.

RAISES DESCRIPTION
MetaValueError

If the field is not a truth value.

Source code in src/quivers/dsl/meta/universe.py
def read_bool(value: object) -> bool:
    """Read a ``Bool`` field.

    Parameters
    ----------
    value : object
        The field: a truth tensor of one element, or a host Boolean.

    Returns
    -------
    bool
        The truth value.

    Raises
    ------
    MetaValueError
        If the field is not a truth value.
    """
    if (
        isinstance(value, torch.Tensor)
        and value.numel() == 1
        and value.dtype == torch.bool
    ):
        return bool(value.item())
    if isinstance(value, bool):
        return value
    raise MetaValueError(f"expected a truth value, got {value!r}")

library

The meta-phase library: the prelude and the built-in deriving handlers.

Both are ordinary QVR source shipped with quivers. Their declarations are in scope in the meta phase of every module, so a module's own declarations may not reuse their names there.

LIBRARY_DIRECTORY module-attribute

LIBRARY_DIRECTORY = Path(__file__).resolve().parent

The directory the library's source files live in.

LIBRARY_FILES module-attribute

LIBRARY_FILES: tuple[str, ...] = ('prelude.qvr', 'deriving.qvr', 'ornaments.qvr')

The library sources, in the order their declarations enter the meta phase.

MetaLibrary didactic-model

MetaLibrary(*, statements: tuple[Statement, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), names: frozenset[str] = field(opaque=True, extras=OPAQUE_BY_VALUE), computations: frozenset[str] = field(opaque=True, extras=OPAQUE_BY_VALUE), digest: str)

Bases: ValueModel

The parsed meta-phase library.

PARAMETER DESCRIPTION
statements

Every library declaration, in file order.

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

names

Every name the library declares in any namespace: families, constructors, computations, effect instances, and handlers.

TYPE: frozenset[str] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

computations

The names of the library's computations.

TYPE: frozenset[str] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

digest

The content-hash-domain digest, of kind meta-library, of the library's source files, which enters the provenance of every declaration the meta phase generates.

TYPE: str

declared_names

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

The names a declaration introduces in any namespace.

PARAMETER DESCRIPTION
statement

The declaration.

TYPE: Statement

RETURNS DESCRIPTION
tuple[str, ...]

A family's name and its constructors' names, an index sort's name and its constructors' names, or the name of a computation, effect instance, handler, or pattern synonym. Other statements contribute no names.

Source code in src/quivers/dsl/meta/library.py
def declared_names(statement: Statement) -> tuple[str, ...]:
    """The names a declaration introduces in any namespace.

    Parameters
    ----------
    statement : Statement
        The declaration.

    Returns
    -------
    tuple[str, ...]
        A family's name and its constructors' names, an index sort's name and
        its constructors' names, or the name of a computation, effect
        instance, handler, or pattern synonym. Other statements contribute
        no names.
    """
    if isinstance(statement, QiecFamilyDecl):
        return (statement.name, *(c.name for c in statement.constructors))
    if isinstance(statement, QiecIndexDecl):
        return (statement.name, *(c.name for c in statement.constructors))
    if isinstance(
        statement,
        QiecComputationDecl
        | QiecEffectInstanceDecl
        | QiecHandlerDecl
        | QiecPatternSynonymDecl,
    ):
        return (statement.name,)
    return ()

meta_library cached

meta_library() -> MetaLibrary

Parse the meta-phase library once per process.

RETURNS DESCRIPTION
MetaLibrary

The library's declarations, names, and digest.

Source code in src/quivers/dsl/meta/library.py
@cache
def meta_library() -> MetaLibrary:
    """Parse the meta-phase library once per process.

    Returns
    -------
    MetaLibrary
        The library's declarations, names, and digest.
    """
    statements: list[Statement] = []
    sources: dict[str, CoreJson] = {}
    for name in LIBRARY_FILES:
        path = LIBRARY_DIRECTORY / name
        source = path.read_bytes()
        sources[name] = source.decode("utf-8")
        module: Module = parse(source, file_path=str(path))
        statements.extend(module.statements)
    names = frozenset(
        name for statement in statements for name in declared_names(statement)
    )
    computations = frozenset(
        statement.name
        for statement in statements
        if isinstance(statement, QiecComputationDecl)
    )
    return MetaLibrary(
        statements=tuple(statements),
        names=names,
        computations=computations,
        digest=tagged_digest("meta-library", sources),
    )