Skip to content

Theories

The theory layer of a module: theory, view, and model declarations elaborated over panproto's theory engine through quivers.gat. TheoryLayer is what the compiler builds and what Program.theory_layer holds. The theories reference describes the surface, and the semantics states the constructions and guarantees.

theories

Theories, views, and models of QVR modules, elaborated over panproto.

A theory is a presentation: sorts, operations, equations, and rules, and the theories it includes. A view is a theory morphism whose domain's equations become obligations in its codomain. A model is a finite set-theoretic model, interpreted by QIEC types and computations or constructed along a view. Every composition is a colimit computed by panproto's theory engine through quivers.gat, over shared theories identified by origin and never by name; see the theories page of the semantics documentation.

TheoryLayer is what the compiler builds for a module and what Program.theory_layer exposes.

MAX_ASSIGNMENTS module-attribute

MAX_ASSIGNMENTS = 1000000

The most variable assignments a law is checked at in one model.

MAX_ELEMENTS module-attribute

MAX_ELEMENTS = 10000

The most elements a free extension may build.

MODEL_FUEL module-attribute

MODEL_FUEL = 100000

The machine steps one operation of a model may take on one argument tuple.

MAX_SEARCHED_MODELS module-attribute

MAX_SEARCHED_MODELS = 10000

The most complete models of the included theory one search examines.

HostValue

HostValue = bool | tuple[HostValue, ...] | RuntimeConstructor

A value of a finite type as the reference machine holds it.

ResultValue

ResultValue = Tensor | bool | int | str | RuntimeConstructor | tuple[ResultValue, ...]

A value the reference machine returns from a model's operation.

TheoryStatement

TheoryStatement = TheoryDecl | ViewDecl | ModelDecl

A declaration of the theory layer.

Classification

Classification = Literal['definitional', 'conservative', 'neither', 'undetermined']

What an extension of a theory is known to be.

LawStatus

LawStatus = Literal['established', 'assumed']

How a law is known to hold: proved by the checker, or assumed.

A law that is assumed may still be checked in finite models; the models it was checked in are recorded beside its status.

MemberKind

MemberKind = Literal['sort', 'op', 'eq', 'rule']

The kinds of symbol and law a presentation has.

CarrierError

Bases: ValueError

A type whose values the checker cannot list, with the reason.

Verdict didactic-model

Verdict(*, classification: Classification, reason: str, witness: ExtensionWitness | None = None, search: SearchResult | None = None)

Bases: Model

The classification of one inclusion and the argument for it.

PARAMETER DESCRIPTION
classification

What the checker established.

TYPE: Classification

reason

Why.

TYPE: str

witness

The model with no expansion, for "neither".

TYPE: ExtensionWitness or None DEFAULT: None

search

The bounded model search, when the inclusion asked for one and the classification was not settled without it.

TYPE: SearchResult or None DEFAULT: None

TheoryLayer

TheoryLayer()

The theories, views, and models of a module and what is known of them.

ATTRIBUTE DESCRIPTION
theories

Every theory by origin: the declared ones by name, and every theory expression by its text.

TYPE: dict of str to TheoryValue

views

Every view by name.

TYPE: dict of str to CheckedView

models

Every model by name.

TYPE: dict of str to CheckedModel

extensions

The classification of every inclusion and hiding.

TYPE: list of ExtensionRecord

Source code in src/quivers/dsl/theories/layer.py
def __init__(self) -> None:
    self.theories: dict[str, TheoryValue] = {}
    self.views: dict[str, CheckedView] = {}
    self.models: dict[str, CheckedModel] = {}
    self.extensions: list[ExtensionRecord] = []
    self._statements: list[TheoryStatement] = []
    self._declared: dict[str, tuple[str, int]] = {}
    self._inclusions: list[_Inclusion] = []
    self._assumptions: dict[str, dict[str, tuple[int, int]]] = {}
    self._checked = False

declarations property

declarations: tuple[TheoryStatement, ...]

The queued declarations, in source order.

RETURNS DESCRIPTION
tuple

The declarations.

add

add(statement: TheoryStatement) -> None

Queue a declaration, in source order.

PARAMETER DESCRIPTION
statement

The declaration.

TYPE: TheoryDecl or ViewDecl or ModelDecl

Source code in src/quivers/dsl/theories/layer.py
def add(self, statement: TheoryStatement) -> None:
    """Queue a declaration, in source order.

    Parameters
    ----------
    statement : TheoryDecl or ViewDecl or ModelDecl
        The declaration.
    """
    self._statements.append(statement)

theory

theory(name: str) -> TheoryValue

A declared theory.

PARAMETER DESCRIPTION
name

Its name.

TYPE: str

RETURNS DESCRIPTION
TheoryValue

The theory.

RAISES DESCRIPTION
KeyError

If no theory of that name is declared.

Source code in src/quivers/dsl/theories/layer.py
def theory(self, name: str) -> TheoryValue:
    """A declared theory.

    Parameters
    ----------
    name : str
        Its name.

    Returns
    -------
    TheoryValue
        The theory.

    Raises
    ------
    KeyError
        If no theory of that name is declared.
    """
    return self.theories[name]

add_theory

add_theory(value: TheoryValue) -> TheoryValue

Record a theory built outside a theory declaration.

A module signature that carries equations is a theory (quivers.dsl.theories.instances.signature_theory); recording it here lets views and models refer to it by its origin.

PARAMETER DESCRIPTION
value

The theory.

TYPE: TheoryValue

RETURNS DESCRIPTION
TheoryValue

The theory.

RAISES DESCRIPTION
TheoryError

If a theory, view, or model of the same name is declared.

Source code in src/quivers/dsl/theories/layer.py
def add_theory(self, value: TheoryValue) -> TheoryValue:
    """Record a theory built outside a ``theory`` declaration.

    A module signature that carries equations is a theory
    (`quivers.dsl.theories.instances.signature_theory`); recording it
    here lets views and models refer to it by its origin.

    Parameters
    ----------
    value : TheoryValue
        The theory.

    Returns
    -------
    TheoryValue
        The theory.

    Raises
    ------
    TheoryError
        If a theory, view, or model of the same name is declared.
    """
    earlier = self._declared.get(value.name)
    if earlier is not None:
        kind, line = earlier
        raise TheoryError(
            f"{value.name!r} is already declared as a {kind} at line {line}",
            value.line,
            value.col,
        )
    self._declared[value.name] = ("theory", value.line)
    return self._register(value)

check_view

check_view(decl: ViewDecl) -> CheckedView

Elaborate one view and settle its obligations with the known models.

PARAMETER DESCRIPTION
decl

The view.

TYPE: ViewDecl

RETURNS DESCRIPTION
CheckedView

The view, each obligation established or assumed.

RAISES DESCRIPTION
TheoryError

If the view is refused, an obligation is refuted by a model of its codomain, or an obligation is neither established nor assumed.

Source code in src/quivers/dsl/theories/layer.py
def check_view(self, decl: ViewDecl) -> CheckedView:
    """Elaborate one view and settle its obligations with the known models.

    Parameters
    ----------
    decl : ViewDecl
        The view.

    Returns
    -------
    CheckedView
        The view, each obligation established or assumed.

    Raises
    ------
    TheoryError
        If the view is refused, an obligation is refuted by a model of
        its codomain, or an obligation is neither established nor
        assumed.
    """
    self._claim(decl)
    self._view(decl)
    view = self._settle(self.views[decl.name])
    self.views[decl.name] = view
    return view

check

check(module: QiecModule | None) -> None

Elaborate and check every queued declaration.

PARAMETER DESCRIPTION
module

The module's checked QIEC core, whose types and computations interpret models, or None when it has none.

TYPE: QiecModule or None

RAISES DESCRIPTION
TheoryError

At the first declaration, view obligation, or inclusion the checker refuses.

Source code in src/quivers/dsl/theories/layer.py
def check(self, module: QiecModule | None) -> None:
    """Elaborate and check every queued declaration.

    Parameters
    ----------
    module : QiecModule or None
        The module's checked QIEC core, whose types and computations
        interpret models, or ``None`` when it has none.

    Raises
    ------
    TheoryError
        At the first declaration, view obligation, or inclusion the
        checker refuses.
    """
    if self._checked:
        return
    for statement in self._statements:
        self._claim(statement)
        if isinstance(statement, TheoryDecl):
            self._theory(statement)
        elif isinstance(statement, ViewDecl):
            self._view(statement)
        else:
            self._model(statement, module)
    for view in list(self.views.values()):
        self.views[view.name] = self._settle(view)
    for inclusion in self._inclusions:
        self.extensions.append(self._classify(inclusion))
    self._checked = True

models_of

models_of(origin: str) -> tuple[CheckedModel, ...]

The checked models of one theory.

PARAMETER DESCRIPTION
origin

The theory.

TYPE: str

RETURNS DESCRIPTION
tuple of CheckedModel

Its models, in declaration order.

Source code in src/quivers/dsl/theories/layer.py
def models_of(self, origin: str) -> tuple[CheckedModel, ...]:
    """The checked models of one theory.

    Parameters
    ----------
    origin : str
        The theory.

    Returns
    -------
    tuple of CheckedModel
        Its models, in declaration order.
    """
    return tuple(m for m in self.models.values() if m.theory == origin)

LocalLaw didactic-model

LocalLaw(*, local: str, sides: str, oriented: bool = False, line: int = 0, col: int = 0)

Bases: Model

A checked equation or rule a theory declares itself.

PARAMETER DESCRIPTION
local

Its name as declared.

TYPE: str

sides

Its two sides, as panproto serializes terms, in one JSON list.

TYPE: str

oriented

Whether it is a rule lhs ~> rhs.

TYPE: bool DEFAULT: False

line

Where it is declared.

TYPE: int DEFAULT: 0

col

Where it is declared.

TYPE: int DEFAULT: 0

lhs property

lhs: Json

The left side.

RETURNS DESCRIPTION
Json

The serialized term.

rhs property

rhs: Json

The right side.

RETURNS DESCRIPTION
Json

The serialized term.

LocalOperation didactic-model

LocalOperation(*, name: str, serialized: str, line: int = 0, col: int = 0)

Bases: Model

An operation a theory declares itself.

PARAMETER DESCRIPTION
name

The operation.

TYPE: str

serialized

The operation in panproto's serialized shape: its inputs, each with a name, a sort expression, and whether it is implicit, and its output sort expression.

TYPE: str

line

Where it is declared.

TYPE: int DEFAULT: 0

col

Where it is declared.

TYPE: int DEFAULT: 0

entry property

entry: Json

The declaration in panproto's serialized shape.

RETURNS DESCRIPTION
Json

The parsed serialized text.

LocalPart didactic-model

LocalPart(*, sorts: tuple[LocalSort, ...] = (), operations: tuple[LocalOperation, ...] = (), laws: tuple[LocalLaw, ...] = (), assume_terminating: bool = False)

Bases: Model

The declarations of a theory that are not included from another.

PARAMETER DESCRIPTION
sorts

Its sorts.

TYPE: tuple of LocalSort DEFAULT: ()

operations

Its operations.

TYPE: tuple of LocalOperation DEFAULT: ()

laws

Its equations and rules.

TYPE: tuple of LocalLaw DEFAULT: ()

assume_terminating

Whether termination of the rules it can reach is assumed.

TYPE: bool DEFAULT: False

is_empty

is_empty() -> bool

Whether it declares nothing.

RETURNS DESCRIPTION
bool

Whether there are no sorts, operations, or laws.

Source code in src/quivers/dsl/theories/presentation.py
def is_empty(self) -> bool:
    """Whether it declares nothing.

    Returns
    -------
    bool
        Whether there are no sorts, operations, or laws.
    """
    return not (self.sorts or self.operations or self.laws)

LocalSort didactic-model

LocalSort(*, name: str, serialized: str, line: int = 0, col: int = 0)

Bases: Model

A sort a theory declares itself.

PARAMETER DESCRIPTION
name

The sort.

TYPE: str

serialized

The sort in panproto's serialized shape, with its parameters.

TYPE: str

line

Where it is declared.

TYPE: int DEFAULT: 0

col

Where it is declared.

TYPE: int DEFAULT: 0

entry property

entry: Json

The declaration in panproto's serialized shape.

RETURNS DESCRIPTION
Json

The parsed serialized text.

SearchResult didactic-model

SearchResult(*, bound: int, models: int = 0, exhausted: bool = True, witness: ExtensionWitness | None = None)

Bases: Model

What a bounded search found.

PARAMETER DESCRIPTION
bound

The most elements a carrier had.

TYPE: int

models

The models of the included theory examined.

TYPE: int DEFAULT: 0

exhausted

Whether every model within the bound was examined, rather than the search stopping at MAX_SEARCHED_MODELS.

TYPE: bool DEFAULT: True

witness

A model with no expansion, if one was found.

TYPE: ExtensionWitness or None DEFAULT: None

CheckedModel didactic-model

CheckedModel(*, name: str, theory: str, model: FiniteModel, interpretations: tuple[SymbolInterpretation, ...] = (), construction: Literal['', 'reduct', 'free'] = '', source: str = '', view: str = '', unit: tuple[UnitPair, ...] = (), line: int = 0, col: int = 0)

Bases: Model

A finite model of a theory, checked against its laws.

PARAMETER DESCRIPTION
name

The model's name.

TYPE: str

theory

The origin of the theory it is a model of.

TYPE: str

model

Its carriers and operation tables.

TYPE: FiniteModel

interpretations

The QIEC type of each sort and computation of each operation, for a model given by them.

TYPE: tuple of SymbolInterpretation DEFAULT: ()

construction

"" for a model given by interpretations, "reduct" or "free" for a constructed one.

TYPE: str DEFAULT: ''

source

The model a constructed model starts from.

TYPE: str DEFAULT: ''

view

The view it is constructed along.

TYPE: str DEFAULT: ''

unit

The unit of a free extension.

TYPE: tuple of UnitPair DEFAULT: ()

line

Where it is declared.

TYPE: int DEFAULT: 0

col

Where it is declared.

TYPE: int DEFAULT: 0

CheckedView didactic-model

CheckedView(*, name: str, domain: str, codomain: str, morphism: MorphismRecord, obligations: tuple[ObligationRecord, ...] = (), line: int = 0, col: int = 0)

Bases: Model

A theory morphism and the status of every obligation it incurs.

PARAMETER DESCRIPTION
name

The view's name.

TYPE: str

domain

The origin of its domain.

TYPE: str

codomain

The origin of its codomain.

TYPE: str

morphism

The morphism panproto checked.

TYPE: MorphismRecord

obligations

One per equation of the domain, in declaration order.

TYPE: tuple of ObligationRecord DEFAULT: ()

line

Where it is declared.

TYPE: int DEFAULT: 0

col

Where it is declared.

TYPE: int DEFAULT: 0

ExtensionRecord didactic-model

ExtensionRecord(*, theory: str, included: str, classification: Classification, declared: Classification | None = None, status: LawStatus = 'established', reason: str = '', witness: ExtensionWitness | None = None, search_bound: int | None = None, searched_models: int = 0, line: int = 0, col: int = 0)

Bases: Model

The classification of one inclusion of a theory into another.

PARAMETER DESCRIPTION
theory

The extension.

TYPE: str

included

The included theory.

TYPE: str

classification

What the checker found: "definitional" (every model of the included theory has exactly one expansion), "conservative" (every model has one), "neither" (some model has none), or "undetermined".

TYPE: Classification

declared

The classification the declaration states, if any.

TYPE: Classification or None DEFAULT: None

status

"established" for a classification the checker proved or refuted, "assumed" for a declared one it records unproved.

TYPE: LawStatus DEFAULT: 'established'

reason

The argument for the classification.

TYPE: str DEFAULT: ''

witness

The model with no expansion, for "neither".

TYPE: ExtensionWitness or None DEFAULT: None

search_bound

The most elements per sort the model search tried, when the inclusion asked for one; an "undetermined" classification then holds within this bound only.

TYPE: int or None DEFAULT: None

searched_models

The models of the included theory the search examined.

TYPE: int DEFAULT: 0

line

Where the inclusion is written.

TYPE: int DEFAULT: 0

col

Where the inclusion is written.

TYPE: int DEFAULT: 0

ExtensionWitness didactic-model

ExtensionWitness(*, model: str, sort: str, left: str, right: str)

Bases: Model

A model of the included theory with no expansion to the extension.

PARAMETER DESCRIPTION
model

The model.

TYPE: str

sort

A sort of the included theory.

TYPE: str

left

Two distinct elements of the sort the extension identifies.

TYPE: str

right

Two distinct elements of the sort the extension identifies.

TYPE: str

Member didactic-model

Member(*, kind: MemberKind, name: str, origin: str, local: str, line: int = 0, col: int = 0)

Bases: Model

A sort, operation, equation, or rule of a presentation and its origin.

PARAMETER DESCRIPTION
kind

What it is.

TYPE: MemberKind

name

Its name in the flat theory. A sort or operation keeps the name it was declared with; a law is qualified by its origin, as Monoid.assoc.

TYPE: str

origin

The theory that declares it.

TYPE: str

local

Its name as declared.

TYPE: str

line

Where it is declared.

TYPE: int DEFAULT: 0

col

Where it is declared.

TYPE: int DEFAULT: 0

ObligationRecord didactic-model

ObligationRecord(*, equation: Member, lhs: str, rhs: str, image_lhs: str, image_rhs: str, status: LawStatus, witness: Witness | None = None, reason: str = '', checked_in: tuple[str, ...] = ())

Bases: Model

One equation of a view's domain and what is known of its image.

PARAMETER DESCRIPTION
equation

The equation in the domain.

TYPE: Member

lhs

Its two sides.

TYPE: str

rhs

Its two sides.

TYPE: str

image_lhs

Their images in the codomain.

TYPE: str

image_rhs

Their images in the codomain.

TYPE: str

status

"established" when panproto derives the image from the codomain's laws, "assumed" when the view assumes it.

TYPE: LawStatus

witness

The derivation, for an established obligation.

TYPE: Witness or None DEFAULT: None

reason

Why the checker did not establish it, for an assumed obligation.

TYPE: str DEFAULT: ''

checked_in

The models of the codomain the image was checked in.

TYPE: tuple of str DEFAULT: ()

RuleCheck didactic-model

RuleCheck(*, termination: LawStatus = 'established', confluence: LawStatus = 'established')

Bases: Model

What the checker found about a theory's rules.

PARAMETER DESCRIPTION
termination

"established" when panproto's lexicographic path ordering orients every rule, "assumed" when the theory assumes it.

TYPE: LawStatus DEFAULT: 'established'

confluence

"established" when every critical pair joins.

TYPE: LawStatus DEFAULT: 'established'

SymbolInterpretation didactic-model

SymbolInterpretation(*, symbol: str, value: str)

Bases: Model

What interprets one sort or operation in a model.

PARAMETER DESCRIPTION
symbol

The sort or operation.

TYPE: str

value

The QIEC type or computation that interprets it.

TYPE: str

TheoryError

TheoryError(message: str, line: int, col: int)

Bases: ValueError

A theory, view, or model declaration the checker refuses.

PARAMETER DESCRIPTION
message

What is wrong, naming the symbols, laws, and theories involved.

TYPE: str

line

The source position of the offending declaration or entry.

TYPE: int

col

The source position of the offending declaration or entry.

TYPE: int

Source code in src/quivers/dsl/theories/values.py
def __init__(self, message: str, line: int, col: int) -> None:
    super().__init__(message)
    self.message = message
    self.line = line
    self.col = col

TheoryParameter didactic-model

TheoryParameter(*, name: str, theory: str)

Bases: Model

A parameter of a generic theory.

PARAMETER DESCRIPTION
name

The parameter's name.

TYPE: str

theory

The origin of the theory it ranges over.

TYPE: str

TheoryValue didactic-model

TheoryValue(*, name: str, theory: Theory = field(opaque=True, extras=OPAQUE_BY_IDENTITY), own: Theory = field(opaque=True, extras=OPAQUE_BY_IDENTITY), signature: Theory = field(opaque=True, extras=OPAQUE_BY_IDENTITY), members: tuple[Member, ...] = (), includes: tuple[str, ...] = (), closure: tuple[str, ...] = (), parameters: tuple[TheoryParameter, ...] = (), composition: ComposedTheory | None = None, rules: RuleCheck = field(default_factory=RuleCheck), line: int = 0, col: int = 0)

Bases: ValueModel

A presentation with its identity of origin.

PARAMETER DESCRIPTION
name

The origin: the declaration's name, or the text of the theory expression that built it. Two values with one origin are the same theory.

TYPE: str

theory

The flat presentation.

TYPE: Theory DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

own

The flat signature with only the laws this origin declares.

TYPE: Theory DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

signature

The flat signature without laws.

TYPE: Theory DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

members

Every sort, operation, equation, and rule, with its origin.

TYPE: tuple of Member DEFAULT: ()

includes

The origins it includes directly.

TYPE: tuple of str DEFAULT: ()

closure

Every origin it includes, directly or not, each after the origins it includes.

TYPE: tuple of str DEFAULT: ()

parameters

The parameters of a generic theory.

TYPE: tuple of TheoryParameter DEFAULT: ()

composition

The colimit panproto computed, with its provenance and report.

TYPE: ComposedTheory or None DEFAULT: None

rules

What is known of its rules.

TYPE: RuleCheck DEFAULT: field(default_factory=RuleCheck)

line

Where it is declared.

TYPE: int DEFAULT: 0

col

Where it is declared.

TYPE: int DEFAULT: 0

member

member(kind: MemberKind, name: str) -> Member | None

The member of one kind with one flat name.

PARAMETER DESCRIPTION
kind

The kind.

TYPE: MemberKind

name

The flat name.

TYPE: str

RETURNS DESCRIPTION
Member or None

The member, or None when there is none.

Source code in src/quivers/dsl/theories/values.py
def member(self, kind: MemberKind, name: str) -> Member | None:
    """The member of one kind with one flat name.

    Parameters
    ----------
    kind : MemberKind
        The kind.
    name : str
        The flat name.

    Returns
    -------
    Member or None
        The member, or ``None`` when there is none.
    """
    for member in self.members:
        if member.kind == kind and member.name == name:
            return member
    return None

names

names(*kinds: MemberKind) -> tuple[str, ...]

The flat names of every member of the given kinds.

PARAMETER DESCRIPTION
*kinds

The kinds.

TYPE: MemberKind DEFAULT: ()

RETURNS DESCRIPTION
tuple of str

The names, in member order.

Source code in src/quivers/dsl/theories/values.py
def names(self, *kinds: MemberKind) -> tuple[str, ...]:
    """The flat names of every member of the given kinds.

    Parameters
    ----------
    *kinds : MemberKind
        The kinds.

    Returns
    -------
    tuple of str
        The names, in member order.
    """
    return tuple(m.name for m in self.members if m.kind in kinds)

own_members

own_members() -> tuple[Member, ...]

The members whose origin is this theory.

RETURNS DESCRIPTION
tuple of Member

The members it declares itself.

Source code in src/quivers/dsl/theories/values.py
def own_members(self) -> tuple[Member, ...]:
    """The members whose origin is this theory.

    Returns
    -------
    tuple of Member
        The members it declares itself.
    """
    return tuple(m for m in self.members if m.origin == self.name)

reaches

reaches(origin: str) -> bool

Whether this theory is origin or includes it.

PARAMETER DESCRIPTION
origin

An origin.

TYPE: str

RETURNS DESCRIPTION
bool

Whether origin is this theory or in its closure.

Source code in src/quivers/dsl/theories/values.py
def reaches(self, origin: str) -> bool:
    """Whether this theory is ``origin`` or includes it.

    Parameters
    ----------
    origin : str
        An origin.

    Returns
    -------
    bool
        Whether ``origin`` is this theory or in its closure.
    """
    return origin == self.name or origin in self.closure

hide

hide(value: TheoryValue, names: Sequence[tuple[str, int, int]], registry: Mapping[str, TheoryValue], *, name: str, line: int, col: int) -> TheoryValue

A theory without some sorts and operations, and the laws that use them.

Hiding a sort hides every operation whose signature mentions it.

PARAMETER DESCRIPTION
value

The theory.

TYPE: TheoryValue

names

The hidden sorts and operations.

TYPE: sequence of (name, line, col)

registry

Every theory by origin.

TYPE: mapping of str to TheoryValue

name

The result's origin.

TYPE: str

line

Where the hiding is written.

TYPE: int

col

Where the hiding is written.

TYPE: int

RETURNS DESCRIPTION
TheoryValue

The visible part.

RAISES DESCRIPTION
TheoryError

If a hidden name is not a sort or operation of the theory.

Source code in src/quivers/dsl/theories/algebra.py
def hide(
    value: TheoryValue,
    names: Sequence[tuple[str, int, int]],
    registry: Mapping[str, TheoryValue],
    *,
    name: str,
    line: int,
    col: int,
) -> TheoryValue:
    """A theory without some sorts and operations, and the laws that use them.

    Hiding a sort hides every operation whose signature mentions it.

    Parameters
    ----------
    value : TheoryValue
        The theory.
    names : sequence of (name, line, col)
        The hidden sorts and operations.
    registry : mapping of str to TheoryValue
        Every theory by origin.
    name : str
        The result's origin.
    line, col : int
        Where the hiding is written.

    Returns
    -------
    TheoryValue
        The visible part.

    Raises
    ------
    TheoryError
        If a hidden name is not a sort or operation of the theory.
    """
    sorts = list(sorts_of(value.theory))
    ops = operations_of(value.theory)
    hidden: set[str] = set()
    for hidden_name, h_line, h_col in names:
        if hidden_name not in sorts and hidden_name not in ops:
            raise TheoryError(
                f"{hidden_name!r} is not a sort or operation of theory {value.name!r}",
                h_line,
                h_col,
            )
        hidden.add(hidden_name)
    hidden |= _depending(value, hidden)
    fixed = [
        origin
        for origin in value.closure
        if not any(
            m.kind in ("sort", "op") and m.name in hidden
            for m in _members_of(origin, registry)
        )
    ]
    moved = (set(value.closure) - set(fixed)) | {value.name}
    rendered: dict[str, tuple[Json, Json]] = {}
    for member in value.members:
        if member.kind in ("eq", "rule") and member.origin in moved:
            lhs, rhs = law_terms(value, member.name)
            if (term_operations(lhs) | term_operations(rhs)) & hidden:
                continue
            rendered[member.name] = (lhs, rhs)
    keep = (set(sorts) | set(ops)) - hidden
    local = _local_part(
        value,
        moved,
        {s: s for s in sorts},
        {o: o for o in ops},
        keep,
        rendered,
    )
    return assemble(
        name,
        [registry[o] for o in maximal(fixed, registry)],
        local,
        registry,
        line=line,
        col=col,
    )

instantiate

instantiate(generic: TheoryValue, parameter: str, actual: TheoryValue, fitting: CheckedView | None, registry: Mapping[str, TheoryValue], *, name: str, line: int, col: int) -> TheoryValue

A generic theory instantiated at one parameter, by pushout.

PARAMETER DESCRIPTION
generic

The generic theory.

TYPE: TheoryValue

parameter

The parameter instantiated.

TYPE: str

actual

The theory it is instantiated with.

TYPE: TheoryValue

fitting

The fitting view from the parameter's theory to actual, or None when actual includes the parameter's theory.

TYPE: CheckedView or None

registry

Every theory by origin.

TYPE: mapping of str to TheoryValue

name

The result's origin.

TYPE: str

line

Where the instantiation is written.

TYPE: int

col

Where the instantiation is written.

TYPE: int

RETURNS DESCRIPTION
TheoryValue

The pushout of generic and actual over the parameter's theory, generic in its remaining parameters.

RAISES DESCRIPTION
TheoryError

If the theory has no such parameter, the fitting view does not go from the parameter's theory to actual, or panproto refuses the pushout.

Source code in src/quivers/dsl/theories/algebra.py
def instantiate(
    generic: TheoryValue,
    parameter: str,
    actual: TheoryValue,
    fitting: CheckedView | None,
    registry: Mapping[str, TheoryValue],
    *,
    name: str,
    line: int,
    col: int,
) -> TheoryValue:
    """A generic theory instantiated at one parameter, by pushout.

    Parameters
    ----------
    generic : TheoryValue
        The generic theory.
    parameter : str
        The parameter instantiated.
    actual : TheoryValue
        The theory it is instantiated with.
    fitting : CheckedView or None
        The fitting view from the parameter's theory to ``actual``, or
        ``None`` when ``actual`` includes the parameter's theory.
    registry : mapping of str to TheoryValue
        Every theory by origin.
    name : str
        The result's origin.
    line, col : int
        Where the instantiation is written.

    Returns
    -------
    TheoryValue
        The pushout of ``generic`` and ``actual`` over the parameter's
        theory, generic in its remaining parameters.

    Raises
    ------
    TheoryError
        If the theory has no such parameter, the fitting view does not go
        from the parameter's theory to ``actual``, or panproto refuses the
        pushout.
    """
    found = [p for p in generic.parameters if p.name == parameter]
    if not found:
        raise TheoryError(
            f"theory {generic.name!r} has no parameter {parameter!r}", line, col
        )
    formal = registry[found[0].theory]
    if fitting is None:
        if not actual.reaches(formal.name):
            raise TheoryError(
                f"theory {actual.name!r} does not include {formal.name!r}, the theory "
                f"of parameter {parameter!r}; give a fitting view with `via`",
                line,
                col,
            )
        leg = MorphismRecord(
            name=f"{name}#fit",
            domain=formal.theory.name,
            codomain=actual.theory.name,
            sort_map={s: s for s in sorts_of(formal.theory)},
            op_renames={o: o for o in operations_of(formal.theory)},
        )
    else:
        if fitting.domain != formal.name or fitting.codomain != actual.name:
            raise TheoryError(
                f"view {fitting.name!r} goes from {fitting.domain!r} to "
                f"{fitting.codomain!r}; parameter {parameter!r} needs a view from "
                f"{formal.name!r} to {actual.name!r}",
                line,
                col,
            )
        leg = fitting.morphism
    parameter_part = {formal.name, *formal.closure}
    inclusion = MorphismRecord(
        name=f"{name}#parameter",
        domain=formal.theory.name,
        codomain=generic.theory.name,
        sort_map={s: s for s in sorts_of(formal.theory)},
        op_renames={o: o for o in operations_of(formal.theory)},
    )
    try:
        pushout = compose_span(
            ("P", formal.theory),
            ("G", generic.theory),
            ("X", actual.theory),
            inclusion,
            leg,
            result_name=name,
        )
    except CompositionRefused as error:
        raise TheoryError(
            f"the instantiation of {generic.name!r} at {parameter!r} := "
            f"{actual.name!r} has no pushout: {error.message}",
            line,
            col,
        ) from error
    flat = composed_theory(pushout)
    provenance = pushout.provenance
    independent = [
        origin
        for origin in generic.closure
        if not any(registry[origin].reaches(p) for p in parameter_part)
    ]
    kept = set(independent)

    sorts: list[LocalSort] = []
    for sort in sorts_of(flat):
        if (
            _from_node(provenance, "sort", sort, "X")
            or _origin_in(provenance, generic, "sort", sort) in kept
        ):
            continue
        sorts.append(
            LocalSort(
                name=sort,
                serialized=json.dumps(sort_entries(flat)[sort]),
                line=line,
                col=col,
            )
        )
    operations: list[LocalOperation] = []
    for op, entry in operation_entries(flat).items():
        if (
            _from_node(provenance, "op", op, "X")
            or _origin_in(provenance, generic, "op", op) in kept
        ):
            continue
        operations.append(
            LocalOperation(name=op, serialized=json.dumps(entry), line=line, col=col)
        )
    laws: list[LocalLaw] = []
    law_kinds: tuple[tuple[SymbolKind, list[Json]], ...] = (
        ("eq", flat.eqs),
        ("directed_eq", flat.directed_eqs),
    )
    for kind, entries in law_kinds:
        for entry in entries:
            if not isinstance(entry, dict):
                continue
            law = entry.get("name")
            if not isinstance(law, str):
                continue
            if (
                _from_node(provenance, kind, law, "X")
                or _origin_in(provenance, generic, kind, law) in kept
            ):
                continue
            member = generic.member(_MEMBER_KINDS[kind], law)
            local = law if member is None else _moved_local(member, generic)
            laws.append(
                LocalLaw(
                    local=local,
                    sides=json.dumps([entry["lhs"], entry["rhs"]]),
                    oriented=kind == "directed_eq",
                    line=member.line if member else line,
                    col=member.col if member else col,
                )
            )
    local = LocalPart(
        sorts=tuple(sorts),
        operations=tuple(operations),
        laws=tuple(laws),
        assume_terminating=generic.rules.termination == "assumed",
    )
    includes = [actual, *(registry[o] for o in maximal(independent, registry))]
    return assemble(
        name,
        includes,
        local,
        registry,
        parameters=tuple(p for p in generic.parameters if p.name != parameter),
        line=line,
        col=col,
    )

law_terms

law_terms(value: TheoryValue, flat: str) -> tuple[Json, Json]

The serialized sides of a law of a theory.

PARAMETER DESCRIPTION
value

The theory.

TYPE: TheoryValue

flat

The law's flat name.

TYPE: str

RETURNS DESCRIPTION
tuple of Json

Its left and right sides.

RAISES DESCRIPTION
KeyError

If the theory has no law of that name.

Source code in src/quivers/dsl/theories/algebra.py
def law_terms(value: TheoryValue, flat: str) -> tuple[Json, Json]:
    """The serialized sides of a law of a theory.

    Parameters
    ----------
    value : TheoryValue
        The theory.
    flat : str
        The law's flat name.

    Returns
    -------
    tuple of Json
        Its left and right sides.

    Raises
    ------
    KeyError
        If the theory has no law of that name.
    """
    for entry in (*value.theory.eqs, *value.theory.directed_eqs):
        if isinstance(entry, dict) and entry.get("name") == flat:
            return entry["lhs"], entry["rhs"]
    raise KeyError(f"theory {value.name!r} has no law {flat!r}")

maximal

maximal(origins: Sequence[str], registry: Mapping[str, TheoryValue]) -> list[str]

The origins not included by another of the given origins.

PARAMETER DESCRIPTION
origins

Origins, closed under inclusion.

TYPE: sequence of str

registry

Every theory by origin.

TYPE: mapping of str to TheoryValue

RETURNS DESCRIPTION
list of str

The maximal ones, in the given order.

Source code in src/quivers/dsl/theories/algebra.py
def maximal(origins: Sequence[str], registry: Mapping[str, TheoryValue]) -> list[str]:
    """The origins not included by another of the given origins.

    Parameters
    ----------
    origins : sequence of str
        Origins, closed under inclusion.
    registry : mapping of str to TheoryValue
        Every theory by origin.

    Returns
    -------
    list of str
        The maximal ones, in the given order.
    """
    return [
        origin
        for origin in origins
        if not any(
            origin in registry[other].closure for other in origins if other != origin
        )
    ]

rename

rename(value: TheoryValue, renames: Sequence[tuple[str, str, int, int]], registry: Mapping[str, TheoryValue], *, name: str, line: int, col: int) -> TheoryValue

A copy of a theory with some sorts and operations renamed.

PARAMETER DESCRIPTION
value

The theory.

TYPE: TheoryValue

renames

The renamed symbols and their new names.

TYPE: sequence of (source, target, line, col)

registry

Every theory by origin.

TYPE: mapping of str to TheoryValue

name

The copy's origin.

TYPE: str

line

Where the renaming is written.

TYPE: int

col

Where the renaming is written.

TYPE: int

RETURNS DESCRIPTION
TheoryValue

The copy.

RAISES DESCRIPTION
TheoryError

If a renamed name is not a sort or operation of the theory, two symbols get one name, or a new name is already taken.

Source code in src/quivers/dsl/theories/algebra.py
def rename(
    value: TheoryValue,
    renames: Sequence[tuple[str, str, int, int]],
    registry: Mapping[str, TheoryValue],
    *,
    name: str,
    line: int,
    col: int,
) -> TheoryValue:
    """A copy of a theory with some sorts and operations renamed.

    Parameters
    ----------
    value : TheoryValue
        The theory.
    renames : sequence of (source, target, line, col)
        The renamed symbols and their new names.
    registry : mapping of str to TheoryValue
        Every theory by origin.
    name : str
        The copy's origin.
    line, col : int
        Where the renaming is written.

    Returns
    -------
    TheoryValue
        The copy.

    Raises
    ------
    TheoryError
        If a renamed name is not a sort or operation of the theory, two
        symbols get one name, or a new name is already taken.
    """
    sorts = list(sorts_of(value.theory))
    ops = operations_of(value.theory)
    mapping: dict[str, str] = {}
    for source, target, r_line, r_col in renames:
        if source not in sorts and source not in ops:
            raise TheoryError(
                f"{source!r} is not a sort or operation of theory {value.name!r}",
                r_line,
                r_col,
            )
        if source in mapping:
            raise TheoryError(f"{source!r} is renamed twice", r_line, r_col)
        mapping[source] = target
    targets = [mapping.get(s, s) for s in (*sorts, *ops)]
    for source, target, r_line, r_col in renames:
        if targets.count(target) > 1:
            raise TheoryError(
                f"renaming {source!r} to {target!r} gives two symbols of theory "
                f"{value.name!r} the name {target!r}",
                r_line,
                r_col,
            )
    renamed = set(mapping)
    fixed = [
        origin
        for origin in value.closure
        if not any(
            m.kind in ("sort", "op") and m.name in renamed
            for m in _members_of(origin, registry)
        )
    ]
    moved = (set(value.closure) - set(fixed)) | {value.name}
    sort_names = {s: mapping.get(s, s) for s in sorts}
    op_names = {o: mapping.get(o, o) for o in ops}
    morphism = MorphismRecord(
        name=f"{name}#renaming",
        domain=value.theory.name,
        codomain=name,
        sort_map=sort_names,
        op_renames=op_names,
    )
    rendered: dict[str, tuple[Json, Json]] = {}
    for member in value.members:
        if member.kind in ("eq", "rule") and member.origin in moved:
            lhs, rhs = law_terms(value, member.name)
            rendered[member.name] = (
                rename_term(lhs, op_names),
                rename_term(rhs, op_names),
            )
    local = _local_part(
        value, moved, sort_names, op_names, set(sorts) | set(ops), rendered
    )
    copy = assemble(
        name,
        [registry[o] for o in maximal(fixed, registry)],
        local,
        registry,
        line=line,
        col=col,
    )
    _certify(morphism.with_(codomain=copy.theory.name), value, copy, line, col)
    return copy

summed

summed(summands: Sequence[TheoryValue], shared: Sequence[tuple[TheoryValue, int, int]], registry: Mapping[str, TheoryValue], *, name: str, line: int, col: int) -> TheoryValue

The colimit of theories over the theories they share.

PARAMETER DESCRIPTION
summands

The theories composed.

TYPE: sequence of TheoryValue

shared

The theories declared shared.

TYPE: sequence of (TheoryValue, line, col)

registry

Every theory by origin.

TYPE: mapping of str to TheoryValue

name

The result's origin.

TYPE: str

line

Where the sum is written.

TYPE: int

col

Where the sum is written.

TYPE: int

RETURNS DESCRIPTION
TheoryValue

The colimit.

RAISES DESCRIPTION
TheoryError

If a declared shared theory is not included by two summands, two summands share a theory over does not declare, or panproto refuses the colimit.

Source code in src/quivers/dsl/theories/algebra.py
def summed(
    summands: Sequence[TheoryValue],
    shared: Sequence[tuple[TheoryValue, int, int]],
    registry: Mapping[str, TheoryValue],
    *,
    name: str,
    line: int,
    col: int,
) -> TheoryValue:
    """The colimit of theories over the theories they share.

    Parameters
    ----------
    summands : sequence of TheoryValue
        The theories composed.
    shared : sequence of (TheoryValue, line, col)
        The theories declared shared.
    registry : mapping of str to TheoryValue
        Every theory by origin.
    name : str
        The result's origin.
    line, col : int
        Where the sum is written.

    Returns
    -------
    TheoryValue
        The colimit.

    Raises
    ------
    TheoryError
        If a declared shared theory is not included by two summands, two
        summands share a theory ``over`` does not declare, or panproto
        refuses the colimit.
    """
    reach = [{s.name, *s.closure} for s in summands]
    declared: set[str] = set()
    for theory, s_line, s_col in shared:
        holders = [
            s.name for s, r in zip(summands, reach, strict=True) if theory.name in r
        ]
        if len(holders) < 2:
            raise TheoryError(
                f"theory {theory.name!r} is declared shared, but "
                + (
                    f"only {holders[0]!r} includes it"
                    if holders
                    else "no summand includes it"
                ),
                s_line,
                s_col,
            )
        declared |= {theory.name, *theory.closure}
    for i, left in enumerate(summands):
        for j in range(i + 1, len(summands)):
            right = summands[j]
            common = (reach[i] & reach[j]) - declared
            if common:
                first = next(o for o in (*left.closure, left.name) if o in common)
                raise TheoryError(
                    f"{left.name!r} and {right.name!r} both include {first!r}, which "
                    f"`over` does not declare shared; write `over {first}`",
                    line,
                    col,
                )
    return assemble(name, summands, LocalPart(), registry, line=line, col=col)

term_operations

term_operations(term: Json) -> set[str]

The operations applied in a serialized term.

PARAMETER DESCRIPTION
term

A term in panproto's serialized shape.

TYPE: Json

RETURNS DESCRIPTION
set of str

Every operation it applies.

Source code in src/quivers/dsl/theories/algebra.py
def term_operations(term: Json) -> set[str]:
    """The operations applied in a serialized term.

    Parameters
    ----------
    term : Json
        A term in panproto's serialized shape.

    Returns
    -------
    set of str
        Every operation it applies.
    """
    found: set[str] = set()
    stack: list[Json] = [term]
    while stack:
        current = stack.pop()
        if isinstance(current, dict):
            application = current.get("App")
            if isinstance(application, dict):
                op = application.get("op")
                if isinstance(op, str):
                    found.add(op)
            stack.extend(current.values())
        elif isinstance(current, list):
            stack.extend(current)
    return found

finite_values

finite_values(type_: TypeExpr, module: QiecModule, enclosing: tuple[TypeExpr, ...] = ()) -> tuple[HostValue, ...]

Every value of a finite type, constructors in declaration order.

PARAMETER DESCRIPTION
type_

The type.

TYPE: TypeExpr

module

The checked module declaring its families.

TYPE: QiecModule

enclosing

The families whose values are being built around this one.

TYPE: tuple of TypeExpr DEFAULT: ()

RETURNS DESCRIPTION
tuple of HostValue

The values.

RAISES DESCRIPTION
CarrierError

If the type is not finite: an opaque or indexed family, a constructor with static binders, a recursive family, or a type with infinitely many values.

Source code in src/quivers/dsl/theories/carriers.py
def finite_values(
    type_: TypeExpr, module: QiecModule, enclosing: tuple[TypeExpr, ...] = ()
) -> tuple[HostValue, ...]:
    """Every value of a finite type, constructors in declaration order.

    Parameters
    ----------
    type_ : TypeExpr
        The type.
    module : QiecModule
        The checked module declaring its families.
    enclosing : tuple of TypeExpr
        The families whose values are being built around this one.

    Returns
    -------
    tuple of HostValue
        The values.

    Raises
    ------
    CarrierError
        If the type is not finite: an opaque or indexed family, a
        constructor with static binders, a recursive family, or a type
        with infinitely many values.
    """
    if type_ == BOOL:
        return (False, True)
    if type_ == UNIT:
        return ((),)
    if isinstance(type_, TypeApplication):
        family = _family(type_, module)
        if family is not None:
            return _family_values(family, type_, module, enclosing)
    raise CarrierError(f"the type {type_!r} does not have finitely many values")

named_type

named_type(name: str, module: QiecModule) -> TypeExpr

The QIEC type a model's sort interpretation names.

PARAMETER DESCRIPTION
name

Bool, Unit, or a data family's name.

TYPE: str

module

The checked module.

TYPE: QiecModule

RETURNS DESCRIPTION
TypeExpr

The type.

RAISES DESCRIPTION
CarrierError

If the name is neither a builtin finite type nor a family of the module, or the family takes parameters or indices.

Source code in src/quivers/dsl/theories/carriers.py
def named_type(name: str, module: QiecModule) -> TypeExpr:
    """The QIEC type a model's sort interpretation names.

    Parameters
    ----------
    name : str
        ``Bool``, ``Unit``, or a data family's name.
    module : QiecModule
        The checked module.

    Returns
    -------
    TypeExpr
        The type.

    Raises
    ------
    CarrierError
        If the name is neither a builtin finite type nor a family of the
        module, or the family takes parameters or indices.
    """
    if name == "Bool":
        return BOOL
    if name == "Unit":
        return UNIT
    for family in module.families:
        if family.name == name:
            if family.parameters or family.indices:
                raise CarrierError(
                    f"family {name!r} takes parameters or indices; a carrier is a "
                    "closed type"
                )
            return TypeApplication(constructor=family.type_constructor, arguments=())
    raise CarrierError(f"{name!r} is not Bool, Unit, or a data family of the module")

render_value

render_value(value: Value) -> str

Render a value record as QVR writes it.

PARAMETER DESCRIPTION
value

The value.

TYPE: Value

RETURNS DESCRIPTION
str

true/false, a number, a string, a constructor applied to its fields, a tuple, a map {k = v} (an element of a right Kan extension), or null.

RAISES DESCRIPTION
CarrierError

If the record is not a value variant.

Source code in src/quivers/dsl/theories/carriers.py
def render_value(value: Value) -> str:
    """Render a value record as QVR writes it.

    Parameters
    ----------
    value : Value
        The value.

    Returns
    -------
    str
        ``true``/``false``, a number, a string, a constructor applied to
        its fields, a tuple, a map ``{k = v}`` (an element of a right
        Kan extension), or ``null``.

    Raises
    ------
    CarrierError
        If the record is not a value variant.
    """
    if isinstance(value, BoolValue):
        return "true" if value.value else "false"
    if isinstance(value, IntValue):
        return str(value.value)
    if isinstance(value, StrValue):
        return repr(value.value)
    if isinstance(value, ListValue):
        return "(" + ", ".join(render_value(v) for v in value.items) + ")"
    if isinstance(value, ConstructorValue):
        if not value.args:
            return value.tag
        return f"{value.tag}(" + ", ".join(render_value(v) for v in value.args) + ")"
    if isinstance(value, MapValue):
        entries = ", ".join(f"{e.key} = {render_value(e.value)}" for e in value.entries)
        return "{" + entries + "}"
    if isinstance(value, NullValue):
        return "null"
    raise CarrierError(f"not a model value: {value!r}")

value_record

value_record(value: ResultValue, module: QiecModule) -> Value

A machine value as panproto's value record.

PARAMETER DESCRIPTION
value

A value of a finite type, or a result of an operation.

TYPE: ResultValue

module

The checked module, for constructor names.

TYPE: QiecModule

RETURNS DESCRIPTION
Value

A constructor value tagged by the constructor's source name, a boolean (a truth tensor included), an integer, a string, or a list for a tuple.

RAISES DESCRIPTION
CarrierError

If the value is of none of these forms.

Source code in src/quivers/dsl/theories/carriers.py
def value_record(value: ResultValue, module: QiecModule) -> Value:
    """A machine value as panproto's value record.

    Parameters
    ----------
    value : ResultValue
        A value of a finite type, or a result of an operation.
    module : QiecModule
        The checked module, for constructor names.

    Returns
    -------
    Value
        A constructor value tagged by the constructor's source name, a
        boolean (a truth tensor included), an integer, a string, or a list
        for a tuple.

    Raises
    ------
    CarrierError
        If the value is of none of these forms.
    """
    if isinstance(value, torch.Tensor):
        if value.dim() != 0:
            raise CarrierError(
                f"a tensor of shape {tuple(value.shape)} is not finite data"
            )
        if value.dtype == torch.bool:
            return BoolValue(value=bool(value.item()))
        if value.dtype.is_floating_point or value.dtype.is_complex:
            raise CarrierError(f"the real number {value.item()} is not finite data")
        return IntValue(value=int(value.item()))
    if isinstance(value, bool):
        return BoolValue(value=value)
    if isinstance(value, int):
        return IntValue(value=value)
    if isinstance(value, str):
        return StrValue(value=value)
    if isinstance(value, tuple):
        return ListValue(items=tuple(value_record(item, module) for item in value))
    if isinstance(value, RuntimeConstructor):
        names = {c.id: c.name for c in module.constructors}
        return ConstructorValue(
            tag=names[value.constructor],
            args=tuple(
                value_record(_result_value(field), module) for field in value.fields
            ),
        )
    raise CarrierError(f"a model value is not finite data: {value!r}")

classify

classify(base: TheoryValue, extension: TheoryValue, models: Sequence[CheckedModel], search_bound: int | None = None) -> Verdict

Classify the inclusion of one theory into another that includes it.

PARAMETER DESCRIPTION
base

The included theory.

TYPE: TheoryValue

extension

A theory that includes it.

TYPE: TheoryValue

models

Checked models of base, which may refute conservativity.

TYPE: sequence of CheckedModel

search_bound

When given, and neither the syntactic conditions nor models settle the classification, the models of base with at most this many elements per sort are searched for one with no expansion (quivers.dsl.theories.search.search_refutation).

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
Verdict

The classification and its argument. A search that finds nothing leaves it undetermined within its bound, never conservative.

Source code in src/quivers/dsl/theories/classification.py
def classify(
    base: TheoryValue,
    extension: TheoryValue,
    models: Sequence[CheckedModel],
    search_bound: int | None = None,
) -> Verdict:
    """Classify the inclusion of one theory into another that includes it.

    Parameters
    ----------
    base : TheoryValue
        The included theory.
    extension : TheoryValue
        A theory that includes it.
    models : sequence of CheckedModel
        Checked models of ``base``, which may refute conservativity.
    search_bound : int or None
        When given, and neither the syntactic conditions nor ``models``
        settle the classification, the models of ``base`` with at most
        this many elements per sort are searched for one with no expansion
        (`quivers.dsl.theories.search.search_refutation`).

    Returns
    -------
    Verdict
        The classification and its argument. A search that finds nothing
        leaves it undetermined within its bound, never conservative.
    """
    base_sorts = set(sorts_of(base.theory))
    base_ops = set(operations_of(base.theory))
    ext_ops = operations_of(extension.theory)
    new_sorts = set(sorts_of(extension.theory)) - base_sorts
    new_ops = set(ext_ops) - base_ops
    base_laws = set(base.names("eq", "rule"))
    laws = [
        _Law(name=str(entry["name"]), lhs=entry["lhs"], rhs=entry["rhs"])
        for entry in (*extension.theory.eqs, *extension.theory.directed_eqs)
        if isinstance(entry, dict) and entry.get("name") not in base_laws
    ]
    candidates: dict[str, list[tuple[_Law, Json]]] = {}
    for law in laws:
        found = _definition(law, new_ops)
        if found is not None:
            candidates.setdefault(found[0], []).append((law, found[1]))
    unique = {op: pairs[0] for op, pairs in candidates.items() if len(pairs) == 1}
    defined = _ordered_definitions(unique, base_ops)
    definition_names = {law.name for law in defined.values()}
    definitional_ops = base_ops | set(defined)
    definitional_sorts = set(base_sorts)
    for op in defined:
        _, inputs, output = ext_ops[op]
        definitional_sorts.update((*inputs, output))
    definitional = with_laws(
        restricted(
            extension.theory,
            f"{extension.name}#definitional",
            definitional_sorts,
            definitional_ops,
        ),
        f"{extension.name}#definitional",
        [
            *(e for e in base.theory.eqs),
            *(
                {"name": e["name"], "lhs": e["lhs"], "rhs": e["rhs"]}
                for e in base.theory.directed_eqs
                if isinstance(e, dict)
            ),
            *(_equation_entry(law) for law in defined.values()),
        ],
        [],
    )
    blocking_laws: list[_Law] = []
    for law in laws:
        if law.name in definition_names:
            continue
        mentioned = term_operations(law.lhs) | term_operations(law.rhs)
        if mentioned <= definitional_ops and _holds_in(
            law, definitional, definitional_sorts, definitional_ops
        ):
            continue
        blocking_laws.append(law)
    undefined = sorted(new_ops - set(defined))
    if not new_sorts and not undefined and not blocking_laws:
        return Verdict(
            classification="definitional",
            reason=(
                "it adds no sorts, defines each operation it adds explicitly, and "
                "every other law it adds holds in the included theory with those "
                "definitions"
                if new_ops or laws
                else "it adds nothing to the included theory"
            ),
        )
    into_old = [op for op in undefined if ext_ops[op][2] not in new_sorts]
    old_sort_laws = [
        law
        for law in blocking_laws
        if (_sort_of(law.lhs, ext_ops) or _sort_of(law.rhs, ext_ops)) not in new_sorts
    ]
    if not into_old and not old_sort_laws:
        return Verdict(
            classification="conservative",
            reason=(
                "every operation it adds without a definition has a result sort it "
                "adds, and every other law it adds relates terms of a sort it adds"
            ),
        )
    witness = _refute(base, extension, models)
    if witness is not None:
        return Verdict(
            classification="neither",
            reason=(
                f"model {witness.model!r} of {base.name!r} has no expansion: the "
                f"laws of {extension.name!r} identify its elements {witness.left} and "
                f"{witness.right} of sort {witness.sort!r}"
            ),
            witness=witness,
        )
    blockers = [f"operation {op!r}" for op in into_old] + [
        f"law {_display(extension, law.name)!r}" for law in old_sort_laws
    ]
    reason = (
        "the checker neither establishes nor refutes conservativity: "
        + ", ".join(blockers)
        + " may constrain the included theory's sorts, and no checked model of "
        f"{base.name!r} refutes it"
    )
    if search_bound is None:
        return Verdict(classification="undetermined", reason=reason)
    if any(sort_parameters(base.theory).values()):
        return Verdict(
            classification="undetermined",
            reason=reason
            + "; the bounded search enumerates models of theories whose sorts "
            "take no parameters, and models of dependent sorts await fibered "
            "models in panproto (panproto/panproto#439)",
        )
    search = search_refutation(base, extension, search_bound)
    if search.witness is not None:
        found = search.witness
        return Verdict(
            classification="neither",
            reason=(
                f"{found.model}, a model of {base.name!r} with at most "
                f"{search_bound} elements per sort, has no expansion: the laws of "
                f"{extension.name!r} identify its elements {found.left} and "
                f"{found.right} of sort {found.sort!r}"
            ),
            witness=found,
            search=search,
        )
    scope = (
        f"none of the {search.models} models of {base.name!r} with at most "
        f"{search_bound} elements per sort refutes it"
        if search.exhausted
        else f"the search stopped after {search.models} models of {base.name!r} "
        f"with at most {search_bound} elements per sort without refuting it"
    )
    return Verdict(
        classification="undetermined",
        reason=f"{reason}; undetermined within bound {search_bound}: {scope}",
        search=search,
    )

check_instance

check_instance(theory: TheoryValue, instance: str, interpretations: Mapping[str, str], module: QiecModule, *, line: int = 0, col: int = 0) -> CheckedModel

Check an instance of a signature as a finite model of its theory.

PARAMETER DESCRIPTION
theory

The signature's theory.

TYPE: TheoryValue

instance

The instance's name, for refusals.

TYPE: str

interpretations

Each sort's QIEC type and each operation's computation.

TYPE: mapping of str to str

module

The checked module the types and computations belong to.

TYPE: QiecModule

line

Where the instance is declared.

TYPE: int DEFAULT: 0

col

Where the instance is declared.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
CheckedModel

The model, every law of the theory checked at every assignment.

RAISES DESCRIPTION
TheoryError

If a symbol is not interpreted, a carrier is not finite, a computation does not fit its operation, or a law fails, with the assignment.

Source code in src/quivers/dsl/theories/instances.py
def check_instance(
    theory: TheoryValue,
    instance: str,
    interpretations: Mapping[str, str],
    module: QiecModule,
    *,
    line: int = 0,
    col: int = 0,
) -> CheckedModel:
    """Check an instance of a signature as a finite model of its theory.

    Parameters
    ----------
    theory : TheoryValue
        The signature's theory.
    instance : str
        The instance's name, for refusals.
    interpretations : mapping of str to str
        Each sort's QIEC type and each operation's computation.
    module : QiecModule
        The checked module the types and computations belong to.
    line, col : int
        Where the instance is declared.

    Returns
    -------
    CheckedModel
        The model, every law of the theory checked at every assignment.

    Raises
    ------
    TheoryError
        If a symbol is not interpreted, a carrier is not finite, a
        computation does not fit its operation, or a law fails, with the
        assignment.
    """
    declaration = ModelDecl(
        name=instance,
        theory=theory.name,
        interpretations=tuple(
            ModelInterpretationDecl(symbol=symbol, value=value, line=line, col=col)
            for symbol, value in interpretations.items()
        ),
        line=line,
        col=col,
    )
    return interpreted_model(declaration, theory, module)

check_instance_view

check_instance_view(theory: TheoryValue, instance: TheoryValue, mapping: Mapping[str, str], layer: TheoryLayer, *, name: str, assumed: Sequence[str] = (), line: int = 0, col: int = 0) -> CheckedView

Check an instance that is a theory as a view from the signature's theory.

PARAMETER DESCRIPTION
theory

The signature's theory, the view's domain.

TYPE: TheoryValue

instance

The instance, the view's codomain.

TYPE: TheoryValue

mapping

Each sort and operation of theory sent to a sort or operation of instance; a symbol left out goes to itself when instance includes the theory that declares it.

TYPE: mapping of str to str

layer

The layer holding both theories and the models of instance, which refute obligations.

TYPE: TheoryLayer

name

The view's name.

TYPE: str

assumed

The equations the instance assumes.

TYPE: sequence of str DEFAULT: ()

line

Where the instance is declared.

TYPE: int DEFAULT: 0

col

Where the instance is declared.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
CheckedView

The view, each obligation established or assumed.

RAISES DESCRIPTION
TheoryError

If the mapping is not a theory morphism, or an obligation is refuted by a model or neither established nor assumed.

Source code in src/quivers/dsl/theories/instances.py
def check_instance_view(
    theory: TheoryValue,
    instance: TheoryValue,
    mapping: Mapping[str, str],
    layer: TheoryLayer,
    *,
    name: str,
    assumed: Sequence[str] = (),
    line: int = 0,
    col: int = 0,
) -> CheckedView:
    """Check an instance that is a theory as a view from the signature's theory.

    Parameters
    ----------
    theory : TheoryValue
        The signature's theory, the view's domain.
    instance : TheoryValue
        The instance, the view's codomain.
    mapping : mapping of str to str
        Each sort and operation of ``theory`` sent to a sort or operation of
        ``instance``; a symbol left out goes to itself when ``instance``
        includes the theory that declares it.
    layer : TheoryLayer
        The layer holding both theories and the models of ``instance``,
        which refute obligations.
    name : str
        The view's name.
    assumed : sequence of str
        The equations the instance assumes.
    line, col : int
        Where the instance is declared.

    Returns
    -------
    CheckedView
        The view, each obligation established or assumed.

    Raises
    ------
    TheoryError
        If the mapping is not a theory morphism, or an obligation is
        refuted by a model or neither established nor assumed.
    """
    for value in (theory, instance):
        if layer.theories.get(value.name) is not value:
            raise TheoryError(
                f"instance {name!r}: theory {value.name!r} is not recorded in the "
                "theory layer; record it with TheoryLayer.add_theory",
                line,
                col,
            )
    declaration = ViewDecl(
        name=name,
        domain=theory.name,
        codomain=instance.name,
        mappings=tuple(
            ViewMappingDecl(
                source=PatternSyntax(kind="name", name=source, line=line, col=col),
                target=PatternSyntax(kind="name", name=target, line=line, col=col),
                line=line,
                col=col,
            )
            for source, target in mapping.items()
        ),
        assumptions=tuple(
            ViewAssumptionDecl(equation=equation, line=line, col=col)
            for equation in assumed
        ),
        line=line,
        col=col,
    )
    return layer.check_view(declaration)

signature_theory

signature_theory(name: str, sorts: Sequence[str], operations: Sequence[tuple[str, Sequence[str], str]], equations: Sequence[EquationDecl], registry: Mapping[str, TheoryValue], *, includes: Sequence[TheoryValue] = (), line: int = 0, col: int = 0) -> TheoryValue

The theory of a signature's sorts, operations, and equations.

PARAMETER DESCRIPTION
name

The theory's origin, the signature's name.

TYPE: str

sorts

The signature's own sorts.

TYPE: sequence of str

operations

Its own operations.

TYPE: sequence of (name, input sorts, output sort)

equations

Its equations and rules, as the parser reads them.

TYPE: sequence of EquationDecl

registry

Every theory by origin, for includes.

TYPE: mapping of str to TheoryValue

includes

Theories the signature includes.

TYPE: sequence of TheoryValue DEFAULT: ()

line

Where the signature is declared.

TYPE: int DEFAULT: 0

col

Where the signature is declared.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
TheoryValue

The theory.

RAISES DESCRIPTION
TheoryError

If a law is ill-sorted, or panproto refuses the composition.

Source code in src/quivers/dsl/theories/instances.py
def signature_theory(
    name: str,
    sorts: Sequence[str],
    operations: Sequence[tuple[str, Sequence[str], str]],
    equations: Sequence[EquationDecl],
    registry: Mapping[str, TheoryValue],
    *,
    includes: Sequence[TheoryValue] = (),
    line: int = 0,
    col: int = 0,
) -> TheoryValue:
    """The theory of a signature's sorts, operations, and equations.

    Parameters
    ----------
    name : str
        The theory's origin, the signature's name.
    sorts : sequence of str
        The signature's own sorts.
    operations : sequence of (name, input sorts, output sort)
        Its own operations.
    equations : sequence of EquationDecl
        Its equations and rules, as the parser reads them.
    registry : mapping of str to TheoryValue
        Every theory by origin, for ``includes``.
    includes : sequence of TheoryValue
        Theories the signature includes.
    line, col : int
        Where the signature is declared.

    Returns
    -------
    TheoryValue
        The theory.

    Raises
    ------
    TheoryError
        If a law is ill-sorted, or panproto refuses the composition.
    """
    base = assemble(name, includes, LocalPart(), registry, line=line, col=col)
    signature_part = LocalPart(
        sorts=tuple(
            LocalSort(name=s, serialized=json.dumps(sort_entry(s)), line=line, col=col)
            for s in sorts
        ),
        operations=tuple(
            LocalOperation(
                name=op,
                serialized=json.dumps(
                    operation_entry(
                        op,
                        [
                            (name, sort, False)
                            for name, sort in zip(
                                input_names(len(inputs)), inputs, strict=True
                            )
                        ],
                        output,
                    )
                ),
                line=line,
                col=col,
            )
            for op, inputs, output in operations
        ),
    )
    laws = check_laws(name, equations, signature_of(base, signature_part))
    return assemble(
        name,
        includes,
        signature_part.with_(laws=laws),
        registry,
        line=line,
        col=col,
    )

law_theory

law_theory(value: TheoryValue, name: str, lhs: str, rhs: str) -> Theory

A theory's signature with one equation.

PARAMETER DESCRIPTION
value

The theory whose sorts and operations it has.

TYPE: TheoryValue

name

The equation's name.

TYPE: str

lhs

Its sides, in panproto's term syntax.

TYPE: str

rhs

Its sides, in panproto's term syntax.

TYPE: str

RETURNS DESCRIPTION
Theory

The theory.

Source code in src/quivers/dsl/theories/layer.py
def law_theory(value: TheoryValue, name: str, lhs: str, rhs: str) -> panproto.Theory:
    """A theory's signature with one equation.

    Parameters
    ----------
    value : TheoryValue
        The theory whose sorts and operations it has.
    name : str
        The equation's name.
    lhs, rhs : str
        Its sides, in panproto's term syntax.

    Returns
    -------
    panproto.Theory
        The theory.
    """
    builder = panproto.TheoryBuilder(value.theory.name)
    for sort in sorts_of(value.theory):
        builder.sort(sort)
    for op, (names, sorts, output) in operations_of(value.theory).items():
        builder.op(op, list(sorts), output, input_names=list(names))
    builder.eq(name, lhs, rhs)
    return builder.build()

check_laws_hold

check_laws_hold(where: str, model: FiniteModel, value: TheoryValue, line: int, col: int) -> ModelVerification

Require every law of a theory to hold in a finite model.

PARAMETER DESCRIPTION
where

The model, for refusals.

TYPE: str

model

The model.

TYPE: FiniteModel

value

Its theory.

TYPE: TheoryValue

line

Where the model is declared.

TYPE: int

col

Where the model is declared.

TYPE: int

RETURNS DESCRIPTION
ModelVerification

panproto's verdict, "passed".

RAISES DESCRIPTION
TheoryError

If a law fails, with the assignment and the values of both sides, or the check is not exhaustive within MAX_ASSIGNMENTS.

Source code in src/quivers/dsl/theories/models.py
def check_laws_hold(
    where: str, model: FiniteModel, value: TheoryValue, line: int, col: int
) -> ModelVerification:
    """Require every law of a theory to hold in a finite model.

    Parameters
    ----------
    where : str
        The model, for refusals.
    model : FiniteModel
        The model.
    value : TheoryValue
        Its theory.
    line, col : int
        Where the model is declared.

    Returns
    -------
    ModelVerification
        panproto's verdict, ``"passed"``.

    Raises
    ------
    TheoryError
        If a law fails, with the assignment and the values of both sides,
        or the check is not exhaustive within `MAX_ASSIGNMENTS`.
    """
    verdict = verify_model(model, laws_as_equations(value.theory), MAX_ASSIGNMENTS)
    if verdict.violations:
        violation = verdict.violations[0]
        member = value.member("eq", violation.equation) or value.member(
            "rule", violation.equation
        )
        local = member.local if member is not None else violation.equation
        origin = (
            f" of {member.origin!r}" if member and member.origin != value.name else ""
        )
        assignment = ", ".join(
            f"{entry.key} = {render_value(entry.value)}"
            for entry in violation.assignment
        )
        raise TheoryError(
            f"{where} violates the law {local!r}{origin} at {assignment}: the left "
            f"side is {render_value(violation.lhs_value)} and the right side is "
            f"{render_value(violation.rhs_value)}",
            line,
            col,
        )
    if verdict.status != "passed":
        raise TheoryError(
            f"{where}: its laws could not be checked exhaustively "
            f"({verdict.incomplete}); use smaller carriers",
            line,
            col,
        )
    return verdict

constructed_model

constructed_model(decl: ModelDecl, source: CheckedModel, view: CheckedView, registry: Mapping[str, TheoryValue]) -> CheckedModel

The reduct or free extension of a model along a view.

PARAMETER DESCRIPTION
decl

The declaration, reduct or free.

TYPE: ModelDecl

source

The model it starts from.

TYPE: CheckedModel

view

The view.

TYPE: CheckedView

registry

Every theory by origin.

TYPE: mapping of str to TheoryValue

RETURNS DESCRIPTION
CheckedModel

A model of the view's domain (reduct) or codomain (free extension), checked against its theory.

RAISES DESCRIPTION
TheoryError

If the source is not a model of the theory the construction starts from, or panproto refuses the construction.

Source code in src/quivers/dsl/theories/models.py
def constructed_model(
    decl: ModelDecl,
    source: CheckedModel,
    view: CheckedView,
    registry: Mapping[str, TheoryValue],
) -> CheckedModel:
    """The reduct or free extension of a model along a view.

    Parameters
    ----------
    decl : ModelDecl
        The declaration, ``reduct`` or ``free``.
    source : CheckedModel
        The model it starts from.
    view : CheckedView
        The view.
    registry : mapping of str to TheoryValue
        Every theory by origin.

    Returns
    -------
    CheckedModel
        A model of the view's domain (reduct) or codomain (free extension),
        checked against its theory.

    Raises
    ------
    TheoryError
        If the source is not a model of the theory the construction starts
        from, or panproto refuses the construction.
    """
    domain = registry[view.domain]
    codomain = registry[view.codomain]
    where = f"model {decl.name!r}"
    refuse_dependent(where, domain, decl.line, decl.col)
    refuse_dependent(where, codomain, decl.line, decl.col)
    if decl.construction == "reduct":
        if source.theory != codomain.name:
            raise TheoryError(
                f"{where}: the reduct along {view.name!r} starts from a model of "
                f"{codomain.name!r}, and {source.name!r} is a model of {source.theory!r}",
                decl.line,
                decl.col,
            )
        try:
            model = reduct_model(view.morphism, domain.theory, source.model)
        except ModelRefused as error:
            raise TheoryError(
                f"{where}: panproto refuses the reduct: {error.message}",
                decl.line,
                decl.col,
            ) from error
        model = model.with_(theory=domain.theory.name)
        check_laws_hold(where, model, domain, decl.line, decl.col)
        return CheckedModel(
            name=decl.name,
            theory=domain.name,
            model=model,
            construction="reduct",
            source=source.name,
            view=view.name,
            line=decl.line,
            col=decl.col,
        )
    if source.theory != domain.name:
        raise TheoryError(
            f"{where}: the free extension along {view.name!r} starts from a model of "
            f"{domain.name!r}, and {source.name!r} is a model of {source.theory!r}",
            decl.line,
            decl.col,
        )
    try:
        extension = sigma_model(
            view.morphism, domain.theory, codomain.theory, source.model, MAX_ELEMENTS
        )
    except ModelRefused as error:
        raise TheoryError(
            f"{where}: panproto refuses the free extension: {error.message}",
            decl.line,
            decl.col,
        ) from error
    model = extension.model.with_(theory=codomain.theory.name)
    check_laws_hold(where, model, codomain, decl.line, decl.col)
    return CheckedModel(
        name=decl.name,
        theory=codomain.name,
        model=model,
        construction="free",
        source=source.name,
        view=view.name,
        unit=extension.unit,
        line=decl.line,
        col=decl.col,
    )

interpreted_model

interpreted_model(decl: ModelDecl, value: TheoryValue, module: QiecModule | None) -> CheckedModel

Build and check a model given by QIEC types and computations.

PARAMETER DESCRIPTION
decl

The declaration, with its interpretations.

TYPE: ModelDecl

value

The theory it interprets.

TYPE: TheoryValue

module

The checked module whose types and computations interpret it, or None when the module declares none.

TYPE: QiecModule or None

RETURNS DESCRIPTION
CheckedModel

The model.

RAISES DESCRIPTION
TheoryError

If a symbol is interpreted twice, not at all, or by something that does not fit its signature; a carrier is not finite; a computation is effectful, fails, or returns a value outside its carrier; or a law of the theory fails in the model, with the assignment.

Source code in src/quivers/dsl/theories/models.py
def interpreted_model(
    decl: ModelDecl, value: TheoryValue, module: QiecModule | None
) -> CheckedModel:
    """Build and check a model given by QIEC types and computations.

    Parameters
    ----------
    decl : ModelDecl
        The declaration, with its interpretations.
    value : TheoryValue
        The theory it interprets.
    module : QiecModule or None
        The checked module whose types and computations interpret it, or
        ``None`` when the module declares none.

    Returns
    -------
    CheckedModel
        The model.

    Raises
    ------
    TheoryError
        If a symbol is interpreted twice, not at all, or by something that
        does not fit its signature; a carrier is not finite; a computation
        is effectful, fails, or returns a value outside its carrier; or a
        law of the theory fails in the model, with the assignment.
    """
    where = f"model {decl.name!r} of {value.name!r}"
    refuse_dependent(where, value, decl.line, decl.col)
    sorts = list(sorts_of(value.theory))
    ops = operations_of(value.theory)
    given: dict[str, tuple[str, int, int]] = {}
    for interpretation in decl.interpretations:
        if interpretation.symbol in given:
            raise TheoryError(
                f"{where} interprets {interpretation.symbol!r} twice",
                interpretation.line,
                interpretation.col,
            )
        if interpretation.symbol not in sorts and interpretation.symbol not in ops:
            raise TheoryError(
                f"{where}: {interpretation.symbol!r} is not a sort or operation of "
                f"{value.name!r}",
                interpretation.line,
                interpretation.col,
            )
        given[interpretation.symbol] = (
            interpretation.value,
            interpretation.line,
            interpretation.col,
        )
    for symbol in (*sorts, *ops):
        if symbol not in given:
            kind = "sort" if symbol in sorts else "operation"
            raise TheoryError(
                f"{where} does not interpret the {kind} {symbol!r}",
                decl.line,
                decl.col,
            )
    if module is None:
        raise TheoryError(
            f"{where}: the module declares no QIEC types or computations to "
            "interpret it by",
            decl.line,
            decl.col,
        )
    carriers: dict[str, tuple[HostValue, ...]] = {}
    carrier_types: dict[str, TypeExpr] = {}
    for sort in sorts:
        type_name, s_line, s_col = given[sort]
        try:
            carrier_types[sort] = named_type(type_name, module)
            carriers[sort] = finite_values(carrier_types[sort], module)
        except CarrierError as error:
            raise TheoryError(
                f"{where}: sort {sort!r} is interpreted by {type_name!r}, which is not "
                f"a finite carrier: {error}",
                s_line,
                s_col,
            ) from error
    records = {
        sort: tuple(value_record(v, module) for v in values)
        for sort, values in carriers.items()
    }
    tables: list[OperationTable] = []
    for op, (_, inputs, output) in ops.items():
        computation_name, o_line, o_col = given[op]
        computation = _computation(module, computation_name)
        if computation is None:
            raise TheoryError(
                f"{where}: operation {op!r} is interpreted by {computation_name!r}, "
                "which is not a computation of the module",
                o_line,
                o_col,
            )
        _check_signature(
            where,
            op,
            computation,
            [carrier_types[s] for s in inputs],
            carrier_types[output],
            o_line,
            o_col,
        )
        allowed = {_key(r) for r in records[output]}
        entries: list[TableEntry] = []
        for arguments in product(*(carriers[s] for s in inputs)):
            result = _run(where, op, module, computation, arguments, o_line, o_col)
            try:
                record = value_record(result, module)
            except CarrierError as error:
                raise TheoryError(
                    f"{where}: operation {op!r} returns {result!r}: {error}",
                    o_line,
                    o_col,
                ) from error
            if _key(record) not in allowed:
                raise TheoryError(
                    f"{where}: operation {op!r} returns {render_value(record)}, which "
                    f"is not in the carrier of {output!r}",
                    o_line,
                    o_col,
                )
            entries.append(
                TableEntry(
                    args=tuple(value_record(a, module) for a in arguments),
                    result=record,
                )
            )
        tables.append(OperationTable(op=op, entries=tuple(entries)))
    model = FiniteModel(
        theory=value.theory.name,
        carriers=tuple(Carrier(sort=s, elements=records[s]) for s in sorts),
        tables=tuple(tables),
    )
    check_laws_hold(where, model, value, decl.line, decl.col)
    return CheckedModel(
        name=decl.name,
        theory=value.name,
        model=model,
        interpretations=tuple(
            SymbolInterpretation(symbol=s, value=given[s][0]) for s in (*sorts, *ops)
        ),
        line=decl.line,
        col=decl.col,
    )

laws_as_equations

laws_as_equations(theory: Theory) -> Theory

A theory whose rules are also stated as equations.

A model satisfies a rule l ~> r when it satisfies l = r, so a model is checked against this theory.

PARAMETER DESCRIPTION
theory

The theory.

TYPE: Theory

RETURNS DESCRIPTION
Theory

The theory with every rule added as an equation of the same name.

Source code in src/quivers/dsl/theories/models.py
def laws_as_equations(theory: panproto.Theory) -> panproto.Theory:
    """A theory whose rules are also stated as equations.

    A model satisfies a rule ``l ~> r`` when it satisfies ``l = r``, so a
    model is checked against this theory.

    Parameters
    ----------
    theory : panproto.Theory
        The theory.

    Returns
    -------
    panproto.Theory
        The theory with every rule added as an equation of the same name.
    """
    spec = theory.to_dict()
    eqs = list(theory.eqs)
    for rule in theory.directed_eqs:
        if isinstance(rule, dict):
            eqs.append({"name": rule["name"], "lhs": rule["lhs"], "rhs": rule["rhs"]})
    spec["eqs"] = eqs
    spec["directed_eqs"] = []
    return panproto.create_theory(spec)

refuse_dependent

refuse_dependent(where: str, value: TheoryValue, line: int, col: int) -> None

Refuse a model of a theory with dependent sorts or implicit inputs.

PARAMETER DESCRIPTION
where

The model, for the refusal.

TYPE: str

value

Its theory.

TYPE: TheoryValue

line

Where the model is declared.

TYPE: int

col

Where the model is declared.

TYPE: int

RAISES DESCRIPTION
TheoryError

If a sort of the theory takes parameters or an operation has an implicit input: checking a finite model of such a theory needs equations with variable contexts and models whose elements carry their sort arguments, which panproto does not provide yet.

Source code in src/quivers/dsl/theories/models.py
def refuse_dependent(where: str, value: TheoryValue, line: int, col: int) -> None:
    """Refuse a model of a theory with dependent sorts or implicit inputs.

    Parameters
    ----------
    where : str
        The model, for the refusal.
    value : TheoryValue
        Its theory.
    line, col : int
        Where the model is declared.

    Raises
    ------
    TheoryError
        If a sort of the theory takes parameters or an operation has an
        implicit input: checking a finite model of such a theory needs
        equations with variable contexts and models whose elements carry
        their sort arguments, which panproto does not provide yet.
    """
    if not is_dependent(value.theory):
        return
    dependent = [s for s, params in sort_parameters(value.theory).items() if params]
    raise TheoryError(
        f"{where}: theory {value.name!r} has dependent sorts "
        f"({', '.join(dependent) or 'implicit inputs'}); a finite model of a "
        "dependent theory needs equations with variable contexts "
        "(panproto/panproto#438) and fibered models (panproto/panproto#439), "
        "which panproto does not provide yet",
        line,
        col,
    )

assemble

assemble(name: str, includes: Sequence[TheoryValue], local: LocalPart, registry: Mapping[str, TheoryValue], *, parameters: tuple[TheoryParameter, ...] = (), line: int = 0, col: int = 0) -> TheoryValue

Compose a presentation from what it includes and what it declares.

PARAMETER DESCRIPTION
name

The presentation's origin.

TYPE: str

includes

The theories it includes directly.

TYPE: sequence of TheoryValue

local

Its own checked declarations.

TYPE: LocalPart

registry

Every theory elaborated so far, by origin.

TYPE: mapping of str to TheoryValue

parameters

Its parameters, for a generic theory.

TYPE: tuple of TheoryParameter DEFAULT: ()

line

Where it is declared.

TYPE: int DEFAULT: 0

col

Where it is declared.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
TheoryValue

The presentation.

RAISES DESCRIPTION
TheoryError

If panproto refuses the colimit, naming both sources of a clash, or a rule system is not confluent or not shown terminating.

Source code in src/quivers/dsl/theories/presentation.py
def assemble(
    name: str,
    includes: Sequence[TheoryValue],
    local: LocalPart,
    registry: Mapping[str, TheoryValue],
    *,
    parameters: tuple[TheoryParameter, ...] = (),
    line: int = 0,
    col: int = 0,
) -> TheoryValue:
    """Compose a presentation from what it includes and what it declares.

    Parameters
    ----------
    name : str
        The presentation's origin.
    includes : sequence of TheoryValue
        The theories it includes directly.
    local : LocalPart
        Its own checked declarations.
    registry : mapping of str to TheoryValue
        Every theory elaborated so far, by origin.
    parameters : tuple of TheoryParameter
        Its parameters, for a generic theory.
    line, col : int
        Where it is declared.

    Returns
    -------
    TheoryValue
        The presentation.

    Raises
    ------
    TheoryError
        If panproto refuses the colimit, naming both sources of a clash,
        or a rule system is not confluent or not shown terminating.
    """
    direct = tuple(dict.fromkeys(i.name for i in includes))
    closure: list[str] = []
    for include in includes:
        for origin in (*include.closure, include.name):
            if origin not in closure:
                closure.append(origin)
    members: dict[tuple[str, str], Member] = {}
    for origin in closure:
        for member in registry[origin].members:
            members.setdefault((member.origin, member.local), member)
    diagram = _Diagram()
    law_nodes: dict[str, str] = {}
    for origin in closure:
        law_nodes[origin] = diagram.node("L", origin, registry[origin].own)
    included_by: dict[str, list[str]] = {}
    for origin in closure:
        for included in registry[origin].includes:
            included_by.setdefault(included, []).append(origin)
    for included, includers in included_by.items():
        signature = diagram.node("S", included, registry[included].signature)
        diagram.edge(signature, law_nodes[included])
        for includer in includers:
            diagram.edge(signature, law_nodes[includer])
    base: panproto.Theory | None = None
    composition: ComposedTheory | None = None
    if closure:
        try:
            composition = compose_diagram(
                diagram.nodes, diagram.edges, result_name=name
            )
        except CompositionRefused as error:
            raise _refusal(error, diagram, name, members, line, col) from error
        base = composed_theory(composition)
    own_members: list[Member] = []
    own_label = ""
    if not local.is_empty():
        mentioned = _mentioned(local, base)
        own_theory = build_local(f"{name}#own", base, local, name, mentioned)
        own_label = diagram.node("own", name, own_theory)
        mentioned_sorts, mentioned_ops = mentioned
        for origin in direct:
            value = registry[origin]
            sorts = set(sorts_of(value.signature)) & mentioned_sorts
            ops = set(operations_of(value.signature)) & mentioned_ops
            if not sorts and not ops:
                continue
            part = diagram.node(
                "R",
                origin,
                restricted(value.signature, f"{origin}#used_by#{name}", sorts, ops),
            )
            diagram.edge(part, law_nodes[origin])
            diagram.edge(part, own_label)
        own_members.extend(
            Member(
                kind="sort",
                name=s.name,
                origin=name,
                local=s.name,
                line=s.line,
                col=s.col,
            )
            for s in local.sorts
        )
        own_members.extend(
            Member(
                kind="op",
                name=o.name,
                origin=name,
                local=o.name,
                line=o.line,
                col=o.col,
            )
            for o in local.operations
        )
        own_members.extend(
            Member(
                kind="rule" if law.oriented else "eq",
                name=law_name(name, law.local),
                origin=name,
                local=law.local,
                line=law.line,
                col=law.col,
            )
            for law in local.laws
        )
        for member in own_members:
            members[(name, member.local)] = member
        try:
            composition = compose_diagram(
                diagram.nodes, diagram.edges, result_name=name
            )
        except CompositionRefused as error:
            raise _refusal(error, diagram, name, members, line, col) from error
    if composition is None:
        flat = panproto.TheoryBuilder(name).build()
    else:
        flat = composed_theory(composition)
    all_members: list[Member] = []
    for origin in closure:
        for member in registry[origin].own_members():
            all_members.append(
                _law_image(member, composition, law_nodes[origin], name, line, col)
            )
    if not local.is_empty():
        own_members = [
            _law_image(member, composition, own_label, name, line, col)
            for member in own_members
        ]
    all_members.extend(own_members)
    own_law_names = {m.name for m in own_members if m.kind in ("eq", "rule")}
    eqs, directed = law_entries(flat, own_law_names)
    value = TheoryValue(
        name=name,
        theory=flat,
        own=with_laws(flat, name, eqs, directed),
        signature=with_laws(flat, f"{name}#signature", [], []),
        members=tuple(all_members),
        includes=direct,
        closure=tuple(closure),
        parameters=parameters,
        composition=composition,
        line=line,
        col=col,
    )
    return value.with_(rules=check_rules(value, local.assume_terminating))

build_local

build_local(name: str, base: Theory | None, local: LocalPart, origin: str, mentioned: tuple[set[str], set[str]]) -> Theory

The theory of a presentation's own declarations.

PARAMETER DESCRIPTION
name

The theory's name.

TYPE: str

base

The colimit of the included theories, whose mentioned sorts and operations are declared first.

TYPE: Theory or None

local

The own declarations.

TYPE: LocalPart

origin

The origin the own laws are qualified by.

TYPE: str

mentioned

The included sorts and operations the own declarations mention, closed under what their signatures mention.

TYPE: tuple of two sets of str

RETURNS DESCRIPTION
Theory

The mentioned included symbols, the own symbols, and the own laws.

Source code in src/quivers/dsl/theories/presentation.py
def build_local(
    name: str,
    base: panproto.Theory | None,
    local: LocalPart,
    origin: str,
    mentioned: tuple[set[str], set[str]],
) -> panproto.Theory:
    """The theory of a presentation's own declarations.

    Parameters
    ----------
    name : str
        The theory's name.
    base : panproto.Theory or None
        The colimit of the included theories, whose mentioned sorts and
        operations are declared first.
    local : LocalPart
        The own declarations.
    origin : str
        The origin the own laws are qualified by.
    mentioned : tuple of two sets of str
        The included sorts and operations the own declarations mention,
        closed under what their signatures mention.

    Returns
    -------
    panproto.Theory
        The mentioned included symbols, the own symbols, and the own laws.
    """
    mentioned_sorts, mentioned_ops = mentioned
    sorts: list[Json] = []
    ops: list[Json] = []
    if base is not None:
        sorts = [s for s in base.sorts if _sort_name(s) in mentioned_sorts]
        ops = [o for o in base.ops if operation_signature(o)[0] in mentioned_ops]
    sorts.extend(s.entry for s in local.sorts)
    ops.extend(o.entry for o in local.operations)
    eqs: list[Json] = []
    directed: list[Json] = []
    for law in local.laws:
        qualified = law_name(origin, law.local)
        if law.oriented:
            directed.append(
                {
                    "name": qualified,
                    "lhs": law.lhs,
                    "rhs": law.rhs,
                    "impl_term": _expression(law.rhs),
                    "inverse": None,
                    "source_kind": None,
                    "target_kind": None,
                    "coercion_class": "Opaque",
                }
            )
        else:
            eqs.append({"name": qualified, "lhs": law.lhs, "rhs": law.rhs})
    return panproto.create_theory(
        {
            "name": name,
            "extends": [],
            "sorts": sorts,
            "ops": ops,
            "eqs": eqs,
            "directed_eqs": directed,
            "policies": [],
        }
    )

check_laws

check_laws(owner: str, equations: Sequence[EquationDecl], signature: Signature) -> tuple[LocalLaw, ...]

Check a theory's equations and rules over its signature.

Each side is resolved and sort-checked by the equation checker of binding signatures (quivers.structural.rewriting.make_equation): a bare name is an operation when the signature declares one and a variable otherwise, both sides have one sort, and every variable of a rule's right side occurs on its left. For a theory with dependent sorts the check is of the sorts' heads; panproto typechecks the arguments when the theory is composed.

PARAMETER DESCRIPTION
owner

The theory, for refusals.

TYPE: str

equations

The declared equations and rules.

TYPE: sequence of EquationDecl

signature

The theory's signature, included symbols and own together.

TYPE: Signature

RETURNS DESCRIPTION
tuple of LocalLaw

The checked laws, serialized.

RAISES DESCRIPTION
TheoryError

If two laws share a name, or a law is ill-sorted or not first order, located at the law.

Source code in src/quivers/dsl/theories/presentation.py
def check_laws(
    owner: str,
    equations: Sequence[EquationDecl],
    signature: Signature,
) -> tuple[LocalLaw, ...]:
    """Check a theory's equations and rules over its signature.

    Each side is resolved and sort-checked by the equation checker of
    binding signatures (`quivers.structural.rewriting.make_equation`): a
    bare name is an operation when the signature declares one and a
    variable otherwise, both sides have one sort, and every variable of a
    rule's right side occurs on its left. For a theory with dependent
    sorts the check is of the sorts' heads; panproto typechecks the
    arguments when the theory is composed.

    Parameters
    ----------
    owner : str
        The theory, for refusals.
    equations : sequence of EquationDecl
        The declared equations and rules.
    signature : Signature
        The theory's signature, included symbols and own together.

    Returns
    -------
    tuple of LocalLaw
        The checked laws, serialized.

    Raises
    ------
    TheoryError
        If two laws share a name, or a law is ill-sorted or not first
        order, located at the law.
    """
    seen: set[str] = set()
    laws: list[LocalLaw] = []
    for equation in equations:
        if equation.name in seen:
            raise TheoryError(
                f"theory {owner!r} declares the law {equation.name!r} twice",
                equation.line,
                equation.col,
            )
        seen.add(equation.name)
        where = f"theory {owner!r}, law {equation.name!r}"
        try:
            left = resolve(equation.left, signature)
            right = resolve(equation.right, signature)
            if not isinstance(
                left, PatternApplication | Metavariable
            ) or not isinstance(right, PatternApplication | Metavariable):
                raise TheoryError(
                    f"{where}: a law relates terms of the theory's operations and "
                    "variables, not literals",
                    equation.line,
                    equation.col,
                )
            make_equation(
                equation.name,
                left,
                right,
                signature,
                oriented=equation.oriented,
                line=equation.line,
                col=equation.col,
            )
        except (PatternError, RewriteError) as error:
            raise TheoryError(
                f"{where}: {error}", equation.line, equation.col
            ) from error
        laws.append(
            LocalLaw(
                local=equation.name,
                sides=json.dumps(
                    [
                        _term_json(left, where, equation.line, equation.col),
                        _term_json(right, where, equation.line, equation.col),
                    ]
                ),
                oriented=equation.oriented,
                line=equation.line,
                col=equation.col,
            )
        )
    return tuple(laws)

check_rules

check_rules(value: TheoryValue, assume_terminating: bool) -> RuleCheck

Check the confluence and termination of a theory's rules.

PARAMETER DESCRIPTION
value

The theory.

TYPE: TheoryValue

assume_terminating

Whether the theory assumes its rules terminate.

TYPE: bool

RETURNS DESCRIPTION
RuleCheck

Confluence is established when every critical pair joins; termination is established by the lexicographic path ordering or recorded as assumed.

RAISES DESCRIPTION
TheoryError

If a critical pair does not join, or a rule is not oriented by the path ordering and termination is not assumed, located at the rule.

Source code in src/quivers/dsl/theories/presentation.py
def check_rules(value: TheoryValue, assume_terminating: bool) -> RuleCheck:
    """Check the confluence and termination of a theory's rules.

    Parameters
    ----------
    value : TheoryValue
        The theory.
    assume_terminating : bool
        Whether the theory assumes its rules terminate.

    Returns
    -------
    RuleCheck
        Confluence is established when every critical pair joins;
        termination is established by the lexicographic path ordering or
        recorded as assumed.

    Raises
    ------
    TheoryError
        If a critical pair does not join, or a rule is not oriented by the
        path ordering and termination is not assumed, located at the rule.
    """
    if not value.theory.directed_eqs:
        return RuleCheck()
    report = rewrite_system_report(value.theory)
    for pair in report.critical_pairs:
        if not pair.joins:
            member = value.member("rule", pair.rule_a)
            raise TheoryError(
                f"theory {value.name!r}: the rules {_local(value, pair.rule_a)!r} and "
                f"{_local(value, pair.rule_b)!r} overlap in a critical pair whose "
                f"sides {pair.left} and {pair.right} do not rewrite to a common "
                "term, so the rules are not confluent",
                member.line if member else value.line,
                member.col if member else value.col,
            )
    if report.termination_violations:
        if assume_terminating:
            return RuleCheck(termination="assumed")
        violation = report.termination_violations[0]
        member = value.member("rule", violation.rule)
        raise TheoryError(
            f"theory {value.name!r}: termination of the rule "
            f"{_local(value, violation.rule)!r} is not shown by the lexicographic "
            f"path ordering ({violation.reason}); write `assume terminating` in the "
            "equations block to record it as an assumption",
            member.line if member else value.line,
            member.col if member else value.col,
        )
    return RuleCheck(termination="assumed" if assume_terminating else "established")

first_order_signature

first_order_signature(name: str, sorts: Sequence[str], ops: Mapping[str, tuple[tuple[str, ...], str]]) -> Signature

The binding signature of a presentation's erasure.

PARAMETER DESCRIPTION
name

The signature's name.

TYPE: str

sorts

Its sorts, by name.

TYPE: sequence of str

ops

Each operation's explicit inputs' sorts and output sort, by their heads.

TYPE: mapping of str to (input sorts, output sort)

RETURNS DESCRIPTION
Signature

A signature whose sorts are object sorts and whose constructors bind nothing, so that the equation checker of binding signatures checks the presentation's equations up to the arguments of dependent sorts, which panproto's typechecker then checks.

Source code in src/quivers/dsl/theories/presentation.py
def first_order_signature(
    name: str, sorts: Sequence[str], ops: Mapping[str, tuple[tuple[str, ...], str]]
) -> Signature:
    """The binding signature of a presentation's erasure.

    Parameters
    ----------
    name : str
        The signature's name.
    sorts : sequence of str
        Its sorts, by name.
    ops : mapping of str to (input sorts, output sort)
        Each operation's explicit inputs' sorts and output sort, by their
        heads.

    Returns
    -------
    Signature
        A signature whose sorts are object sorts and whose constructors
        bind nothing, so that the equation checker of binding signatures
        checks the presentation's equations up to the arguments of
        dependent sorts, which panproto's typechecker then checks.
    """
    return Signature(
        name=name,
        sorts_t=tuple(Sort(name=s, kind="object") for s in sorts),
        constructors_t=tuple(
            Constructor(name=op, domain=inputs, codomain=output)
            for op, (inputs, output) in ops.items()
        ),
    )

input_names

input_names(arity: int) -> list[str]

The names panproto gives an operation's unnamed inputs.

PARAMETER DESCRIPTION
arity

The number of inputs.

TYPE: int

RETURNS DESCRIPTION
list of str

x0, x1, ...: an unnamed input is positional, and a derived term refers to it by this name.

Source code in src/quivers/dsl/theories/presentation.py
def input_names(arity: int) -> list[str]:
    """The names panproto gives an operation's unnamed inputs.

    Parameters
    ----------
    arity : int
        The number of inputs.

    Returns
    -------
    list of str
        ``x0``, ``x1``, ...: an unnamed input is positional, and a derived
        term refers to it by this name.
    """
    return [f"x{index}" for index in range(arity)]

is_dependent

is_dependent(theory: Theory) -> bool

Whether a theory has a sort with parameters or an implicit input.

PARAMETER DESCRIPTION
theory

The theory.

TYPE: Theory

RETURNS DESCRIPTION
bool

Whether some sort takes parameters or some operation has an implicit input.

Source code in src/quivers/dsl/theories/presentation.py
def is_dependent(theory: panproto.Theory) -> bool:
    """Whether a theory has a sort with parameters or an implicit input.

    Parameters
    ----------
    theory : panproto.Theory
        The theory.

    Returns
    -------
    bool
        Whether some sort takes parameters or some operation has an
        implicit input.
    """
    return any(sort_parameters(theory).values()) or any(
        implicit for entry in theory.ops for _, _, implicit in operation_inputs(entry)
    )

law_entries

law_entries(theory: Theory, names: set[str]) -> tuple[list[Json], list[Json]]

The serialized equations and rules of a theory with given names.

PARAMETER DESCRIPTION
theory

The theory.

TYPE: Theory

names

The laws kept.

TYPE: set of str

RETURNS DESCRIPTION
tuple of two lists

The equations and the rules, in declaration order.

Source code in src/quivers/dsl/theories/presentation.py
def law_entries(
    theory: panproto.Theory, names: set[str]
) -> tuple[list[Json], list[Json]]:
    """The serialized equations and rules of a theory with given names.

    Parameters
    ----------
    theory : panproto.Theory
        The theory.
    names : set of str
        The laws kept.

    Returns
    -------
    tuple of two lists
        The equations and the rules, in declaration order.
    """
    eqs = [e for e in theory.eqs if isinstance(e, dict) and e.get("name") in names]
    directed = [
        e for e in theory.directed_eqs if isinstance(e, dict) and e.get("name") in names
    ]
    return eqs, directed

law_name

law_name(origin: str, local: str) -> str

The flat name of a law: its local name qualified by its origin.

PARAMETER DESCRIPTION
origin

The theory that declares it.

TYPE: str

local

Its name as declared.

TYPE: str

RETURNS DESCRIPTION
str

origin.local, so two origins' laws never share a name.

Source code in src/quivers/dsl/theories/presentation.py
def law_name(origin: str, local: str) -> str:
    """The flat name of a law: its local name qualified by its origin.

    Parameters
    ----------
    origin : str
        The theory that declares it.
    local : str
        Its name as declared.

    Returns
    -------
    str
        ``origin.local``, so two origins' laws never share a name.
    """
    return f"{origin}.{local}"

operation_entries

operation_entries(theory: Theory) -> dict[str, Json]

The serialized operations of a theory, by name.

PARAMETER DESCRIPTION
theory

The theory.

TYPE: Theory

RETURNS DESCRIPTION
dict of str to Json

Each operation as panproto serializes it.

Source code in src/quivers/dsl/theories/presentation.py
def operation_entries(theory: panproto.Theory) -> dict[str, Json]:
    """The serialized operations of a theory, by name.

    Parameters
    ----------
    theory : panproto.Theory
        The theory.

    Returns
    -------
    dict of str to Json
        Each operation as panproto serializes it.
    """
    return {operation_signature(e)[0]: e for e in theory.ops}

operation_entry

operation_entry(name: str, inputs: Sequence[tuple[str, Json, bool]], output: Json) -> Json

An operation in panproto's serialized shape.

PARAMETER DESCRIPTION
name

The operation.

TYPE: str

inputs

Each input's name, sort expression, and whether it is implicit.

TYPE: sequence of (str, Json, bool)

output

The output sort expression.

TYPE: Json

RETURNS DESCRIPTION
Json

The serialized operation.

Source code in src/quivers/dsl/theories/presentation.py
def operation_entry(
    name: str, inputs: Sequence[tuple[str, Json, bool]], output: Json
) -> Json:
    """An operation in panproto's serialized shape.

    Parameters
    ----------
    name : str
        The operation.
    inputs : sequence of (str, Json, bool)
        Each input's name, sort expression, and whether it is implicit.
    output : Json
        The output sort expression.

    Returns
    -------
    Json
        The serialized operation.
    """
    return {
        "name": name,
        "inputs": [[n, s, "Yes" if implicit else "No"] for n, s, implicit in inputs],
        "output": output,
    }

operation_inputs

operation_inputs(entry: Json) -> list[tuple[str, Json, bool]]

Every input of a serialized operation.

PARAMETER DESCRIPTION
entry

The operation in panproto's serialized shape.

TYPE: Json

RETURNS DESCRIPTION
list of (str, Json, bool)

Each input's name, sort expression, and whether it is implicit.

RAISES DESCRIPTION
ValueError

If the entry is not an operation.

Source code in src/quivers/dsl/theories/presentation.py
def operation_inputs(entry: Json) -> list[tuple[str, Json, bool]]:
    """Every input of a serialized operation.

    Parameters
    ----------
    entry : Json
        The operation in panproto's serialized shape.

    Returns
    -------
    list of (str, Json, bool)
        Each input's name, sort expression, and whether it is implicit.

    Raises
    ------
    ValueError
        If the entry is not an operation.
    """
    inputs = entry.get("inputs") if isinstance(entry, dict) else None
    if not isinstance(inputs, list):
        raise ValueError(f"not a serialized operation: {entry!r}")
    found: list[tuple[str, Json, bool]] = []
    for item in inputs:
        if not isinstance(item, list | tuple) or len(item) != 3:
            raise ValueError(f"not an operation input: {item!r}")
        name, sort, implicit = item
        if not isinstance(name, str):
            raise ValueError(f"not an operation input: {item!r}")
        found.append((name, sort, implicit == "Yes"))
    return found

operation_signature

operation_signature(entry: Json) -> tuple[str, tuple[str, ...], tuple[str, ...], str]

Read a serialized operation's explicit signature.

PARAMETER DESCRIPTION
entry

An operation in panproto's serialized shape.

TYPE: Json

RETURNS DESCRIPTION
tuple

Its name, the names and sorts (by their head) of its explicit inputs, which its applications take as arguments, and its output sort's head. Implicit inputs are inferred where it is applied.

RAISES DESCRIPTION
ValueError

If the entry is not an operation.

Source code in src/quivers/dsl/theories/presentation.py
def operation_signature(
    entry: Json,
) -> tuple[str, tuple[str, ...], tuple[str, ...], str]:
    """Read a serialized operation's explicit signature.

    Parameters
    ----------
    entry : Json
        An operation in panproto's serialized shape.

    Returns
    -------
    tuple
        Its name, the names and sorts (by their head) of its explicit
        inputs, which its applications take as arguments, and its output
        sort's head. Implicit inputs are inferred where it is applied.

    Raises
    ------
    ValueError
        If the entry is not an operation.
    """
    if not isinstance(entry, dict) or not isinstance(entry.get("name"), str):
        raise ValueError(f"not a serialized operation: {entry!r}")
    explicit = [(n, s) for n, s, implicit in operation_inputs(entry) if not implicit]
    return (
        str(entry["name"]),
        tuple(n for n, _ in explicit),
        tuple(sort_head(s) for _, s in explicit),
        sort_head(entry.get("output")),
    )

operations_of

operations_of(theory: Theory) -> dict[str, tuple[tuple[str, ...], tuple[str, ...], str]]

The explicit signatures of a theory's operations.

PARAMETER DESCRIPTION
theory

The theory.

TYPE: Theory

RETURNS DESCRIPTION
dict

Each operation's explicit input names, their sorts' heads, and its output sort's head, by name.

Source code in src/quivers/dsl/theories/presentation.py
def operations_of(
    theory: panproto.Theory,
) -> dict[str, tuple[tuple[str, ...], tuple[str, ...], str]]:
    """The explicit signatures of a theory's operations.

    Parameters
    ----------
    theory : panproto.Theory
        The theory.

    Returns
    -------
    dict
        Each operation's explicit input names, their sorts' heads, and its
        output sort's head, by name.
    """
    found: dict[str, tuple[tuple[str, ...], tuple[str, ...], str]] = {}
    for entry in theory.ops:
        name, names, sorts, output = operation_signature(entry)
        found[name] = (names, sorts, output)
    return found

rename_operation_entry

rename_operation_entry(entry: Json, sorts: Mapping[str, str], ops: Mapping[str, str]) -> Json

A serialized operation with sorts and operations renamed.

PARAMETER DESCRIPTION
entry

The operation.

TYPE: Json

sorts

New names of sorts.

TYPE: mapping of str to str

ops

New names of operations.

TYPE: mapping of str to str

RETURNS DESCRIPTION
Json

The renamed operation.

Source code in src/quivers/dsl/theories/presentation.py
def rename_operation_entry(
    entry: Json, sorts: Mapping[str, str], ops: Mapping[str, str]
) -> Json:
    """A serialized operation with sorts and operations renamed.

    Parameters
    ----------
    entry : Json
        The operation.
    sorts : mapping of str to str
        New names of sorts.
    ops : mapping of str to str
        New names of operations.

    Returns
    -------
    Json
        The renamed operation.
    """
    name = str(entry["name"]) if isinstance(entry, dict) else ""
    output = entry["output"] if isinstance(entry, dict) else None
    return operation_entry(
        ops.get(name, name),
        [
            (n, rename_sort_expression(s, sorts, ops), implicit)
            for n, s, implicit in operation_inputs(entry)
        ],
        rename_sort_expression(output, sorts, ops),
    )

rename_sort_entry

rename_sort_entry(entry: Json, sorts: Mapping[str, str], ops: Mapping[str, str]) -> Json

A serialized sort with sorts and operations renamed.

PARAMETER DESCRIPTION
entry

The sort.

TYPE: Json

sorts

New names of sorts.

TYPE: mapping of str to str

ops

New names of operations.

TYPE: mapping of str to str

RETURNS DESCRIPTION
Json

The renamed sort.

Source code in src/quivers/dsl/theories/presentation.py
def rename_sort_entry(
    entry: Json, sorts: Mapping[str, str], ops: Mapping[str, str]
) -> Json:
    """A serialized sort with sorts and operations renamed.

    Parameters
    ----------
    entry : Json
        The sort.
    sorts : mapping of str to str
        New names of sorts.
    ops : mapping of str to str
        New names of operations.

    Returns
    -------
    Json
        The renamed sort.
    """
    name = _sort_name(entry)
    return sort_entry(
        sorts.get(name, name),
        [
            (p, rename_sort_expression(s, sorts, ops))
            for p, s in sort_parameters_of(entry)
        ],
    )

rename_sort_expression

rename_sort_expression(expression: Json, sorts: Mapping[str, str], ops: Mapping[str, str]) -> Json

A serialized sort expression with sorts and operations renamed.

PARAMETER DESCRIPTION
expression

The sort expression.

TYPE: Json

sorts

New names of sorts.

TYPE: mapping of str to str

ops

New names of operations.

TYPE: mapping of str to str

RETURNS DESCRIPTION
Json

The renamed expression.

Source code in src/quivers/dsl/theories/presentation.py
def rename_sort_expression(
    expression: Json, sorts: Mapping[str, str], ops: Mapping[str, str]
) -> Json:
    """A serialized sort expression with sorts and operations renamed.

    Parameters
    ----------
    expression : Json
        The sort expression.
    sorts : mapping of str to str
        New names of sorts.
    ops : mapping of str to str
        New names of operations.

    Returns
    -------
    Json
        The renamed expression.
    """
    head = sort_head(expression)
    arguments = sort_arguments(expression)
    if not arguments:
        return sorts.get(head, head)
    return {
        "name": sorts.get(head, head),
        "args": [rename_term(a, ops) for a in arguments],
    }

rename_term

rename_term(term: Json, ops: Mapping[str, str]) -> Json

A serialized term with operations renamed.

PARAMETER DESCRIPTION
term

The term.

TYPE: Json

ops

New names of operations; others keep theirs.

TYPE: mapping of str to str

RETURNS DESCRIPTION
Json

The renamed term.

Source code in src/quivers/dsl/theories/presentation.py
def rename_term(term: Json, ops: Mapping[str, str]) -> Json:
    """A serialized term with operations renamed.

    Parameters
    ----------
    term : Json
        The term.
    ops : mapping of str to str
        New names of operations; others keep theirs.

    Returns
    -------
    Json
        The renamed term.
    """
    if isinstance(term, dict):
        application = term.get("App")
        if isinstance(application, dict):
            op = str(application.get("op"))
            args = application.get("args")
            return {
                "App": {
                    "op": ops.get(op, op),
                    "args": [
                        rename_term(a, ops)
                        for a in (args if isinstance(args, list) else [])
                    ],
                }
            }
    return term

restricted

restricted(theory: Theory, name: str, sorts: set[str], ops: set[str]) -> Theory

A law-free theory of some of a theory's sorts and operations.

PARAMETER DESCRIPTION
theory

The theory.

TYPE: Theory

name

The restriction's name.

TYPE: str

sorts

The sorts kept, with every sort and operation they mention.

TYPE: set of str

ops

The operations kept, with every sort and operation they mention.

TYPE: set of str

RETURNS DESCRIPTION
Theory

The restriction, in the theory's declaration order.

Source code in src/quivers/dsl/theories/presentation.py
def restricted(
    theory: panproto.Theory, name: str, sorts: set[str], ops: set[str]
) -> panproto.Theory:
    """A law-free theory of some of a theory's sorts and operations.

    Parameters
    ----------
    theory : panproto.Theory
        The theory.
    name : str
        The restriction's name.
    sorts : set of str
        The sorts kept, with every sort and operation they mention.
    ops : set of str
        The operations kept, with every sort and operation they mention.

    Returns
    -------
    panproto.Theory
        The restriction, in the theory's declaration order.
    """
    sorts, ops = _closed_symbols(theory, sorts, ops)
    spec = theory.to_dict()
    spec["name"] = name
    spec["sorts"] = [s for s in theory.sorts if _sort_name(s) in sorts]
    spec["ops"] = [o for o in theory.ops if operation_signature(o)[0] in ops]
    spec["eqs"] = []
    spec["directed_eqs"] = []
    return panproto.create_theory(spec)

signature_of

signature_of(value: TheoryValue, extra: LocalPart | None = None) -> Signature

The first-order binding signature of a theory, with extra declarations.

PARAMETER DESCRIPTION
value

The theory whose sorts and operations it holds.

TYPE: TheoryValue or None

extra

Further sorts and operations.

TYPE: LocalPart or None DEFAULT: None

RETURNS DESCRIPTION
Signature

The signature the equation checker resolves terms against.

Source code in src/quivers/dsl/theories/presentation.py
def signature_of(value: TheoryValue, extra: LocalPart | None = None) -> Signature:
    """The first-order binding signature of a theory, with extra declarations.

    Parameters
    ----------
    value : TheoryValue or None
        The theory whose sorts and operations it holds.
    extra : LocalPart or None
        Further sorts and operations.

    Returns
    -------
    Signature
        The signature the equation checker resolves terms against.
    """
    sorts = list(sorts_of(value.theory))
    ops = {op: (s, out) for op, (_, s, out) in operations_of(value.theory).items()}
    if extra is not None:
        sorts.extend(s.name for s in extra.sorts if s.name not in sorts)
        for operation in extra.operations:
            _, _, inputs, output = operation_signature(operation.entry)
            ops[operation.name] = (inputs, output)
    return first_order_signature(value.name, sorts, ops)

sort_arguments

sort_arguments(expression: Json) -> list[Json]

The argument terms of a sort expression.

PARAMETER DESCRIPTION
expression

A serialized sort expression.

TYPE: Json

RETURNS DESCRIPTION
list of Json

Its argument terms, empty for a plain sort.

Source code in src/quivers/dsl/theories/presentation.py
def sort_arguments(expression: Json) -> list[Json]:
    """The argument terms of a sort expression.

    Parameters
    ----------
    expression : Json
        A serialized sort expression.

    Returns
    -------
    list of Json
        Its argument terms, empty for a plain sort.
    """
    if isinstance(expression, dict) and isinstance(expression.get("args"), list):
        args = expression["args"]
        assert isinstance(args, list)
        return list(args)
    return []

sort_entries

sort_entries(theory: Theory) -> dict[str, Json]

The serialized sorts of a theory, by name.

PARAMETER DESCRIPTION
theory

The theory.

TYPE: Theory

RETURNS DESCRIPTION
dict of str to Json

Each sort as panproto serializes it.

Source code in src/quivers/dsl/theories/presentation.py
def sort_entries(theory: panproto.Theory) -> dict[str, Json]:
    """The serialized sorts of a theory, by name.

    Parameters
    ----------
    theory : panproto.Theory
        The theory.

    Returns
    -------
    dict of str to Json
        Each sort as panproto serializes it.
    """
    return {_sort_name(e): e for e in theory.sorts}

sort_entry

sort_entry(name: str, parameters: Sequence[tuple[str, Json]] = ()) -> Json

A sort in panproto's serialized shape.

PARAMETER DESCRIPTION
name

The sort.

TYPE: str

parameters

Its parameters and their sort expressions, for a dependent sort.

TYPE: sequence of (str, Json) DEFAULT: ()

RETURNS DESCRIPTION
Json

The serialized sort.

Source code in src/quivers/dsl/theories/presentation.py
def sort_entry(name: str, parameters: Sequence[tuple[str, Json]] = ()) -> Json:
    """A sort in panproto's serialized shape.

    Parameters
    ----------
    name : str
        The sort.
    parameters : sequence of (str, Json)
        Its parameters and their sort expressions, for a dependent sort.

    Returns
    -------
    Json
        The serialized sort.
    """
    return {
        "name": name,
        "params": [{"name": p, "sort": s} for p, s in parameters],
        "kind": "Structural",
        "closure": "Open",
    }

sort_head

sort_head(expression: Json) -> str

The sort a sort expression applies.

PARAMETER DESCRIPTION
expression

A serialized sort expression: a name, or {"name", "args"}.

TYPE: Json

RETURNS DESCRIPTION
str

The sort's name.

RAISES DESCRIPTION
ValueError

If the value is not a sort expression.

Source code in src/quivers/dsl/theories/presentation.py
def sort_head(expression: Json) -> str:
    """The sort a sort expression applies.

    Parameters
    ----------
    expression : Json
        A serialized sort expression: a name, or ``{"name", "args"}``.

    Returns
    -------
    str
        The sort's name.

    Raises
    ------
    ValueError
        If the value is not a sort expression.
    """
    if isinstance(expression, str):
        return expression
    if isinstance(expression, dict) and isinstance(expression.get("name"), str):
        return str(expression["name"])
    raise ValueError(f"not a serialized sort expression: {expression!r}")

sort_parameters

sort_parameters(theory: Theory) -> dict[str, tuple[tuple[str, Json], ...]]

The parameters of each sort of a theory.

PARAMETER DESCRIPTION
theory

The theory.

TYPE: Theory

RETURNS DESCRIPTION
dict

Each sort's parameters as (name, serialized sort) pairs, empty for a sort without parameters.

Source code in src/quivers/dsl/theories/presentation.py
def sort_parameters(theory: panproto.Theory) -> dict[str, tuple[tuple[str, Json], ...]]:
    """The parameters of each sort of a theory.

    Parameters
    ----------
    theory : panproto.Theory
        The theory.

    Returns
    -------
    dict
        Each sort's parameters as (name, serialized sort) pairs, empty for a
        sort without parameters.
    """
    return {_sort_name(e): tuple(sort_parameters_of(e)) for e in theory.sorts}

sort_parameters_of

sort_parameters_of(entry: Json) -> list[tuple[str, Json]]

The parameters of one serialized sort.

PARAMETER DESCRIPTION
entry

The sort.

TYPE: Json

RETURNS DESCRIPTION
list of (str, Json)

Each parameter's name and sort expression.

RAISES DESCRIPTION
ValueError

If the parameters are not serialized as panproto writes them.

Source code in src/quivers/dsl/theories/presentation.py
def sort_parameters_of(entry: Json) -> list[tuple[str, Json]]:
    """The parameters of one serialized sort.

    Parameters
    ----------
    entry : Json
        The sort.

    Returns
    -------
    list of (str, Json)
        Each parameter's name and sort expression.

    Raises
    ------
    ValueError
        If the parameters are not serialized as panproto writes them.
    """
    params = entry.get("params", []) if isinstance(entry, dict) else []
    if not isinstance(params, list):
        raise ValueError(f"not serialized sort parameters: {params!r}")
    found: list[tuple[str, Json]] = []
    for param in params:
        if not isinstance(param, dict) or not isinstance(param.get("name"), str):
            raise ValueError(f"not a serialized sort parameter: {param!r}")
        found.append((str(param["name"]), param.get("sort")))
    return found

sorts_of

sorts_of(theory: Theory) -> tuple[str, ...]

The sorts of a theory.

PARAMETER DESCRIPTION
theory

The theory.

TYPE: Theory

RETURNS DESCRIPTION
tuple of str

Its sorts, in declaration order.

Source code in src/quivers/dsl/theories/presentation.py
def sorts_of(theory: panproto.Theory) -> tuple[str, ...]:
    """The sorts of a theory.

    Parameters
    ----------
    theory : panproto.Theory
        The theory.

    Returns
    -------
    tuple of str
        Its sorts, in declaration order.
    """
    return tuple(_sort_name(s) for s in theory.sorts)

with_laws

with_laws(theory: Theory, name: str, eqs: list[Json], directed: list[Json]) -> Theory

A theory's signature with given laws in place of its own.

PARAMETER DESCRIPTION
theory

The theory whose sorts and operations are kept.

TYPE: Theory

name

The new theory's name.

TYPE: str

eqs

Its equations, serialized.

TYPE: list of Json

directed

Its rules, serialized.

TYPE: list of Json

RETURNS DESCRIPTION
Theory

The theory.

Source code in src/quivers/dsl/theories/presentation.py
def with_laws(
    theory: panproto.Theory, name: str, eqs: list[Json], directed: list[Json]
) -> panproto.Theory:
    """A theory's signature with given laws in place of its own.

    Parameters
    ----------
    theory : panproto.Theory
        The theory whose sorts and operations are kept.
    name : str
        The new theory's name.
    eqs : list of Json
        Its equations, serialized.
    directed : list of Json
        Its rules, serialized.

    Returns
    -------
    panproto.Theory
        The theory.
    """
    spec = theory.to_dict()
    spec["name"] = name
    spec["eqs"] = eqs
    spec["directed_eqs"] = directed
    return panproto.create_theory(spec)

search_refutation

search_refutation(base: TheoryValue, extension: TheoryValue, bound: int) -> SearchResult

Search the models of an included theory, up to a size bound, for one with no expansion to the extension.

PARAMETER DESCRIPTION
base

The included theory, every sort without parameters.

TYPE: TheoryValue

extension

A theory that includes it.

TYPE: TheoryValue

bound

The most elements a carrier may have; every size vector from one element per sort up to bound per sort is tried, smallest total first.

TYPE: int

RETURNS DESCRIPTION
SearchResult

The first model found whose free extension identifies two of its elements, or the number of models examined without one.

RAISES DESCRIPTION
ValueError

If bound is less than one.

Source code in src/quivers/dsl/theories/search.py
def search_refutation(
    base: TheoryValue, extension: TheoryValue, bound: int
) -> SearchResult:
    """Search the models of an included theory, up to a size bound, for one
    with no expansion to the extension.

    Parameters
    ----------
    base : TheoryValue
        The included theory, every sort without parameters.
    extension : TheoryValue
        A theory that includes it.
    bound : int
        The most elements a carrier may have; every size vector from one
        element per sort up to ``bound`` per sort is tried, smallest total
        first.

    Returns
    -------
    SearchResult
        The first model found whose free extension identifies two of its
        elements, or the number of models examined without one.

    Raises
    ------
    ValueError
        If ``bound`` is less than one.
    """
    if bound < 1:
        raise ValueError(f"a search bound is a positive number, not {bound}")
    sorts = list(sorts_of(base.theory))
    inclusion = inclusion_view(f"{base.name}#into#{extension.name}", base, extension)
    checked = laws_as_equations(base.theory)
    vectors = sorted(
        product(range(1, bound + 1), repeat=len(sorts)), key=lambda v: (sum(v), v)
    )
    examined = 0
    for vector in vectors:
        sizes = dict(zip(sorts, vector, strict=True))
        for tables in _models(base, sizes):
            if examined >= MAX_SEARCHED_MODELS:
                return SearchResult(bound=bound, models=examined, exhausted=False)
            model = _finite_model(base, sizes, tables)
            if verify_model(model, checked, MAX_ASSIGNMENTS).status != "passed":
                continue
            examined += 1
            try:
                free = sigma_model(
                    inclusion, base.theory, extension.theory, model, MAX_ELEMENTS
                )
            except ModelRefused:
                continue
            images: dict[tuple[str, str], int] = {}
            for pair in free.unit:
                if not isinstance(pair.element, IntValue):
                    continue
                key = (pair.sort, pair.image.model_dump_json())
                seen = images.get(key)
                if seen is not None and seen != pair.element.value:
                    return SearchResult(
                        bound=bound,
                        models=examined,
                        witness=ExtensionWitness(
                            model=f"the model found by search ({_describe(sizes, tables)})",
                            sort=pair.sort,
                            left=str(seen),
                            right=str(pair.element.value),
                        ),
                    )
                images[key] = pair.element.value
    return SearchResult(bound=bound, models=examined)

own_signature

own_signature(decl: TheoryDecl, base: TheoryValue) -> LocalPart

The sorts and operations a theory declaration declares itself.

PARAMETER DESCRIPTION
decl

The declaration.

TYPE: TheoryDecl

base

The colimit of the theories it includes.

TYPE: TheoryValue

RETURNS DESCRIPTION
LocalPart

Its own sorts and operations, without laws.

RAISES DESCRIPTION
TheoryError

If a sort or operation is declared twice, or a signature is ill-formed, located at the declaration.

Source code in src/quivers/dsl/theories/signatures.py
def own_signature(decl: TheoryDecl, base: TheoryValue) -> LocalPart:
    """The sorts and operations a theory declaration declares itself.

    Parameters
    ----------
    decl : TheoryDecl
        The declaration.
    base : TheoryValue
        The colimit of the theories it includes.

    Returns
    -------
    LocalPart
        Its own sorts and operations, without laws.

    Raises
    ------
    TheoryError
        If a sort or operation is declared twice, or a signature is
        ill-formed, located at the declaration.
    """
    sorts: dict[str, int] = {
        s: len(params) for s, params in sort_parameters(base.theory).items()
    }
    ops: dict[str, int] = {
        o: len(names) for o, (names, _, _) in operations_of(base.theory).items()
    }
    for operation in decl.operations:
        if operation.name in ops:
            raise TheoryError(
                f"theory {decl.name!r} declares the operation {operation.name!r} "
                "twice, or one an included theory declares",
                operation.line,
                operation.col,
            )
        ops[operation.name] = sum(
            max(len(i.names), 1) for i in operation.inputs if not i.implicit
        )
    own_sorts: list[LocalSort] = []
    for sort in decl.sorts:
        if any(s.name == sort.name for s in own_sorts):
            raise TheoryError(
                f"theory {decl.name!r} declares the sort {sort.name!r} twice",
                sort.line,
                sort.col,
            )
        own_sorts.append(_own_sort(sort, decl.name, sorts, ops))
        sorts[sort.name] = sum(len(b.names) for b in sort.parameters)
    own_ops = [_own_operation(o, decl.name, sorts, ops) for o in decl.operations]
    return LocalPart(sorts=tuple(own_sorts), operations=tuple(own_ops))

elaborate_view

elaborate_view(decl: ViewDecl, domain: TheoryValue, codomain: TheoryValue) -> CheckedView

Check a view's signature and record what panproto finds of each equation.

PARAMETER DESCRIPTION
decl

The declaration.

TYPE: ViewDecl

domain

Its domain.

TYPE: TheoryValue

codomain

Its codomain.

TYPE: TheoryValue

RETURNS DESCRIPTION
CheckedView

The view. An obligation panproto discharges is "established", with its witness; any other is provisionally "assumed", with panproto's reason, and the theory layer decides whether the view may assume it.

RAISES DESCRIPTION
TheoryError

If a mapping names no symbol of the domain, maps a symbol twice, or has an ill-sorted image; a symbol is left unmapped with no identity of origin into the codomain; or panproto refuses the signature, located at the declaration.

Source code in src/quivers/dsl/theories/views.py
def elaborate_view(
    decl: ViewDecl, domain: TheoryValue, codomain: TheoryValue
) -> CheckedView:
    """Check a view's signature and record what panproto finds of each equation.

    Parameters
    ----------
    decl : ViewDecl
        The declaration.
    domain : TheoryValue
        Its domain.
    codomain : TheoryValue
        Its codomain.

    Returns
    -------
    CheckedView
        The view. An obligation panproto discharges is ``"established"``,
        with its witness; any other is provisionally ``"assumed"``, with
        panproto's reason, and the theory layer decides whether the view
        may assume it.

    Raises
    ------
    TheoryError
        If a mapping names no symbol of the domain, maps a symbol twice, or
        has an ill-sorted image; a symbol is left unmapped with no identity
        of origin into the codomain; or panproto refuses the signature,
        located at the declaration.
    """
    view = f"view {decl.name!r}"
    domain_sorts = list(sorts_of(domain.theory))
    domain_ops = operations_of(domain.theory)
    codomain_sorts = set(sorts_of(codomain.theory))
    codomain_ops = operations_of(codomain.theory)
    signature = signature_of(codomain)
    sort_map: dict[str, str] = {}
    op_renames: dict[str, str] = {}
    derived: dict[str, str] = {}
    pending: list[tuple[str, PatternSyntax, tuple[str, ...], int, int]] = []
    for mapping in decl.mappings:
        source = mapping.source
        where = f"{view}, mapping of {source.name!r}"
        mapped = source.name
        if (
            mapped in sort_map
            or mapped in op_renames
            or mapped in derived
            or any(p[0] == mapped for p in pending)
        ):
            raise TheoryError(
                f"{view} maps {mapped!r} twice", mapping.line, mapping.col
            )
        if source.kind == "name" and mapped in domain_sorts:
            target = _mapping_target_name(mapping.target)
            if target is None or target not in codomain_sorts:
                raise TheoryError(
                    f"{where}: a sort is sent to a sort of {codomain.name!r}",
                    mapping.line,
                    mapping.col,
                )
            sort_map[mapped] = target
            continue
        if mapped not in domain_ops:
            raise TheoryError(
                f"{view}: {mapped!r} is not a sort or operation of {domain.name!r}",
                mapping.line,
                mapping.col,
            )
        arity = len(domain_ops[mapped][1])
        if source.kind == "name":
            target = _mapping_target_name(mapping.target)
            if target is not None and target in codomain_ops:
                op_renames[mapped] = target
                continue
            if arity:
                raise TheoryError(
                    f"{where}: an operation with arguments is sent to an operation "
                    f"of {codomain.name!r}, or written applied to variables, as in "
                    f"`{mapped}({', '.join(f'x{i}' for i in range(arity))}) => ...`",
                    mapping.line,
                    mapping.col,
                )
            pending.append((mapped, mapping.target, (), mapping.line, mapping.col))
            continue
        if source.kind != "apply" or any(a.kind != "name" for a in source.args):
            raise TheoryError(
                f"{where}: the source of a mapping is a name, or an operation applied "
                "to distinct variables",
                mapping.line,
                mapping.col,
            )
        variables = tuple(a.name for a in source.args)
        if len(variables) != arity or len(set(variables)) != arity:
            raise TheoryError(
                f"{where}: {mapped!r} takes {arity} arguments, written as "
                f"{arity} distinct variables",
                mapping.line,
                mapping.col,
            )
        pending.append((mapped, mapping.target, variables, mapping.line, mapping.col))
    for sort in domain_sorts:
        if sort in sort_map:
            continue
        member = domain.member("sort", sort)
        if (
            member is not None
            and codomain.reaches(member.origin)
            and sort in codomain_sorts
        ):
            sort_map[sort] = sort
            continue
        raise TheoryError(
            f"{view} does not map the sort {sort!r} of {domain.name!r}, and "
            f"{codomain.name!r} does not include the theory that declares it; "
            f"write `{sort} => ...`",
            decl.line,
            decl.col,
        )
    written = {p[0] for p in pending}
    for op in domain_ops:
        if op in op_renames or op in written:
            continue
        member = domain.member("op", op)
        if (
            member is not None
            and codomain.reaches(member.origin)
            and op in codomain_ops
        ):
            op_renames[op] = op
            continue
        raise TheoryError(
            f"{view} does not map the operation {op!r} of {domain.name!r}, and "
            f"{codomain.name!r} does not include the theory that declares it; "
            f"write `{op} => ...`",
            decl.line,
            decl.col,
        )
    for op, target, variables, m_line, m_col in pending:
        where = f"{view}, mapping of {op!r}"
        input_names, input_sorts, output = domain_ops[op]
        clash = [v for v in variables if v in codomain_ops]
        if clash:
            raise TheoryError(
                f"{where}: the variable {clash[0]!r} is also an operation of "
                f"{codomain.name!r}; choose another name",
                m_line,
                m_col,
            )
        metas = {
            v: MetaSort(arguments=(), result=sort_map[s])
            for v, s in zip(variables, input_sorts, strict=True)
        }
        try:
            pattern = resolve(target, signature)
            check_pattern_sorts(pattern, signature, (), sort_map[output], metas)
        except PatternError as error:
            raise TheoryError(f"{where}: {error}", m_line, m_col) from error
        unbound = sorted(set(metas) - set(variables))
        if unbound:
            raise TheoryError(
                f"{where}: {unbound[0]!r} is neither an argument of {op!r} nor an "
                f"operation of {codomain.name!r}",
                m_line,
                m_col,
            )
        derived[op] = _render(
            pattern,
            dict(zip(variables, input_names, strict=True)),
            where,
            m_line,
            m_col,
        )
    morphism = MorphismRecord(
        name=decl.name,
        domain=domain.theory.name,
        codomain=codomain.theory.name,
        sort_map=sort_map,
        op_renames=op_renames,
        derived_terms=derived,
    )
    try:
        checked = check_view(morphism, domain.theory, codomain.theory)
    except ViewRefused as error:
        raise TheoryError(
            f"{view} is not a theory morphism from {domain.name!r} to "
            f"{codomain.name!r}: {error.message}",
            decl.line,
            decl.col,
        ) from error
    obligations: list[ObligationRecord] = []
    for obligation in checked.obligations:
        member = domain.member("eq", obligation.equation)
        if member is None:
            raise TheoryError(
                f"{view}: panproto reports an obligation for {obligation.equation!r}, "
                f"which is not an equation of {domain.name!r}",
                decl.line,
                decl.col,
            )
        if isinstance(obligation, Discharged | Derivable):
            obligations.append(
                ObligationRecord(
                    equation=member,
                    lhs=obligation.lhs,
                    rhs=obligation.rhs,
                    image_lhs=obligation.image_lhs,
                    image_rhs=obligation.image_rhs,
                    status="established",
                    witness=obligation.witness,
                )
            )
        else:
            obligations.append(
                ObligationRecord(
                    equation=member,
                    lhs=obligation.lhs,
                    rhs=obligation.rhs,
                    image_lhs=obligation.image_lhs,
                    image_rhs=obligation.image_rhs,
                    status="assumed",
                    reason=obligation.reason,
                )
            )
    return CheckedView(
        name=decl.name,
        domain=domain.name,
        codomain=codomain.name,
        morphism=morphism,
        obligations=tuple(obligations),
        line=decl.line,
        col=decl.col,
    )

inclusion_view

inclusion_view(name: str, included: TheoryValue, value: TheoryValue) -> MorphismRecord

The inclusion of a theory into one that includes it, as a morphism.

PARAMETER DESCRIPTION
name

The morphism's name.

TYPE: str

included

The included theory.

TYPE: TheoryValue

value

A theory that includes it, so that every symbol of included is a symbol of value of the same name and origin.

TYPE: TheoryValue

RETURNS DESCRIPTION
MorphismRecord

The identity-on-names morphism.

Source code in src/quivers/dsl/theories/views.py
def inclusion_view(
    name: str, included: TheoryValue, value: TheoryValue
) -> MorphismRecord:
    """The inclusion of a theory into one that includes it, as a morphism.

    Parameters
    ----------
    name : str
        The morphism's name.
    included : TheoryValue
        The included theory.
    value : TheoryValue
        A theory that includes it, so that every symbol of ``included`` is a
        symbol of ``value`` of the same name and origin.

    Returns
    -------
    MorphismRecord
        The identity-on-names morphism.
    """
    return MorphismRecord(
        name=name,
        domain=included.theory.name,
        codomain=value.theory.name,
        sort_map={s: s for s in sorts_of(included.theory)},
        op_renames={o: o for o in operations_of(included.theory)},
    )

resolve_equation

resolve_equation(value: TheoryValue, name: str, line: int, col: int, what: str) -> Member

The equation of a theory a source name refers to.

PARAMETER DESCRIPTION
value

The theory.

TYPE: TheoryValue

name

The equation's local name, or its name qualified by its origin.

TYPE: str

line

Where the name is written.

TYPE: int

col

Where the name is written.

TYPE: int

what

What refers to it, for refusals.

TYPE: str

RETURNS DESCRIPTION
Member

The equation.

RAISES DESCRIPTION
TheoryError

If no equation, or more than one, has that name.

Source code in src/quivers/dsl/theories/views.py
def resolve_equation(
    value: TheoryValue, name: str, line: int, col: int, what: str
) -> Member:
    """The equation of a theory a source name refers to.

    Parameters
    ----------
    value : TheoryValue
        The theory.
    name : str
        The equation's local name, or its name qualified by its origin.
    line, col : int
        Where the name is written.
    what : str
        What refers to it, for refusals.

    Returns
    -------
    Member
        The equation.

    Raises
    ------
    TheoryError
        If no equation, or more than one, has that name.
    """
    exact = [m for m in value.members if m.kind == "eq" and m.name == name]
    if exact:
        return exact[0]
    local = [m for m in value.members if m.kind == "eq" and m.local == name]
    if len(local) == 1:
        return local[0]
    if not local:
        raise TheoryError(
            f"{what}: theory {value.name!r} has no equation {name!r}", line, col
        )
    raise TheoryError(
        f"{what}: {name!r} names several equations of theory {value.name!r}: "
        + ", ".join(m.name for m in local)
        + "; write one of these names",
        line,
        col,
    )