Skip to content

Signature families

Each object sort of a syntax declaration is an ordinary checked family of the module. This module derives those families and their constructors from a signature and converts between host Term values and family values.

families

The QIEC families of a binding signature and the codec of their values.

Each object sort S of a signature Sig is one closed QIEC family, named Sig.S (quivers.qiec.names.member_name). Its constructors are the signature's constructors into S, under their own names, with one field per argument in source order: an object argument is a field of its sort's family, a data argument a field of the data sort's value type, and an index argument an Int. An argument that binds variables is the body in the extended scope, a de Bruijn term like any other. Every sort some argument binds has a variable constructor Sig.S.var(index : Int), the BoundVar(index) of quivers.structural.signature.

The families are the one family notion of a signature: computations, case analysis, deductions, encoders, decoders, and decoder laws all use them. At the host boundary a value of Sig.S is a structural Term, so SignatureFamilies.value and SignatureFamilies.term convert between the two; the conversion is the identity on the tree, so it costs the term's size.

VARIABLE_MEMBER module-attribute

VARIABLE_MEMBER = 'var'

The member name of a sort's variable constructor.

SIGNATURE_PROTOCOL module-attribute

SIGNATURE_PROTOCOL = 'quivers-signature'

The source protocol of the standalone module of a signature's families.

SignatureFamilyError

Bases: ValueError

A signature has no QIEC families, or a value does not fit them.

SignatureFamilies didactic-model

SignatureFamilies(*, signature: Signature = field(opaque=True, extras=OPAQUE_BY_VALUE), module: str)

Bases: ValueModel

The closed QIEC families of one term signature in one module.

PARAMETER DESCRIPTION
signature

The signature; it must be first-order or binding, not graph shaped.

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

module

The name of the module that declares the families, which their identities derive from.

TYPE: str

families cached property

families: Mapping[str, FamilyDecl]

The family of every object sort, keyed by sort.

RETURNS DESCRIPTION
Mapping of str to FamilyDecl

The families, in sort order.

constructors cached property

constructors: Mapping[str, ConstructorDecl]

Every constructor, keyed by its name in the families.

RETURNS DESCRIPTION
Mapping of str to ConstructorDecl

The signature's constructors under their own names, then the variable constructors under Sig.S.var.

bindings cached property

bindings: Mapping[ConstructorId, tuple[tuple[ConstructorId, ...], ...]]

For each binding constructor, the variables each field binds.

RETURNS DESCRIPTION
Mapping

Per field, the variable constructor of each bound variable's sort, outermost first; an empty tuple for an unbound field.

registry cached property

registry: KernelRegistry

The checked registry of the families.

RETURNS DESCRIPTION
KernelRegistry

The registry values of the families are checked against.

type_of

type_of(sort: str) -> TypeApplication

The QIEC type of a sort.

PARAMETER DESCRIPTION
sort

An object sort.

TYPE: str

RETURNS DESCRIPTION
TypeApplication

Its family, applied to nothing.

RAISES DESCRIPTION
SignatureFamilyError

If the sort is not an object sort.

Source code in src/quivers/structural/families.py
def type_of(self, sort: str) -> TypeApplication:
    """The QIEC type of a sort.

    Parameters
    ----------
    sort : str
        An object sort.

    Returns
    -------
    TypeApplication
        Its family, applied to nothing.

    Raises
    ------
    SignatureFamilyError
        If the sort is not an object sort.
    """
    family = self.families.get(sort)
    if family is None:
        raise SignatureFamilyError(
            f"sort {sort!r} of signature {self.signature.name!r} is not an "
            "object sort"
        )
    return TypeApplication(constructor=family.type_constructor)

to_module

to_module() -> QiecModule

The families as a standalone checked module.

RETURNS DESCRIPTION
QiecModule

The families and constructors, nothing else.

Source code in src/quivers/structural/families.py
def to_module(self) -> QiecModule:
    """The families as a standalone checked module.

    Returns
    -------
    QiecModule
        The families and constructors, nothing else.
    """
    return QiecModule(
        module=self.module,
        source_protocol=SIGNATURE_PROTOCOL,
        families=tuple(self.families.values()),
        constructors=tuple(self.constructors.values()),
    )

syntax

syntax(term: Term, sort: str) -> ConstructorValue

The QIEC constructor value of a structural term.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

sort

Its sort.

TYPE: str

RETURNS DESCRIPTION
ConstructorValue

The same tree over the families.

RAISES DESCRIPTION
SignatureFamilyError

If the term does not fit the signature.

Source code in src/quivers/structural/families.py
def syntax(self, term: Term, sort: str) -> ConstructorValue:
    """The QIEC constructor value of a structural term.

    Parameters
    ----------
    term : Term
        The term.
    sort : str
        Its sort.

    Returns
    -------
    ConstructorValue
        The same tree over the families.

    Raises
    ------
    SignatureFamilyError
        If the term does not fit the signature.
    """
    if term.op == BOUND_VAR:
        index = term.args[0]
        if sort not in self.signature.variable_sorts:
            raise SignatureFamilyError(
                f"sort {sort!r} has no variables, but the term is a variable"
            )
        declared = self.constructors[variable_name(self.signature.name, sort)]
        return ConstructorValue(
            constructor=declared.id,
            static_arguments=(),
            fields=(LiteralValue(value=index, type=INT),),
            result_type=self.type_of(sort),
        )
    constructor = self.signature.constructors.get(term.op)
    if constructor is None or constructor.codomain != sort:
        raise SignatureFamilyError(
            f"{term.op!r} is not a constructor of sort {sort!r} in signature "
            f"{self.signature.name!r}"
        )
    if len(term.args) != constructor.arity:
        raise SignatureFamilyError(
            f"{term.op!r} takes {constructor.arity} arguments, got {len(term.args)}"
        )
    fields: list[Value] = []
    for argument, argument_sort in zip(term.args, constructor.domain, strict=True):
        fields.append(self._field_syntax(argument, argument_sort))
    return ConstructorValue(
        constructor=self.constructors[term.op].id,
        static_arguments=(),
        fields=tuple(fields),
        result_type=self.type_of(sort),
    )

value

value(term: Term, sort: str) -> RuntimeConstructor

The runtime value of a structural term, as the machine holds it.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

sort

Its sort.

TYPE: str

RETURNS DESCRIPTION
RuntimeConstructor

The evaluated constructor tree.

Source code in src/quivers/structural/families.py
def value(self, term: Term, sort: str) -> RuntimeConstructor:
    """The runtime value of a structural term, as the machine holds it.

    Parameters
    ----------
    term : Term
        The term.
    sort : str
        Its sort.

    Returns
    -------
    RuntimeConstructor
        The evaluated constructor tree.
    """
    result = Evaluator().evaluate(Return(value=self.syntax(term, sort)))
    assert isinstance(result, RuntimeConstructor)
    return result

term

term(value: RuntimeConstructor, sort: str | None = None) -> Term

The structural term of a runtime value, checked against the families.

PARAMETER DESCRIPTION
value

A value of one of the families.

TYPE: RuntimeConstructor

sort

The sort the value must have; its own type's sort when omitted.

TYPE: str or None DEFAULT: None

RETURNS DESCRIPTION
Term

The same tree.

RAISES DESCRIPTION
SignatureFamilyError

If a constructor does not belong to the families, a node has another sort than its position requires, or a field has the wrong kind of value.

Source code in src/quivers/structural/families.py
def term(self, value: RuntimeConstructor, sort: str | None = None) -> Term:
    """The structural term of a runtime value, checked against the families.

    Parameters
    ----------
    value : RuntimeConstructor
        A value of one of the families.
    sort : str or None
        The sort the value must have; its own type's sort when omitted.

    Returns
    -------
    Term
        The same tree.

    Raises
    ------
    SignatureFamilyError
        If a constructor does not belong to the families, a node has
        another sort than its position requires, or a field has the
        wrong kind of value.
    """
    if sort is None:
        found = self.sort_of_type(value.result_type)
        if found is None:
            raise SignatureFamilyError(
                f"a value is not of a family of signature {self.signature.name!r}"
            )
        sort = found
    if value.constructor in self._variable_ids:
        if self._variable_ids[value.constructor] != sort:
            raise SignatureFamilyError(
                f"a variable of sort {self._variable_ids[value.constructor]!r} "
                f"stands where sort {sort!r} is required"
            )
        (index,) = value.fields
        return Term(op=BOUND_VAR, args=(host_index(index, "a variable's index"),))
    declared = self._by_id.get(value.constructor)
    if declared is None:
        raise SignatureFamilyError(
            f"a value's constructor is not one of signature "
            f"{self.signature.name!r}'s"
        )
    constructor = self.signature.constructor(declared.name)
    if constructor.codomain != sort:
        raise SignatureFamilyError(
            f"constructor {declared.name!r} of sort {constructor.codomain!r} "
            f"stands where sort {sort!r} is required"
        )
    if len(value.fields) != constructor.arity:
        raise SignatureFamilyError(
            f"constructor {declared.name!r} has {len(value.fields)} fields, "
            f"declared {constructor.arity}"
        )
    arguments: list[TermArg] = []
    for field, field_sort in zip(value.fields, constructor.domain, strict=True):
        kind = self.signature.sorts[field_sort].kind
        if kind == "object":
            if not isinstance(field, RuntimeConstructor):
                raise SignatureFamilyError(
                    f"a field of sort {field_sort!r} is not a term"
                )
            arguments.append(self.term(field, field_sort))
            continue
        value_type = _data_type(self.signature, field_sort)
        if value_type == STRING:
            if not isinstance(field, str):
                raise SignatureFamilyError(
                    f"a field of sort {field_sort!r} is not a string"
                )
            arguments.append(field)
        elif value_type == INT:
            if isinstance(field, RuntimeConstructor):
                raise SignatureFamilyError(
                    f"a field of sort {field_sort!r} is not an integer"
                )
            arguments.append(host_index(field, f"a field of sort {field_sort!r}"))
        elif isinstance(field, torch.Tensor):
            arguments.append(host_real(field, f"a field of sort {field_sort!r}"))
        elif isinstance(field, float | int | str) and not isinstance(field, bool):
            arguments.append(field)
        else:
            raise SignatureFamilyError(
                f"a field of sort {field_sort!r} holds {type(field).__name__}"
            )
    return Term(op=declared.name, args=tuple(arguments))

sort_of_type

sort_of_type(type_: TypeExpr) -> str | None

The sort whose family a type is, if any.

PARAMETER DESCRIPTION
type_

A type.

TYPE: TypeExpr

RETURNS DESCRIPTION
str or None

The sort, or None when the type is not one of the families.

Source code in src/quivers/structural/families.py
def sort_of_type(self, type_: TypeExpr) -> str | None:
    """The sort whose family a type is, if any.

    Parameters
    ----------
    type_ : TypeExpr
        A type.

    Returns
    -------
    str or None
        The sort, or ``None`` when the type is not one of the families.
    """
    for sort, family in self.families.items():
        if type_ == TypeApplication(constructor=family.type_constructor):
            return sort
    return None

family_name

family_name(signature: str, sort: str) -> str

The QIEC family name of a signature's sort.

PARAMETER DESCRIPTION
signature

The signature's name.

TYPE: str

sort

The object sort.

TYPE: str

RETURNS DESCRIPTION
str

signature.sort.

Source code in src/quivers/structural/families.py
def family_name(signature: str, sort: str) -> str:
    """The QIEC family name of a signature's sort.

    Parameters
    ----------
    signature : str
        The signature's name.
    sort : str
        The object sort.

    Returns
    -------
    str
        ``signature.sort``.
    """
    return member_name(signature, sort)

variable_name

variable_name(signature: str, sort: str) -> str

The variable constructor name of a signature's sort.

PARAMETER DESCRIPTION
signature

The signature's name.

TYPE: str

sort

The sort.

TYPE: str

RETURNS DESCRIPTION
str

signature.sort.var.

Source code in src/quivers/structural/families.py
def variable_name(signature: str, sort: str) -> str:
    """The variable constructor name of a signature's sort.

    Parameters
    ----------
    signature : str
        The signature's name.
    sort : str
        The sort.

    Returns
    -------
    str
        ``signature.sort.var``.
    """
    return member_name(signature, sort, VARIABLE_MEMBER)

signature_families cached

signature_families(signature: Signature, module: str) -> SignatureFamilies

The families of a signature in a module, built once.

PARAMETER DESCRIPTION
signature

The signature.

TYPE: Signature

module

The declaring module's name.

TYPE: str

RETURNS DESCRIPTION
SignatureFamilies

The families.

Source code in src/quivers/structural/families.py
@lru_cache(maxsize=256)
def signature_families(signature: Signature, module: str) -> SignatureFamilies:
    """The families of a signature in a module, built once.

    Parameters
    ----------
    signature : Signature
        The signature.
    module : str
        The declaring module's name.

    Returns
    -------
    SignatureFamilies
        The families.
    """
    return SignatureFamilies(signature=signature, module=module)