Skip to content

Slotted e-graphs

Laws that cannot be oriented are decided by equality saturation over a slotted e-graph, whose classes abstract free variables into slots, followed by least-cost extraction (Equations and normalization §6).

egraph

Equality saturation with slotted e-graphs for laws that cannot be oriented.

Associativity and commutativity have no terminating orientation, so a theory sends such laws to equality saturation [@willsey2021egg]: an e-graph holds a set of terms closed under congruence, each law is applied in both directions until nothing new is learned or a limit is reached, and a term of least cost is extracted from the class of the input.

Terms with binders are stored in a slotted e-graph [@schneider2025slotted]. An e-class abstracts the free variables of its terms into slots, so terms that differ only by a renaming of their free variables, such as the body of one abstraction placed at two depths, share one class; a reference to a class instantiates its slots with variables. A class also records the slot permutations it is invariant under, so commutativity is a symmetry of one class rather than two classes. De Bruijn indices make alpha-equivalent terms identical before any of this.

The backend applies a law l = r when it is regular and renaming: both sides are in Miller's pattern fragment, with every metavariable applied to bound variables only, and they use the same metavariables. Instantiating such a law renames and never substitutes a term, which is exactly what slots express; the theory refuses other laws for this backend and names the property they lack. A data metavariable binds the data leaf at its position, and the other side puts that leaf back.

VARIABLE_CLASS module-attribute

VARIABLE_CLASS = -1

The class a variable node's single child points at: the variable itself.

A variable node BoundVar has one child whose one slot image is the variable's index, so a variable's free variable is computed like any other node's and the variable class has one slot.

MetaBinding

MetaBinding = tuple[Ref, int] | str

What a law's metavariable is bound to while it is applied.

A metavariable at a term position is bound to a class, its slot images in the redex context extended by the metavariable's arity, with the arity; a data metavariable is bound to the key of its data leaf.

SaturationError

Bases: ValueError

A law is outside the saturation backend, or saturation hit a limit.

Ref didactic-model

Ref(*, eclass: int, slots: tuple[int, ...] = ())

Bases: Model

A class instantiated at variables.

PARAMETER DESCRIPTION
eclass

The class.

TYPE: int

slots

The variable each slot of the class stands for, as an index in the context of the reference.

TYPE: tuple of int DEFAULT: ()

Child didactic-model

Child(*, ref: Ref | None = None, bound: int = 0, leaf: str = '')

Bases: Model

One argument of an e-node.

PARAMETER DESCRIPTION
ref

The argument's class, with slot images in the argument's context (the node's context extended by bound variables), or None for a data leaf.

TYPE: Ref or None DEFAULT: None

bound

The variables the argument binds.

TYPE: int DEFAULT: 0

leaf

The data leaf, rendered with its type, when ref is None.

TYPE: str DEFAULT: ''

ENode didactic-model

ENode(*, op: str, children: tuple[Child, ...] = ())

Bases: Model

An operator applied to class references: one way to build a class.

PARAMETER DESCRIPTION
op

The constructor, or BoundVar for the variable node.

TYPE: str

children

Its arguments.

TYPE: tuple of Child DEFAULT: ()

Leaf didactic-model

Leaf(*, value: DataLeaf = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

A data leaf kept with its value for extraction.

PARAMETER DESCRIPTION
value

The value.

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

EGraph

EGraph(signature: Signature)

A slotted e-graph over the terms of a signature.

PARAMETER DESCRIPTION
signature

The signature.

TYPE: Signature

Source code in src/quivers/structural/egraph.py
def __init__(self, signature: Signature) -> None:
    self.signature = signature
    self.classes: list[_Class] = []
    self.memo: dict[ENode, Ref] = {}
    self.leaves: dict[str, DataLeaf] = {}
    self.pending = False

find

find(ref: Ref) -> Ref

The canonical reference equal to a reference.

PARAMETER DESCRIPTION
ref

The reference.

TYPE: Ref

RETURNS DESCRIPTION
Ref

A reference to the root class, slots composed along the path.

Source code in src/quivers/structural/egraph.py
def find(self, ref: Ref) -> Ref:
    """The canonical reference equal to a reference.

    Parameters
    ----------
    ref : Ref
        The reference.

    Returns
    -------
    Ref
        A reference to the root class, slots composed along the path.
    """
    if ref.eclass == VARIABLE_CLASS:
        return ref
    eclass, slots = ref.eclass, ref.slots
    while True:
        link = self.classes[eclass].parent
        if link is None:
            return Ref(eclass=eclass, slots=slots)
        parent, mapping = link
        images = [0] * self.classes[parent].arity
        for slot, target in enumerate(mapping):
            images[target] = slots[slot]
        eclass, slots = parent, tuple(images)

same

same(left: Ref, right: Ref) -> bool

Whether two references denote equal terms.

PARAMETER DESCRIPTION
left

The references.

TYPE: Ref

right

The references.

TYPE: Ref

RETURNS DESCRIPTION
bool

True when they reach one class with slot images related by one of its symmetries.

Source code in src/quivers/structural/egraph.py
def same(self, left: Ref, right: Ref) -> bool:
    """Whether two references denote equal terms.

    Parameters
    ----------
    left, right : Ref
        The references.

    Returns
    -------
    bool
        ``True`` when they reach one class with slot images related by
        one of its symmetries.
    """
    one, two = self.find(left), self.find(right)
    if one.eclass != two.eclass:
        return False
    if one.eclass == VARIABLE_CLASS:
        return one.slots == two.slots
    group = self.classes[one.eclass].symmetries
    return any(
        tuple(one.slots[g[k]] for k in range(len(g))) == two.slots for g in group
    )

add_node

add_node(node: ENode) -> Ref

Add a node and return the reference that denotes it.

PARAMETER DESCRIPTION
node

The node, with slot images in its context.

TYPE: ENode

RETURNS DESCRIPTION
Ref

Its class instantiated at the node's free variables.

Source code in src/quivers/structural/egraph.py
def add_node(self, node: ENode) -> Ref:
    """Add a node and return the reference that denotes it.

    Parameters
    ----------
    node : ENode
        The node, with slot images in its context.

    Returns
    -------
    Ref
        Its class instantiated at the node's free variables.
    """
    shape, free = _canonical(self._normalize_children(node))
    known = self.memo.get(shape)
    if known is not None:
        root = self.find(known)
        return Ref(eclass=root.eclass, slots=tuple(free[k] for k in root.slots))
    eclass = len(self.classes)
    record = _Class(len(free))
    record.nodes[shape] = tuple(range(len(free)))
    self.classes.append(record)
    self.memo[shape] = Ref(eclass=eclass, slots=tuple(range(len(free))))
    return Ref(eclass=eclass, slots=free)

add

add(term: Term) -> Ref

Add a term and return its reference.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

RETURNS DESCRIPTION
Ref

The term's class, its slots at the term's free variables.

Source code in src/quivers/structural/egraph.py
def add(self, term: Term) -> Ref:
    """Add a term and return its reference.

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

    Returns
    -------
    Ref
        The term's class, its slots at the term's free variables.
    """
    if term.op == BOUND_VAR:
        index = term.args[0]
        assert isinstance(index, int)
        return self.variable(index)
    constructor = self.signature.constructor(term.op)
    children: list[Child] = []
    for position, argument in enumerate(term.args):
        bound = len(constructor.bound_at(position))
        if isinstance(argument, Term):
            children.append(Child(ref=self.add(argument), bound=bound))
        else:
            key = _leaf_key(argument)
            self.leaves[key] = argument
            children.append(Child(ref=None, bound=bound, leaf=key))
    return self.add_node(ENode(op=term.op, children=tuple(children)))

variable

variable(index: int) -> Ref

The reference of a variable.

PARAMETER DESCRIPTION
index

The de Bruijn index.

TYPE: int

RETURNS DESCRIPTION
Ref

The one-slot variable class at that index.

Source code in src/quivers/structural/egraph.py
def variable(self, index: int) -> Ref:
    """The reference of a variable.

    Parameters
    ----------
    index : int
        The de Bruijn index.

    Returns
    -------
    Ref
        The one-slot variable class at that index.
    """
    marker = Child(ref=Ref(eclass=VARIABLE_CLASS, slots=(index,)))
    return self.add_node(ENode(op=BOUND_VAR, children=(marker,)))

union

union(left: Ref, right: Ref) -> bool

Record that two references denote equal terms.

PARAMETER DESCRIPTION
left

References in one context, with the same free variables.

TYPE: Ref

right

References in one context, with the same free variables.

TYPE: Ref

RETURNS DESCRIPTION
bool

Whether anything new was learned.

RAISES DESCRIPTION
SaturationError

If the two have different free variables, which a regular law never produces.

Source code in src/quivers/structural/egraph.py
def union(self, left: Ref, right: Ref) -> bool:
    """Record that two references denote equal terms.

    Parameters
    ----------
    left, right : Ref
        References in one context, with the same free variables.

    Returns
    -------
    bool
        Whether anything new was learned.

    Raises
    ------
    SaturationError
        If the two have different free variables, which a regular law
        never produces.
    """
    one, two = self.find(left), self.find(right)
    if sorted(one.slots) != sorted(two.slots):
        raise SaturationError(
            "an equation related terms with different free variables"
        )
    if one.eclass == two.eclass:
        permutation = tuple(one.slots.index(image) for image in two.slots)
        record = self.classes[one.eclass]
        if permutation in record.symmetries:
            return False
        record.symmetries = _closure(
            set(record.symmetries) | {permutation}, record.arity
        )
        self.pending = True
        return True
    mapping = tuple(one.slots.index(image) for image in two.slots)
    child = self.classes[two.eclass]
    root = self.classes[one.eclass]
    child.parent = (one.eclass, mapping)
    for node, slots in child.nodes.items():
        root.nodes[node] = tuple(mapping[s] for s in slots)
    inverse = _inverse(mapping)
    conjugated = {
        tuple(mapping[g[inverse[k]]] for k in range(len(g)))
        for g in child.symmetries
    }
    root.symmetries = _closure(set(root.symmetries) | conjugated, root.arity)
    child.nodes = {}
    self.pending = True
    return True

rebuild

rebuild() -> None

Restore congruence: equal children make equal parents.

Every node is re-canonicalized against the current classes, and two nodes with one canonical form are unified, until nothing changes; the node tables and the memo are then rebuilt.

Source code in src/quivers/structural/egraph.py
def rebuild(self) -> None:
    """Restore congruence: equal children make equal parents.

    Every node is re-canonicalized against the current classes, and
    two nodes with one canonical form are unified, until nothing
    changes; the node tables and the memo are then rebuilt.
    """
    while self.pending:
        self.pending = False
        canon: dict[ENode, Ref] = {}
        for eclass, record in enumerate(self.classes):
            if record.parent is not None:
                continue
            for node, slots in list(record.nodes.items()):
                placed = _instantiate(node, slots)
                shape, free = _canonical(self._normalize_children(placed))
                here = Ref(eclass=eclass, slots=_inverse(free))
                known = canon.get(shape)
                if known is None:
                    canon[shape] = here
                else:
                    self.union(known, here)
        if self.pending:
            continue
        for record in self.classes:
            record.nodes = {}
        self.memo = {}
        for shape, ref in canon.items():
            root = self.find(ref)
            self.classes[root.eclass].nodes[shape] = _inverse(root.slots)
            self.memo[shape] = root

nodes

nodes(ref: Ref) -> Iterator[ENode]

The nodes of a reference's class, instantiated at its slots.

Every symmetric orientation of a node is produced, so matching is complete modulo the class's symmetries.

PARAMETER DESCRIPTION
ref

The reference.

TYPE: Ref

YIELDS DESCRIPTION
ENode

Each node, its children's slot images in the reference's context.

Source code in src/quivers/structural/egraph.py
def nodes(self, ref: Ref) -> Iterator[ENode]:
    """The nodes of a reference's class, instantiated at its slots.

    Every symmetric orientation of a node is produced, so matching is
    complete modulo the class's symmetries.

    Parameters
    ----------
    ref : Ref
        The reference.

    Yields
    ------
    ENode
        Each node, its children's slot images in the reference's
        context.
    """
    root = self.find(ref)
    record = self.classes[root.eclass]
    seen: set[ENode] = set()
    for g in record.symmetries:
        oriented = tuple(root.slots[g[k]] for k in range(len(g)))
        for node, slots in list(record.nodes.items()):
            placed = _instantiate(node, [oriented[s] for s in slots])
            if placed not in seen:
                seen.add(placed)
                yield placed

ematch

ematch(pattern: PatternArgument, ref: Ref, depth: int, binding: dict[str, MetaBinding]) -> Iterator[dict[str, MetaBinding]]

Match a renaming pattern against a class.

PARAMETER DESCRIPTION
pattern

The pattern.

TYPE: PatternArgument

ref

The class, its slot images at the pattern's depth.

TYPE: Ref

depth

The number of pattern binders around it.

TYPE: int

binding

Each metavariable's class, its slot images in the redex context extended by the metavariable's arity, with the arity; a data metavariable's leaf key (MetaBinding).

TYPE: dict

YIELDS DESCRIPTION
dict

Each extended binding.

Source code in src/quivers/structural/egraph.py
def ematch(
    self,
    pattern: PatternArgument,
    ref: Ref,
    depth: int,
    binding: dict[str, MetaBinding],
) -> Iterator[dict[str, MetaBinding]]:
    """Match a renaming pattern against a class.

    Parameters
    ----------
    pattern : PatternArgument
        The pattern.
    ref : Ref
        The class, its slot images at the pattern's depth.
    depth : int
        The number of pattern binders around it.
    binding : dict
        Each metavariable's class, its slot images in the redex
        context extended by the metavariable's arity, with the arity;
        a data metavariable's leaf key (`MetaBinding`).

    Yields
    ------
    dict
        Each extended binding.
    """
    if isinstance(pattern, PatternVariable):
        if self.same(ref, self.variable(pattern.index)):
            yield binding
        return
    if isinstance(pattern, Metavariable):
        positions: dict[int, int] = {}
        for position, argument in enumerate(pattern.args):
            assert isinstance(argument, PatternVariable)
            positions[argument.index] = position
        arity = len(pattern.args)
        root = self.find(ref)
        images: list[int] = []
        for image in root.slots:
            if image < depth:
                if image not in positions:
                    return
                images.append(arity - 1 - positions[image])
            else:
                images.append(image - depth + arity)
        solution = (Ref(eclass=root.eclass, slots=tuple(images)), arity)
        known = binding.get(pattern.name)
        if known is None:
            yield {**binding, pattern.name: solution}
        elif (
            not isinstance(known, str)
            and known[1] == arity
            and self.same(known[0], solution[0])
        ):
            yield binding
        return
    if isinstance(pattern, PatternApplication):
        arities = self.signature.constructor(pattern.op).binding_arity
        for node in self.nodes(ref):
            if node.op != pattern.op or len(node.children) != len(pattern.args):
                continue
            yield from self._match_children(
                pattern, arities, node, 0, depth, binding
            )

build

build(pattern: PatternArgument, binding: Mapping[str, MetaBinding], depth: int) -> Ref

Add the instance of a renaming pattern.

PARAMETER DESCRIPTION
pattern

The pattern.

TYPE: PatternArgument

binding

The metavariables' classes and data metavariables' leaf keys.

TYPE: Mapping

depth

The pattern binders around it.

TYPE: int

RETURNS DESCRIPTION
Ref

The instance, its slots in the redex context at depth.

RAISES DESCRIPTION
SaturationError

If a metavariable is unbound or applied to a non-variable.

Source code in src/quivers/structural/egraph.py
def build(
    self,
    pattern: PatternArgument,
    binding: Mapping[str, MetaBinding],
    depth: int,
) -> Ref:
    """Add the instance of a renaming pattern.

    Parameters
    ----------
    pattern : PatternArgument
        The pattern.
    binding : Mapping
        The metavariables' classes and data metavariables' leaf keys.
    depth : int
        The pattern binders around it.

    Returns
    -------
    Ref
        The instance, its slots in the redex context at ``depth``.

    Raises
    ------
    SaturationError
        If a metavariable is unbound or applied to a non-variable.
    """
    if isinstance(pattern, PatternVariable):
        return self.variable(pattern.index)
    if isinstance(pattern, Metavariable):
        found = binding.get(pattern.name)
        if found is None:
            raise SaturationError(f"metavariable {pattern.name!r} is unbound")
        if isinstance(found, str):
            raise SaturationError(
                f"data metavariable {pattern.name!r} stands at a term position"
            )
        ref, arity = found
        arguments: list[int] = []
        for argument in pattern.args:
            if not isinstance(argument, PatternVariable):
                raise SaturationError(
                    "a law instantiates a metavariable with a term"
                )
            arguments.append(argument.index)
        images = tuple(
            arguments[arity - 1 - image] if image < arity else image - arity + depth
            for image in ref.slots
        )
        return self.find(ref.with_(slots=images))
    if isinstance(pattern, PatternApplication):
        constructor = self.signature.constructor(pattern.op)
        children: list[Child] = []
        for position, argument in enumerate(pattern.args):
            bound = len(constructor.bound_at(position))
            if isinstance(argument, Metavariable) and isinstance(
                datum := binding.get(argument.name), str
            ):
                children.append(Child(ref=None, bound=bound, leaf=datum))
            elif isinstance(
                argument, PatternApplication | Metavariable | PatternVariable
            ):
                children.append(
                    Child(
                        ref=self.build(argument, binding, depth + bound),
                        bound=bound,
                    )
                )
            else:
                key = _leaf_key(argument)
                self.leaves[key] = argument
                children.append(Child(ref=None, bound=bound, leaf=key))
        return self.add_node(ENode(op=pattern.op, children=tuple(children)))
    raise SaturationError("unexpected pattern node")

roots

roots() -> list[Ref]

A reference to every root class at its own slots.

RETURNS DESCRIPTION
list of Ref

The classes.

Source code in src/quivers/structural/egraph.py
def roots(self) -> list[Ref]:
    """A reference to every root class at its own slots.

    Returns
    -------
    list of Ref
        The classes.
    """
    return [
        Ref(eclass=i, slots=tuple(range(c.arity)))
        for i, c in enumerate(self.classes)
        if c.parent is None
    ]

size

size() -> int

The number of nodes.

RETURNS DESCRIPTION
int

The node count over root classes.

Source code in src/quivers/structural/egraph.py
def size(self) -> int:
    """The number of nodes.

    Returns
    -------
    int
        The node count over root classes.
    """
    return sum(len(c.nodes) for c in self.classes if c.parent is None)

CostModel didactic-model

CostModel(*, kind: str = 'size', weights: dict[str, float] = field(default_factory=dict))

Bases: Model

The cost of a term for extraction: a weight per constructor.

PARAMETER DESCRIPTION
kind

"size" sums the weights of a term's nodes; "depth" takes the weight of the root plus the costliest argument.

TYPE: str DEFAULT: 'size'

weights

Per-constructor weights; absent constructors weigh one.

TYPE: dict of str to float DEFAULT: field(default_factory=dict)

combine

combine(op: str, children: Sequence[float]) -> float

The cost of a node from its children's costs.

PARAMETER DESCRIPTION
op

The constructor.

TYPE: str

children

The children's costs.

TYPE: Sequence of float

RETURNS DESCRIPTION
float

The node's cost.

RAISES DESCRIPTION
SaturationError

If the kind is unknown.

Source code in src/quivers/structural/egraph.py
def combine(self, op: str, children: Sequence[float]) -> float:
    """The cost of a node from its children's costs.

    Parameters
    ----------
    op : str
        The constructor.
    children : Sequence of float
        The children's costs.

    Returns
    -------
    float
        The node's cost.

    Raises
    ------
    SaturationError
        If the kind is unknown.
    """
    own = self.weights.get(op, 1.0)
    if self.kind == "size":
        return own + sum(children)
    if self.kind == "depth":
        return own + max(children, default=0.0)
    raise SaturationError(f"unknown extraction cost {self.kind!r}")

SaturationResult didactic-model

SaturationResult(*, saturated: bool, iterations: int, nodes: int)

Bases: ValueModel

What a saturation run reached.

PARAMETER DESCRIPTION
saturated

Whether a pass found nothing new, so the e-graph is closed under the laws.

TYPE: bool

iterations

The passes run.

TYPE: int

nodes

The final node count.

TYPE: int

Saturation

Saturation(signature: Signature, laws: Sequence[Equation], cost: CostModel, max_iterations: int = 30, max_nodes: int = 20000)

Equality saturation for a signature's renaming laws.

PARAMETER DESCRIPTION
signature

The signature.

TYPE: Signature

laws

The laws, each checked by check_renaming_law.

TYPE: Sequence of Equation

cost

The extraction cost.

TYPE: CostModel

max_iterations

The passes allowed.

TYPE: int DEFAULT: 30

max_nodes

The node budget.

TYPE: int DEFAULT: 20000

Source code in src/quivers/structural/egraph.py
def __init__(
    self,
    signature: Signature,
    laws: Sequence[Equation],
    cost: CostModel,
    max_iterations: int = 30,
    max_nodes: int = 20_000,
) -> None:
    for law in laws:
        check_renaming_law(law, signature)
    self.signature = signature
    self.laws = tuple(laws)
    self.cost = cost
    self.max_iterations = max_iterations
    self.max_nodes = max_nodes

saturate

saturate(graph: EGraph) -> SaturationResult

Apply every law in both directions until nothing changes.

PARAMETER DESCRIPTION
graph

The e-graph, extended in place.

TYPE: EGraph

RETURNS DESCRIPTION
SaturationResult

Whether it saturated within the limits.

Source code in src/quivers/structural/egraph.py
def saturate(self, graph: EGraph) -> SaturationResult:
    """Apply every law in both directions until nothing changes.

    Parameters
    ----------
    graph : EGraph
        The e-graph, extended in place.

    Returns
    -------
    SaturationResult
        Whether it saturated within the limits.
    """
    for iteration in itertools.count(1):
        matches: list[tuple[Equation, bool, Ref, dict[str, MetaBinding]]] = []
        for law in self.laws:
            for forward in (True, False):
                source = law.left if forward else law.right
                if _bare(source):
                    continue
                for ref in graph.roots():
                    for binding in graph.ematch(source, ref, 0, {}):
                        matches.append((law, forward, ref, binding))
        changed = False
        for law, forward, ref, binding in matches:
            target = law.right if forward else law.left
            built = graph.build(target, binding, 0)
            if graph.union(ref, built):
                changed = True
        graph.rebuild()
        if not changed:
            return SaturationResult(
                saturated=True, iterations=iteration, nodes=graph.size()
            )
        if iteration >= self.max_iterations or graph.size() > self.max_nodes:
            return SaturationResult(
                saturated=False, iterations=iteration, nodes=graph.size()
            )
    raise AssertionError("unreachable")

extract

extract(graph: EGraph, ref: Ref) -> Term

The least-cost term of a class.

PARAMETER DESCRIPTION
graph

The e-graph.

TYPE: EGraph

ref

The class, instantiated.

TYPE: Ref

RETURNS DESCRIPTION
Term

The cheapest term under the cost model.

RAISES DESCRIPTION
SaturationError

If the class has no finite term.

Source code in src/quivers/structural/egraph.py
def extract(self, graph: EGraph, ref: Ref) -> Term:
    """The least-cost term of a class.

    Parameters
    ----------
    graph : EGraph
        The e-graph.
    ref : Ref
        The class, instantiated.

    Returns
    -------
    Term
        The cheapest term under the cost model.

    Raises
    ------
    SaturationError
        If the class has no finite term.
    """
    best: dict[int, tuple[float, ENode, tuple[int, ...]]] = {}
    changed = True
    while changed:
        changed = False
        for root in graph.roots():
            record = graph.classes[root.eclass]
            for node, slots in record.nodes.items():
                costs: list[float] = []
                complete = True
                for child in node.children:
                    if child.ref is None or child.ref.eclass == VARIABLE_CLASS:
                        continue
                    found = best.get(graph.find(child.ref).eclass)
                    if found is None:
                        complete = False
                        break
                    costs.append(found[0])
                if not complete:
                    continue
                cost = self.cost.combine(node.op, costs)
                current = best.get(root.eclass)
                if current is None or cost < current[0]:
                    best[root.eclass] = (cost, node, slots)
                    changed = True
    return self._term(graph, graph.find(ref), best)

normalize

normalize(term: Term) -> tuple[Term, SaturationResult]

The least-cost term equal to a term under the laws.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

RETURNS DESCRIPTION
tuple of Term and SaturationResult

The extracted term and how saturation went.

Source code in src/quivers/structural/egraph.py
def normalize(self, term: Term) -> tuple[Term, SaturationResult]:
    """The least-cost term equal to a term under the laws.

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

    Returns
    -------
    tuple of Term and SaturationResult
        The extracted term and how saturation went.
    """
    graph = EGraph(self.signature)
    ref = graph.add(term)
    result = self.saturate(graph)
    return self.extract(graph, ref), result

equal_modulo

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

Whether two terms are equal under the laws.

PARAMETER DESCRIPTION
left

The terms.

TYPE: Term

right

The terms.

TYPE: Term

RETURNS DESCRIPTION
bool

True when saturation puts them in one class; False when it saturates without doing so.

RAISES DESCRIPTION
SaturationError

If saturation stops at a limit before deciding.

Source code in src/quivers/structural/egraph.py
def equal_modulo(self, left: Term, right: Term) -> bool:
    """Whether two terms are equal under the laws.

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

    Returns
    -------
    bool
        ``True`` when saturation puts them in one class; ``False`` when
        it saturates without doing so.

    Raises
    ------
    SaturationError
        If saturation stops at a limit before deciding.
    """
    graph = EGraph(self.signature)
    one, two = graph.add(left), graph.add(right)
    result = self.saturate(graph)
    if graph.same(one, two):
        return True
    if not result.saturated:
        raise SaturationError(
            f"saturation stopped after {result.iterations} passes and "
            f"{result.nodes} nodes without deciding the equation"
        )
    return False

check_renaming_law

check_renaming_law(law: Equation, signature: Signature) -> None

Require a law the saturation backend can apply.

Both sides use the same metavariables (the law is regular), so equal terms have the same free variables. Each side is either in Miller's pattern fragment, with every metavariable applied to distinct bound variables, or a bare metavariable; a law is applied only from a side that is a constructor application, and at least one side is.

PARAMETER DESCRIPTION
law

The law.

TYPE: Equation

signature

The signature.

TYPE: Signature

RAISES DESCRIPTION
SaturationError

If the sides use different metavariables, both sides are bare metavariables, or a side is outside the pattern fragment; the message names the law.

Source code in src/quivers/structural/egraph.py
def check_renaming_law(law: Equation, signature: Signature) -> None:
    """Require a law the saturation backend can apply.

    Both sides use the same metavariables (the law is regular), so equal
    terms have the same free variables. Each side is either in Miller's
    pattern fragment, with every metavariable applied to distinct bound
    variables, or a bare metavariable; a law is applied only from a side
    that is a constructor application, and at least one side is.

    Parameters
    ----------
    law : Equation
        The law.
    signature : Signature
        The signature.

    Raises
    ------
    SaturationError
        If the sides use different metavariables, both sides are bare
        metavariables, or a side is outside the pattern fragment; the
        message names the law.
    """
    left = {m.name for m in metavariables(law.left)}
    right = {m.name for m in metavariables(law.right)}
    if left != right:
        missing = sorted(left ^ right)
        raise SaturationError(
            f"law {law.name!r} is not regular: metavariable {missing[0]!r} occurs on "
            "one side only, so the two sides have different free variables"
        )
    sides = [side for side in (law.left, law.right) if not _bare(side)]
    if not sides:
        raise SaturationError(
            f"law {law.name!r} equates two metavariables and applies nowhere"
        )
    for side in sides:
        try:
            check_miller_pattern(side, signature)
        except PatternError as error:
            raise SaturationError(
                f"law {law.name!r} is outside the saturation backend: {error}"
            ) from error