Skip to content

Rewriting

Oriented equations form a higher-order pattern rewrite system. This module normalizes terms under a strategy, computes critical pairs, searches for a recursive path order, and records termination and confluence as proved or assumed laws (Equations and normalization §2 to §4).

rewriting

Equational theories on binding signatures: checked rewriting and normalizers.

An EquationalTheory declares second-order equations over a Signature [@fiore2010second; @fiore2010algebraic]. An oriented equation is a RewriteRule whose left side is in Miller's pattern fragment, so the rules form a higher-order pattern rewrite system [@mayr1998higher]. Such a system is confluent when it terminates and every critical pair joins, and its normal forms then decide the equational theory of its rules [@hamana2017decidable]. check_theory establishes both, soundly and incompletely:

  • Critical pairs. Every overlap of two left sides is computed by higher-order pattern unification (quivers.structural.patterns). Each peak is instantiated with a generic constant for every unsolved metavariable, both reducts are normalized, and a pair whose normal forms differ is reported with its peak.
  • Termination. A recursive path order is searched for: a precedence on the constructors under which every left side is greater than its right side [@dershowitz1982orderings; @baader1998term]. The search reads each rule first-order, with binders as ordinary symbols, bound variables as one least constant, and metavariables as variables. This reading is sound when every right-side metavariable is applied to variables only, because instantiating it then renames and never copies a term; a rule that instantiates a metavariable with a term is not ordered, and its theory needs the recorded assumption assume terminating.

The result records each law's status with quivers.core.laws evidence: termination is proved by the path order found, or assumed when declared; confluence is proved from joinable critical pairs and proved termination, or assumed when termination is.

RewriteSystem.normalize computes normal forms under a strategy: innermost, outermost, or node-wise during construction (RewriteSystem.build). Normal forms are memoized in a table keyed by the term, whose hash is structural and cached, so a shared subterm is normalized once.

TERMINATION module-attribute

TERMINATION = Law(name='rewriting-terminates', statement="every sequence of rewrites by the theory's rules is finite")

The law that a theory's rules terminate.

CONFLUENCE module-attribute

CONFLUENCE = Law(name='rewriting-confluent', statement="any two rewrites of one term by the theory's rules have a common reduct")

The law that a theory's rules are confluent.

Precedence

Precedence = frozenset[tuple[str, str]]

A strict partial order on symbols, as its transitively closed pairs.

RewriteError

Bases: ValueError

A rewrite system or equational theory is ill-formed or fails a check.

RewriteLimitExceeded

Bases: RewriteError

Normalization took more steps than its budget allows.

Strategy

Bases: str, Enum

Where a normalizer looks for the next redex.

INNERMOST normalizes arguments before their parent, OUTERMOST contracts the leftmost-outermost redex first, and NODEWISE normalizes each node as it is built from normal arguments, so a term built by RewriteSystem.build is normal at every stage.

Equation didactic-model

Equation(*, name: str, left: Pattern = field(opaque=True, extras=OPAQUE_BY_VALUE), right: Pattern = field(opaque=True, extras=OPAQUE_BY_VALUE), sort: str, metas: dict = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE), oriented: bool = False, line: int = 0, col: int = 0)

Bases: ValueModel

A named second-order equation between two patterns.

PARAMETER DESCRIPTION
name

Its name.

TYPE: str

left

Its two sides.

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

right

Its two sides.

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

sort

The sort of both sides.

TYPE: str

metas

The type of every metavariable it uses.

TYPE: dict of str to MetaSort DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE)

oriented

Whether it is a rule left ~> right rather than a law.

TYPE: bool DEFAULT: False

line

Its source position, zero when built in Python.

TYPE: int DEFAULT: 0

col

Its source position, zero when built in Python.

TYPE: int DEFAULT: 0

text

text(signature: Signature) -> str

The equation as source writes it.

PARAMETER DESCRIPTION
signature

The signature.

TYPE: Signature

RETURNS DESCRIPTION
str

left = right or left ~> right.

Source code in src/quivers/structural/rewriting.py
def text(self, signature: Signature) -> str:
    """The equation as source writes it.

    Parameters
    ----------
    signature : Signature
        The signature.

    Returns
    -------
    str
        ``left = right`` or ``left ~> right``.
    """
    relation = "~>" if self.oriented else "="
    return (
        f"{render_pattern(self.left, signature)} {relation} "
        f"{render_pattern(self.right, signature)}"
    )

RewriteSystem

RewriteSystem(signature: Signature, rules: Sequence[Equation], max_steps: int = 100000)

A higher-order pattern rewrite system with memoized normal forms.

PARAMETER DESCRIPTION
signature

The signature of the terms.

TYPE: Signature

rules

Oriented equations.

TYPE: Sequence of Equation

max_steps

The number of contractions one normalization may make.

TYPE: int DEFAULT: 100000

RAISES DESCRIPTION
RewriteError

If a rule is not oriented.

Source code in src/quivers/structural/rewriting.py
def __init__(
    self,
    signature: Signature,
    rules: Sequence[Equation],
    max_steps: int = 100_000,
) -> None:
    for rule in rules:
        if not rule.oriented:
            raise RewriteError(f"equation {rule.name!r} is not an oriented rule")
    self.signature = signature
    self.rules = tuple(rules)
    self.max_steps = max_steps
    self._by_root: dict[str, list[Equation]] = {}
    for rule in self.rules:
        assert isinstance(rule.left, PatternApplication)
        self._by_root.setdefault(rule.left.op, []).append(rule)
    self._normal: dict[Term, Term] = {}
    self.steps = 0

with_signature

with_signature(signature: Signature) -> RewriteSystem

The same rules over an extended signature.

PARAMETER DESCRIPTION
signature

A signature that declares every constructor of this one.

TYPE: Signature

RETURNS DESCRIPTION
RewriteSystem

A system with a fresh memo table.

Source code in src/quivers/structural/rewriting.py
def with_signature(self, signature: Signature) -> RewriteSystem:
    """The same rules over an extended signature.

    Parameters
    ----------
    signature : Signature
        A signature that declares every constructor of this one.

    Returns
    -------
    RewriteSystem
        A system with a fresh memo table.
    """
    return RewriteSystem(signature, self.rules, self.max_steps)

contract

contract(term: Term) -> tuple[Equation, Term] | None

Contract a redex at the root, by the first rule that matches.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

RETURNS DESCRIPTION
tuple of Equation and Term, or None

The rule and the contractum, or None when the root is not a redex.

Source code in src/quivers/structural/rewriting.py
def contract(self, term: Term) -> tuple[Equation, Term] | None:
    """Contract a redex at the root, by the first rule that matches.

    Parameters
    ----------
    term : Term
        The term.

    Returns
    -------
    tuple of Equation and Term, or None
        The rule and the contractum, or ``None`` when the root is not a
        redex.
    """
    for rule in self._by_root.get(term.op, ()):
        solutions = match(rule.left, term, self.signature)
        if solutions is None:
            continue
        result = instantiate_pattern(rule.right, solutions, self.signature)
        assert isinstance(result, Term)
        return rule, result
    return None

normalize

normalize(term: Term, strategy: Strategy = INNERMOST) -> Term

The normal form of a term.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

strategy

Where to contract first. Every strategy reaches the same normal form when the system is confluent and terminating.

TYPE: Strategy DEFAULT: INNERMOST

RETURNS DESCRIPTION
Term

Its normal form.

RAISES DESCRIPTION
RewriteLimitExceeded

If more than max_steps contractions are needed.

Source code in src/quivers/structural/rewriting.py
def normalize(self, term: Term, strategy: Strategy = Strategy.INNERMOST) -> Term:
    """The normal form of a term.

    Parameters
    ----------
    term : Term
        The term.
    strategy : Strategy
        Where to contract first. Every strategy reaches the same normal
        form when the system is confluent and terminating.

    Returns
    -------
    Term
        Its normal form.

    Raises
    ------
    RewriteLimitExceeded
        If more than ``max_steps`` contractions are needed.
    """
    self.steps = 0
    if strategy is Strategy.OUTERMOST:
        return self._outermost(term)
    return self._innermost(term)

build

build(op: str, arguments: Sequence[TermArg]) -> Term

Build a node from normal arguments and normalize it at once.

This is node-wise normalization: a term assembled bottom-up through build is normal at every node, which is how a derivation that constructs meanings item by item keeps them small.

PARAMETER DESCRIPTION
op

The constructor.

TYPE: str

arguments

Its arguments, each already normal.

TYPE: Sequence of TermArg

RETURNS DESCRIPTION
Term

The normal form of the node.

Source code in src/quivers/structural/rewriting.py
def build(self, op: str, arguments: Sequence[TermArg]) -> Term:
    """Build a node from normal arguments and normalize it at once.

    This is node-wise normalization: a term assembled bottom-up through
    `build` is normal at every node, which is how a derivation that
    constructs meanings item by item keeps them small.

    Parameters
    ----------
    op : str
        The constructor.
    arguments : Sequence of TermArg
        Its arguments, each already normal.

    Returns
    -------
    Term
        The normal form of the node.
    """
    self.steps = 0
    node = Term(op=op, args=tuple(arguments))
    known = self._normal.get(node)
    if known is not None:
        return known
    result = self._root_normal(node)
    self._normal[node] = result
    return result

equal_modulo

equal_modulo(left: Term, right: Term) -> bool

Whether two terms have the same normal form.

PARAMETER DESCRIPTION
left

The terms.

TYPE: Term

right

The terms.

TYPE: Term

RETURNS DESCRIPTION
bool

Equality modulo the rules, decided when they are confluent and terminating.

Source code in src/quivers/structural/rewriting.py
def equal_modulo(self, left: Term, right: Term) -> bool:
    """Whether two terms have the same normal form.

    Parameters
    ----------
    left, right : Term
        The terms.

    Returns
    -------
    bool
        Equality modulo the rules, decided when they are confluent and
        terminating.
    """
    return self.normalize(left) == self.normalize(right)

is_normal

is_normal(term: Term) -> bool

Whether no subterm is a redex.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

RETURNS DESCRIPTION
bool

True for a normal form.

Source code in src/quivers/structural/rewriting.py
def is_normal(self, term: Term) -> bool:
    """Whether no subterm is a redex.

    Parameters
    ----------
    term : Term
        The term.

    Returns
    -------
    bool
        ``True`` for a normal form.
    """
    stack: list[Term] = [term]
    while stack:
        node = stack.pop()
        if node.op == BOUND_VAR:
            continue
        if self.contract(node) is not None:
            return False
        stack.extend(a for a in node.args if isinstance(a, Term))
    return True

normal_form_hash

normal_form_hash(term: Term) -> str

The content hash of a term's normal form.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

RETURNS DESCRIPTION
str

A stable key for the term's class modulo the rules.

Source code in src/quivers/structural/rewriting.py
def normal_form_hash(self, term: Term) -> str:
    """The content hash of a term's normal form.

    Parameters
    ----------
    term : Term
        The term.

    Returns
    -------
    str
        A stable key for the term's class modulo the rules.
    """
    return content_hash(self.normalize(term))

CriticalPair didactic-model

CriticalPair(*, outer: str, inner: str, position: tuple[int, ...] = (), peak: Term = field(opaque=True, extras=OPAQUE_BY_VALUE), left: Term = field(opaque=True, extras=OPAQUE_BY_VALUE), right: Term = field(opaque=True, extras=OPAQUE_BY_VALUE), left_normal: Term | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), right_normal: Term | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), joinable: bool = False, extended: Signature = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

An overlap of two rules and whether its two reducts join.

PARAMETER DESCRIPTION
outer

The rule contracted at the root of the peak and the one contracted at position.

TYPE: str

inner

The rule contracted at the root of the peak and the one contracted at position.

TYPE: str

position

The argument path from the root of the peak to the inner redex.

TYPE: tuple of int DEFAULT: ()

peak

The most general term both rules rewrite, with a generic constant ?M for each metavariable left free.

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

left

The reducts by the outer and the inner rule.

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

right

The reducts by the outer and the inner rule.

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

left_normal

Their normal forms, None when normalization ran out of steps.

TYPE: Term or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

right_normal

Their normal forms, None when normalization ran out of steps.

TYPE: Term or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

joinable

Whether the normal forms are equal.

TYPE: bool DEFAULT: False

describe

describe() -> str

The pair as a diagnostic names it.

RETURNS DESCRIPTION
str

The rules, the peak, and the two normal forms.

Source code in src/quivers/structural/rewriting.py
def describe(self) -> str:
    """The pair as a diagnostic names it.

    Returns
    -------
    str
        The rules, the peak, and the two normal forms.
    """
    left = self.left_normal if self.left_normal is not None else self.left
    right = self.right_normal if self.right_normal is not None else self.right
    return (
        f"rules {self.outer!r} and {self.inner!r} overlap at "
        f"{show(self.peak, self.extended)}, which rewrites to "
        f"{show(left, self.extended)} and to {show(right, self.extended)}"
    )

FirstOrder didactic-model

FirstOrder(*, symbol: str, args: tuple = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), variable: bool = False)

Bases: ValueModel

A first-order term: a variable, or a symbol applied to terms.

PARAMETER DESCRIPTION
symbol

The function symbol, or the variable's name when variable.

TYPE: str

args

The arguments.

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

variable

Whether it is a variable.

TYPE: bool DEFAULT: False

PathOrder

PathOrder(status: str, budget: int = 200000)

A recursive path order with a searched precedence.

PARAMETER DESCRIPTION
status

"lexicographic" or "multiset" for every symbol.

TYPE: str

budget

The number of comparisons the search may make.

TYPE: int DEFAULT: 200000

Source code in src/quivers/structural/rewriting.py
def __init__(self, status: str, budget: int = 200_000) -> None:
    self.status = status
    self.budget = budget

greater

greater(left: FirstOrder, right: FirstOrder, order: Precedence) -> Iterator[Precedence]

Precedences extending order under which left > right.

PARAMETER DESCRIPTION
left

The terms.

TYPE: FirstOrder

right

The terms.

TYPE: FirstOrder

order

The precedence so far.

TYPE: Precedence

YIELDS DESCRIPTION
Precedence

Each extension found.

Source code in src/quivers/structural/rewriting.py
def greater(
    self, left: FirstOrder, right: FirstOrder, order: Precedence
) -> Iterator[Precedence]:
    """Precedences extending ``order`` under which ``left > right``.

    Parameters
    ----------
    left, right : FirstOrder
        The terms.
    order : Precedence
        The precedence so far.

    Yields
    ------
    Precedence
        Each extension found.
    """
    self._spend()
    if left.variable:
        return
    if right.variable:
        if right.symbol in set(_variables(left)):
            yield order
        return
    for argument in left.args:
        yield from self.greater_equal(argument, right, order)
    if left.symbol == right.symbol and len(left.args) == len(right.args):
        for extended in self._dominates(left, right.args, order):
            yield from self._extension(left.args, right.args, extended)
        return
    extended = _add(order, left.symbol, right.symbol)
    if extended is not None:
        yield from self._dominates(left, right.args, extended)

greater_equal

greater_equal(left: FirstOrder, right: FirstOrder, order: Precedence) -> Iterator[Precedence]

Precedences under which left >= right.

PARAMETER DESCRIPTION
left

The terms.

TYPE: FirstOrder

right

The terms.

TYPE: FirstOrder

order

The precedence so far.

TYPE: Precedence

YIELDS DESCRIPTION
Precedence

Each extension found.

Source code in src/quivers/structural/rewriting.py
def greater_equal(
    self, left: FirstOrder, right: FirstOrder, order: Precedence
) -> Iterator[Precedence]:
    """Precedences under which ``left >= right``.

    Parameters
    ----------
    left, right : FirstOrder
        The terms.
    order : Precedence
        The precedence so far.

    Yields
    ------
    Precedence
        Each extension found.
    """
    if left == right:
        yield order
        return
    yield from self.greater(left, right, order)

orient

orient(pairs: Sequence[tuple[FirstOrder, FirstOrder]], order: Precedence) -> Precedence | None

A precedence under which every left term exceeds its right term.

PARAMETER DESCRIPTION
pairs

The rules, left then right.

TYPE: Sequence of tuple of FirstOrder

order

The precedence so far.

TYPE: Precedence

RETURNS DESCRIPTION
Precedence or None

The first precedence found, or None.

Source code in src/quivers/structural/rewriting.py
def orient(
    self, pairs: Sequence[tuple[FirstOrder, FirstOrder]], order: Precedence
) -> Precedence | None:
    """A precedence under which every left term exceeds its right term.

    Parameters
    ----------
    pairs : Sequence of tuple of FirstOrder
        The rules, left then right.
    order : Precedence
        The precedence so far.

    Returns
    -------
    Precedence or None
        The first precedence found, or ``None``.
    """
    if not pairs:
        return order
    left, right = pairs[0]
    seen: set[Precedence] = set()
    for extended in self.greater(left, right, order):
        if extended in seen:
            continue
        seen.add(extended)
        result = self.orient(pairs[1:], extended)
        if result is not None:
            return result
    return None

Greater didactic-model

Greater(*, high: str, low: str)

Bases: Model

One pair of a precedence: high > low.

PARAMETER DESCRIPTION
high

The symbols.

TYPE: str

low

The symbols.

TYPE: str

TerminationProof didactic-model

TerminationProof(*, status: str, precedence: tuple[Greater, ...] = ())

Bases: ValueModel

A recursive path order that orients every rule.

PARAMETER DESCRIPTION
status

"lexicographic" or "multiset".

TYPE: str

precedence

The pairs of the precedence, sorted.

TYPE: tuple of Greater DEFAULT: ()

describe

describe() -> str

The order as a sentence.

RETURNS DESCRIPTION
str

The status and the precedence.

Source code in src/quivers/structural/rewriting.py
def describe(self) -> str:
    """The order as a sentence.

    Returns
    -------
    str
        The status and the precedence.
    """
    pairs = ", ".join(f"{p.high} > {p.low}" for p in self.precedence)
    kind = "lexicographic" if self.status == "lexicographic" else "multiset"
    return f"{kind} path order with precedence {pairs or '(empty)'}"

TerminationFailure didactic-model

TerminationFailure(*, rules: tuple[str, ...] = (), reason: str)

Bases: ValueModel

Why no path order was found.

PARAMETER DESCRIPTION
rules

The rules that could not be oriented, or that are outside what the first-order reading can order.

TYPE: tuple of str DEFAULT: ()

reason

The explanation.

TYPE: str

EquationalTheory didactic-model

EquationalTheory(*, signature: Signature = field(opaque=True, extras=OPAQUE_BY_VALUE), rules: tuple = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), laws: tuple = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), assume_terminating: bool = False, strategy: Strategy = INNERMOST)

Bases: ValueModel

The equations of a signature, with how each is to be decided.

PARAMETER DESCRIPTION
signature

The signature.

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

rules

The oriented rules.

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

laws

The equations that are not oriented.

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

assume_terminating

Whether termination is a recorded assumption.

TYPE: bool DEFAULT: False

strategy

The normalization strategy.

TYPE: Strategy DEFAULT: INNERMOST

TheoryReport didactic-model

TheoryReport(*, termination: TerminationProof | None = field(default=None, opaque=True, extras=OPAQUE_BY_VALUE), pairs: tuple = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), claims: tuple[LawClaim, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

What check_theory established about a theory.

PARAMETER DESCRIPTION
termination

The path order, or None when termination is assumed.

TYPE: TerminationProof or None DEFAULT: field(default=None, opaque=True, extras=OPAQUE_BY_VALUE)

pairs

Every critical pair.

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

claims

The termination and confluence claims with their evidence.

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

NonConfluent

Bases: RewriteError

A theory's rules have a critical pair that does not join.

NonTerminating

Bases: RewriteError

No path order orients a theory's rules and no assumption is recorded.

make_equation

make_equation(name: str, left: Pattern, right: Pattern, signature: Signature, *, oriented: bool, line: int = 0, col: int = 0) -> Equation

Check an equation's sorts and scopes and record its metavariables.

Both sides must be closed patterns of one sort. Every metavariable of the right side occurs on the left with the same arity. A rule's left side is in Miller's pattern fragment.

PARAMETER DESCRIPTION
name

Its name.

TYPE: str

left

Its sides.

TYPE: Pattern

right

Its sides.

TYPE: Pattern

signature

The signature.

TYPE: Signature

oriented

Whether it is a rule.

TYPE: bool

line

Its source position.

TYPE: int DEFAULT: 0

col

Its source position.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
Equation

The checked equation.

RAISES DESCRIPTION
RewriteError

If a side is ill-sorted, a right-side metavariable is unbound, or a rule's left side is outside the pattern fragment; the message names the equation.

Source code in src/quivers/structural/rewriting.py
def make_equation(
    name: str,
    left: Pattern,
    right: Pattern,
    signature: Signature,
    *,
    oriented: bool,
    line: int = 0,
    col: int = 0,
) -> Equation:
    """Check an equation's sorts and scopes and record its metavariables.

    Both sides must be closed patterns of one sort. Every metavariable of
    the right side occurs on the left with the same arity. A rule's left
    side is in Miller's pattern fragment.

    Parameters
    ----------
    name : str
        Its name.
    left, right : Pattern
        Its sides.
    signature : Signature
        The signature.
    oriented : bool
        Whether it is a rule.
    line, col : int
        Its source position.

    Returns
    -------
    Equation
        The checked equation.

    Raises
    ------
    RewriteError
        If a side is ill-sorted, a right-side metavariable is unbound, or a
        rule's left side is outside the pattern fragment; the message names
        the equation.
    """
    metas: dict[str, MetaSort] = {}
    try:
        if oriented:
            check_miller_pattern(left, signature)
        sort = check_pattern_sorts(left, signature, (), None, metas)
        left_metas = set(metas)
        check_pattern_sorts(right, signature, (), sort, metas)
    except PatternError as error:
        raise RewriteError(f"equation {name!r}: {error}") from error
    unbound = sorted(set(metas) - left_metas)
    if oriented and unbound:
        raise RewriteError(
            f"rule {name!r}: metavariable {unbound[0]!r} of the right side does not "
            "occur on the left side"
        )
    return Equation(
        name=name,
        left=left,
        right=right,
        sort=sort,
        metas=metas,
        oriented=oriented,
        line=line,
        col=col,
    )

critical_pairs

critical_pairs(signature: Signature, rules: Sequence[Equation], max_steps: int = 10000) -> tuple[CriticalPair, ...]

Every critical pair of a rule set, with joinability.

For each pair of rules and each constructor position of the first rule's left side, the second rule's left side is unified with the subpattern there. The second rule's metavariables are raised over the variables bound above the position, so they may depend on them, and pruning keeps the unifier most general [@miller1991logic].

PARAMETER DESCRIPTION
signature

The signature.

TYPE: Signature

rules

The oriented rules.

TYPE: Sequence of Equation

max_steps

The step budget for normalizing each reduct.

TYPE: int DEFAULT: 10000

RETURNS DESCRIPTION
tuple of CriticalPair

One pair per overlap, outer rule first, in rule and position order.

Source code in src/quivers/structural/rewriting.py
def critical_pairs(
    signature: Signature, rules: Sequence[Equation], max_steps: int = 10_000
) -> tuple[CriticalPair, ...]:
    """Every critical pair of a rule set, with joinability.

    For each pair of rules and each constructor position of the first
    rule's left side, the second rule's left side is unified with the
    subpattern there. The second rule's metavariables are raised over the
    variables bound above the position, so they may depend on them, and
    pruning keeps the unifier most general [@miller1991logic].

    Parameters
    ----------
    signature : Signature
        The signature.
    rules : Sequence of Equation
        The oriented rules.
    max_steps : int
        The step budget for normalizing each reduct.

    Returns
    -------
    tuple of CriticalPair
        One pair per overlap, outer rule first, in rule and position order.
    """
    found: list[CriticalPair] = []
    for outer, inner in itertools.product(rules, rules):
        renamed = _rename_metas(inner, "'")
        for path in _positions(outer.left, signature):
            if not path and outer.name == inner.name:
                continue
            problem = UnificationProblem(signature, outer.metas)
            sub, names, sorts = _subterm(problem, outer.left, path)
            frees = tuple(FreeVariable(name=n) for n in names)
            data = frozenset(
                meta
                for meta, sort in renamed.metas.items()
                if signature.sorts[sort.result].kind == "data"
            )
            for meta, sort in renamed.metas.items():
                problem.sorts[meta] = MetaSort(
                    arguments=sort.arguments
                    if meta in data
                    else (*sorts, *sort.arguments),
                    result=sort.result,
                )
            try:
                unified = problem.unify(sub, _raise(renamed.left, frees, data))
            except PatternError:
                unified = False
            if not unified:
                continue
            free_metas = {
                occurrence.name
                for occurrence in metavariables(problem.full(outer.left))
                if signature.sorts[problem.sorts[occurrence.name].result].kind != "data"
            }
            extended = signature.with_(
                constructors_t=(
                    *signature.constructors_t,
                    *(
                        Constructor(
                            name=generic_name(meta),
                            domain=problem.sorts[meta].arguments,
                            codomain=problem.sorts[meta].result,
                        )
                        for meta in sorted(free_metas)
                    ),
                )
            )
            peak = _realize(problem, outer.left, (), path, names, extended)
            assert isinstance(peak, Term)
            found.append(_join(extended, rules, outer, inner, path, peak, max_steps))
    return tuple(found)

first_order

first_order(pattern: PatternArgument, *, right: bool, rule: str) -> FirstOrder

Read a pattern as a first-order term for the path order.

PARAMETER DESCRIPTION
pattern

The pattern.

TYPE: PatternArgument

right

Whether it is a right side, where a metavariable must be applied to variables only.

TYPE: bool

rule

The rule, for diagnostics.

TYPE: str

RETURNS DESCRIPTION
FirstOrder

The first-order reading.

RAISES DESCRIPTION
RewriteError

If a right-side metavariable is instantiated with a term other than a variable, which no first-order path order bounds.

Source code in src/quivers/structural/rewriting.py
def first_order(pattern: PatternArgument, *, right: bool, rule: str) -> FirstOrder:
    """Read a pattern as a first-order term for the path order.

    Parameters
    ----------
    pattern : PatternArgument
        The pattern.
    right : bool
        Whether it is a right side, where a metavariable must be applied to
        variables only.
    rule : str
        The rule, for diagnostics.

    Returns
    -------
    FirstOrder
        The first-order reading.

    Raises
    ------
    RewriteError
        If a right-side metavariable is instantiated with a term other than
        a variable, which no first-order path order bounds.
    """
    if isinstance(pattern, PatternVariable):
        return FirstOrder(symbol=_VARIABLE)
    if isinstance(pattern, Metavariable):
        if right and any(not isinstance(a, PatternVariable) for a in pattern.args):
            raise RewriteError(
                f"rule {rule!r} instantiates metavariable {pattern.name!r} with a "
                "term, which may copy it; a path order cannot bound that"
            )
        return FirstOrder(symbol=pattern.name, variable=True)
    if isinstance(pattern, PatternApplication):
        return FirstOrder(
            symbol=pattern.op,
            args=tuple(
                first_order(a, right=right, rule=rule)
                if isinstance(a, PatternApplication | Metavariable | PatternVariable)
                else FirstOrder(symbol=f"{type(a).__name__}:{a!r}")
                for a in pattern.args
            ),
        )
    raise RewriteError(f"rule {rule!r}: unexpected pattern node")

prove_termination

prove_termination(rules: Sequence[Equation], budget: int = 200000) -> TerminationProof | TerminationFailure

Search for a recursive path order that orients every rule.

PARAMETER DESCRIPTION
rules

The oriented rules.

TYPE: Sequence of Equation

budget

The comparison budget of each search.

TYPE: int DEFAULT: 200000

RETURNS DESCRIPTION
TerminationProof or TerminationFailure

The order, or the rules that defeat the search.

Source code in src/quivers/structural/rewriting.py
def prove_termination(
    rules: Sequence[Equation], budget: int = 200_000
) -> TerminationProof | TerminationFailure:
    """Search for a recursive path order that orients every rule.

    Parameters
    ----------
    rules : Sequence of Equation
        The oriented rules.
    budget : int
        The comparison budget of each search.

    Returns
    -------
    TerminationProof or TerminationFailure
        The order, or the rules that defeat the search.
    """
    pairs: list[tuple[FirstOrder, FirstOrder]] = []
    for rule in rules:
        try:
            pairs.append(
                (
                    first_order(rule.left, right=False, rule=rule.name),
                    first_order(rule.right, right=True, rule=rule.name),
                )
            )
        except RewriteError as error:
            return TerminationFailure(rules=(rule.name,), reason=str(error))
    for status in ("lexicographic", "multiset"):
        order = PathOrder(status, budget)
        try:
            found = order.orient(pairs, frozenset())
        except RewriteError:
            found = None
        if found is not None:
            return TerminationProof(
                status=status,
                precedence=tuple(Greater(high=a, low=b) for a, b in sorted(found)),
            )
    stuck: list[str] = []
    for rule, pair in zip(rules, pairs, strict=True):
        alone = False
        for status in ("lexicographic", "multiset"):
            try:
                alone = (
                    PathOrder(status, budget).orient((pair,), frozenset()) is not None
                )
            except RewriteError:
                alone = False
            if alone:
                break
        if not alone:
            stuck.append(rule.name)
    return TerminationFailure(
        rules=tuple(stuck) or tuple(r.name for r in rules),
        reason=(
            "no recursive path order makes every left side greater than its right side"
        ),
    )

check_theory

check_theory(theory: EquationalTheory, max_steps: int = 10000) -> TheoryReport

Establish termination and confluence of a theory's rules.

PARAMETER DESCRIPTION
theory

The theory.

TYPE: EquationalTheory

max_steps

The budget for normalizing each critical pair's reducts.

TYPE: int DEFAULT: 10000

RETURNS DESCRIPTION
TheoryReport

The proofs, the critical pairs, and the law claims.

RAISES DESCRIPTION
NonTerminating

If no path order orients the rules and termination is not assumed; the message names the rules.

NonConfluent

If a critical pair does not join; the message reports every such pair with its peak and its two normal forms.

Source code in src/quivers/structural/rewriting.py
def check_theory(theory: EquationalTheory, max_steps: int = 10_000) -> TheoryReport:
    """Establish termination and confluence of a theory's rules.

    Parameters
    ----------
    theory : EquationalTheory
        The theory.
    max_steps : int
        The budget for normalizing each critical pair's reducts.

    Returns
    -------
    TheoryReport
        The proofs, the critical pairs, and the law claims.

    Raises
    ------
    NonTerminating
        If no path order orients the rules and termination is not assumed;
        the message names the rules.
    NonConfluent
        If a critical pair does not join; the message reports every such
        pair with its peak and its two normal forms.
    """
    subject = ClaimSubject(kind="presentation", name=theory.signature.name)
    rules = tuple(theory.rules)
    claims: list[LawClaim] = []
    proof: TerminationProof | None = None
    if theory.assume_terminating:
        claims.append(
            LawClaim(
                law=TERMINATION,
                subject=subject,
                evidence=Assumed(
                    declared_by=f"syntax {theory.signature.name}",
                    reason="declared with `assume terminating`",
                ),
            )
        )
    else:
        found = prove_termination(rules)
        if isinstance(found, TerminationFailure):
            names = ", ".join(repr(r) for r in found.rules)
            raise NonTerminating(
                f"syntax {theory.signature.name!r}: termination of rule(s) "
                f"{names} is not established: {found.reason}; declare "
                "`assume terminating` to record it as an assumption"
            )
        proof = found
        claims.append(
            LawClaim(
                law=TERMINATION,
                subject=subject,
                evidence=Proved(
                    argument="docs/semantics/equations.md#termination",
                    sources=(_PATH_ORDERS,),
                ),
            )
        )
    pairs = critical_pairs(theory.signature, rules, max_steps)
    failing = [pair for pair in pairs if not pair.joinable]
    if failing:
        listed = "; ".join(pair.describe() for pair in failing)
        raise NonConfluent(
            f"syntax {theory.signature.name!r}: {len(failing)} critical "
            f"pair(s) do not join: {listed}"
        )
    if proof is not None:
        evidence: Proved | Assumed = Proved(
            argument="docs/semantics/equations.md#confluence",
            sources=(_PATTERN_CONFLUENCE,),
        )
    else:
        evidence = Assumed(
            declared_by=f"syntax {theory.signature.name}",
            reason=(
                "every critical pair joins, and confluence follows by Newman's "
                "lemma from the assumed termination"
            ),
        )
    claims.append(LawClaim(law=CONFLUENCE, subject=subject, evidence=evidence))
    return TheoryReport(termination=proof, pairs=pairs, claims=tuple(claims))

solutions_of

solutions_of(pattern: Pattern, term: Term, signature: Signature) -> Mapping[str, Solution] | None

Match a term against a pattern; a convenience over match.

PARAMETER DESCRIPTION
pattern

The pattern.

TYPE: Pattern

term

The term.

TYPE: Term

signature

The signature.

TYPE: Signature

RETURNS DESCRIPTION
Mapping or None

The solutions, or None.

Source code in src/quivers/structural/rewriting.py
def solutions_of(
    pattern: Pattern, term: Term, signature: Signature
) -> Mapping[str, Solution] | None:
    """Match a term against a pattern; a convenience over `match`.

    Parameters
    ----------
    pattern : Pattern
        The pattern.
    term : Term
        The term.
    signature : Signature
        The signature.

    Returns
    -------
    Mapping or None
        The solutions, or ``None``.
    """
    return match(pattern, term, signature)