Skip to content

Binding operations

Terms of a binding signature are stored with de Bruijn indices in one index space shared by every sort, so alpha-equivalence is structural equality. This module defines the operations every signature gets: weakening and renaming, substitution and instantiation, free variables, alpha-equality, a hash and an order that agree with it, conversion to and from named terms, printing with fresh names, and a generic fold whose algebra receives each bound argument as a Scoped value (Tree and graph autoencoders §1.2.1).

binding

Generated operations on the terms of a second-order binding signature.

Following Fiore, Plotkin, and Turi, the terms of a signature with binding are the initial algebra of a signature endofunctor on presheaves over contexts, and substitution is its monoid structure [@fiore1999abstract]. The terms of a Signature are well-scoped de Bruijn terms in the style of Autosubst 2 [@stark2019autosubst]: a variable is BoundVar(i), the i-th enclosing bound variable counted from the innermost, and an argument that binds k variables is a term in a context extended by k. Bound names are kept by the signature for printing only, so alpha-equivalent terms are structurally equal and alpha-equality, hashing, and ordering are structural.

Every signature has the operations of this module, generated from its binding arities rather than written per signature:

  • rename and weaken, the renamings;
  • substitute (from quivers.structural.signature), the simultaneous substitution, and instantiate, the substitution of the variables of one binder;
  • free_variables;
  • alpha_equal, content_hash, compare, and sort_key;
  • to_named, from_named, and show, which print with fresh names;
  • fold, the unique map into an algebra that respects substitution, the Sigma-monoid fold of Fiore and Szamozvancev [@fiore2022formal].

A context is written as a tuple of sorts, outermost first, so the variable BoundVar(i) of a context ctx has sort ctx[-1 - i].

BOUND_VAR module-attribute

BOUND_VAR = 'BoundVar'

The operator of a de Bruijn variable.

NamedArgument

NamedArgument = NamedTerm | Name | Abstraction | DataLeaf

An argument of a named term.

FoldArgument

FoldArgument = V | Scoped[V] | DataLeaf

What an algebra operation receives at one argument position.

Substitution didactic-model

Substitution(*, replacements: tuple[Term, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), shift: int = 0)

Bases: ValueModel

A simultaneous substitution of the free variables of de-Bruijn terms.

The variable with index i becomes replacements[i] when i is below their number n, and the variable i - n + shift otherwise. Every substitution of terms in a context of n + k variables by terms in a context of shift + k variables has this form. A renaming is a substitution whose replacements are variables.

PARAMETER DESCRIPTION
replacements

The replacements of the innermost variables.

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

shift

Where the remaining variables go; at least zero.

TYPE: int DEFAULT: 0

RAISES DESCRIPTION
ValidationError

If the shift is negative.

weakening classmethod

weakening(amount: int) -> Substitution

The renaming that makes room for new innermost variables.

PARAMETER DESCRIPTION
amount

How many variables are added.

TYPE: int

RETURNS DESCRIPTION
Substitution

The variable i goes to i + amount.

Source code in src/quivers/structural/signature.py
@classmethod
def weakening(cls, amount: int) -> Substitution:
    """The renaming that makes room for new innermost variables.

    Parameters
    ----------
    amount : int
        How many variables are added.

    Returns
    -------
    Substitution
        The variable ``i`` goes to ``i + amount``.
    """
    return cls(shift=amount)

renaming classmethod

renaming(targets: tuple[int, ...], shift: int) -> Substitution

The renaming that sends variable i to targets[i].

PARAMETER DESCRIPTION
targets

The new index of each of the innermost variables.

TYPE: tuple of int

shift

Where the remaining variables go.

TYPE: int

RETURNS DESCRIPTION
Substitution

The renaming.

Source code in src/quivers/structural/signature.py
@classmethod
def renaming(cls, targets: tuple[int, ...], shift: int) -> Substitution:
    """The renaming that sends variable ``i`` to ``targets[i]``.

    Parameters
    ----------
    targets : tuple of int
        The new index of each of the innermost variables.
    shift : int
        Where the remaining variables go.

    Returns
    -------
    Substitution
        The renaming.
    """
    return cls(replacements=tuple(bound_var(i) for i in targets), shift=shift)

image

image(index: int) -> Term

The replacement of one variable.

PARAMETER DESCRIPTION
index

The variable.

TYPE: int

RETURNS DESCRIPTION
Term

Its replacement.

Source code in src/quivers/structural/signature.py
def image(self, index: int) -> Term:
    """The replacement of one variable.

    Parameters
    ----------
    index : int
        The variable.

    Returns
    -------
    Term
        Its replacement.
    """
    if index < len(self.replacements):
        return self.replacements[index]
    return bound_var(index - len(self.replacements) + self.shift)

lift

lift(count: int, signature: Signature) -> Substitution

The substitution under count new innermost variables.

PARAMETER DESCRIPTION
count

The variables a binder introduces.

TYPE: int

signature

The signature of the terms.

TYPE: Signature

RETURNS DESCRIPTION
Substitution

The new variables go to themselves, and the replacements are weakened past them.

Source code in src/quivers/structural/signature.py
def lift(self, count: int, signature: Signature) -> Substitution:
    """The substitution under ``count`` new innermost variables.

    Parameters
    ----------
    count : int
        The variables a binder introduces.
    signature : Signature
        The signature of the terms.

    Returns
    -------
    Substitution
        The new variables go to themselves, and the replacements are
        weakened past them.
    """
    if count == 0:
        return self
    weaken = Substitution.weakening(count)
    return Substitution(
        replacements=(
            *(bound_var(i) for i in range(count)),
            *(substitute(item, weaken, signature) for item in self.replacements),
        ),
        shift=self.shift + count,
    )

then

then(other: Substitution, signature: Signature) -> Substitution

The substitution that applies this one and then another.

PARAMETER DESCRIPTION
other

The substitution applied second.

TYPE: Substitution

signature

The signature of the terms.

TYPE: Signature

RETURNS DESCRIPTION
Substitution

substitute(t, self.then(other)) == substitute(substitute(t, self), other) for every term t.

Source code in src/quivers/structural/signature.py
def then(self, other: Substitution, signature: Signature) -> Substitution:
    """The substitution that applies this one and then another.

    Parameters
    ----------
    other : Substitution
        The substitution applied second.
    signature : Signature
        The signature of the terms.

    Returns
    -------
    Substitution
        ``substitute(t, self.then(other)) == substitute(substitute(t,
        self), other)`` for every term ``t``.
    """
    first = tuple(substitute(item, other, signature) for item in self.replacements)
    count = len(other.replacements)
    extra = other.replacements[self.shift :] if self.shift < count else ()
    return Substitution(
        replacements=(*first, *extra),
        shift=other.shift + max(0, self.shift - count),
    )

SubstitutionError

Bases: ValueError

A substitution cannot be applied to a term.

BindingError

Bases: ValueError

A term does not fit the scope or the sorts its signature declares.

Name didactic-model

Name(*, name: str)

Bases: Model

A variable written by name in a named term.

PARAMETER DESCRIPTION
name

The variable's name.

TYPE: str

Abstraction didactic-model

Abstraction(*, names: tuple[str, ...] = (), body: NamedTerm | Name = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

An argument that binds names: the x, y. body of Op(x, y. body).

PARAMETER DESCRIPTION
names

The bound names, outermost first.

TYPE: tuple of str DEFAULT: ()

body

The argument.

TYPE: NamedTerm or Name DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

NamedTerm didactic-model

NamedTerm(*, op: str, args: tuple = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

A term written with named variables.

An argument that binds variables is an Abstraction; a variable is a Name. Named terms are what a reader writes and what show prints; from_named gives the de Bruijn term.

PARAMETER DESCRIPTION
op

The constructor.

TYPE: str

args

Its arguments.

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

Scoped didactic-model

Scoped(*, arity: int, apply: Callable[[tuple[V, ...]], V] = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

The value of a binding argument: a function of its bound variables.

Applying it to one value per bound variable, outermost first, folds the argument in the environment extended by them. It is the abstraction of a Sigma-monoid's operations over the context presheaf.

PARAMETER DESCRIPTION
arity

The number of variables bound.

TYPE: int

apply

The fold of the argument as a function of the bound values.

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

__call__

__call__(*values: V) -> V

Fold the argument with its bound variables given values.

PARAMETER DESCRIPTION
*values

One value per bound variable, outermost first.

TYPE: V DEFAULT: ()

RETURNS DESCRIPTION
V

The fold of the argument.

RAISES DESCRIPTION
BindingError

If the number of values differs from the binding arity.

Source code in src/quivers/structural/binding.py
def __call__(self, *values: V) -> V:
    """Fold the argument with its bound variables given values.

    Parameters
    ----------
    *values : V
        One value per bound variable, outermost first.

    Returns
    -------
    V
        The fold of the argument.

    Raises
    ------
    BindingError
        If the number of values differs from the binding arity.
    """
    if len(values) != self.arity:
        raise BindingError(
            f"a binding argument takes {self.arity} values, got {len(values)}"
        )
    return self.apply(tuple(values))

SubstitutionAlgebra

Bases: Protocol

An algebra of a binding signature: one operation per constructor.

operation receives, for each argument, the fold of an unbound object argument, a Scoped function for a binding argument, the raw value of a data argument, or the environment's value of the variable at an index argument. Variables are interpreted by the environment, so the fold respects substitution: fold(substitute(t, s), env) equals fold(t, env') where env' holds the fold of each replacement.

operation

operation(op: str, arguments: tuple[FoldArgument[V], ...]) -> V

Interpret one constructor.

PARAMETER DESCRIPTION
op

The constructor.

TYPE: str

arguments

Its folded arguments.

TYPE: tuple

RETURNS DESCRIPTION
V

The value.

Source code in src/quivers/structural/binding.py
def operation(self, op: str, arguments: tuple[FoldArgument[V], ...]) -> V:
    """Interpret one constructor.

    Parameters
    ----------
    op : str
        The constructor.
    arguments : tuple
        Its folded arguments.

    Returns
    -------
    V
        The value.
    """
    ...

Built didactic-model

Built(*, at: Callable[[int], Term] = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

A term as a function of the depth of the context it is placed in.

The carrier of TermAlgebra: a variable is a de Bruijn level, so its index depends on how deep the context is where the term is used.

PARAMETER DESCRIPTION
at

The term at each depth.

TYPE: Callable[[int], Term] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

TermAlgebra

TermAlgebra(signature: Signature)

The initial algebra: folding a term rebuilds it, as a check of fold.

PARAMETER DESCRIPTION
signature

The signature.

TYPE: Signature

Source code in src/quivers/structural/binding.py
def __init__(self, signature: Signature) -> None:
    self.signature = signature

operation

operation(op: str, arguments: tuple[FoldArgument[Built], ...]) -> Built

Rebuild one constructor at any depth.

PARAMETER DESCRIPTION
op

The constructor.

TYPE: str

arguments

Its folded arguments.

TYPE: tuple

RETURNS DESCRIPTION
Built

The node as a function of the depth of its context.

Source code in src/quivers/structural/binding.py
def operation(self, op: str, arguments: tuple[FoldArgument[Built], ...]) -> Built:
    """Rebuild one constructor at any depth.

    Parameters
    ----------
    op : str
        The constructor.
    arguments : tuple
        Its folded arguments.

    Returns
    -------
    Built
        The node as a function of the depth of its context.
    """
    constructor = self.signature.constructor(op)

    def at(depth: int) -> Term:
        """Build the node in a context of ``depth`` variables.

        Parameters
        ----------
        depth : int
            The depth.

        Returns
        -------
        Term
            The node.
        """
        built: list[TermArg] = []
        for position, argument in enumerate(arguments):
            bound = constructor.bound_at(position)
            declared = self.signature.sorts[constructor.domain[position]]
            if isinstance(argument, Scoped):
                variables = [_level(depth + k) for k in range(len(bound))]
                built.append(argument(*variables).at(depth + len(bound)))
            elif isinstance(argument, Built):
                value = argument.at(depth)
                if declared.kind == "index":
                    index = value.args[0]
                    assert value.op == BOUND_VAR and isinstance(index, int)
                    built.append(index)
                else:
                    built.append(value)
            else:
                built.append(argument)
        return Term(op=op, args=tuple(built))

    return Built(at=at)

substitute

substitute(term: Term, substitution: Substitution, signature: Signature) -> Term

Apply a substitution to the free variables of a term.

It goes under binders by lifting the substitution, so a replacement is never captured. An argument at an index-sorted position names a variable and may only be renamed. The cost is the size of the term times the cost of weakening each replacement used under binders; the traversal uses an explicit stack.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

substitution

The substitution.

TYPE: Substitution

signature

The signature of the term.

TYPE: Signature

RETURNS DESCRIPTION
Term

The substituted term.

RAISES DESCRIPTION
SubstitutionError

If an operation is undeclared, an index position would receive a term that is not a variable, or an argument's kind does not match its position.

Source code in src/quivers/structural/signature.py
def substitute(term: Term, substitution: Substitution, signature: Signature) -> Term:
    """Apply a substitution to the free variables of a term.

    It goes under binders by lifting the substitution, so a replacement is
    never captured. An argument at an index-sorted position names a
    variable and may only be renamed. The cost is the size of the term
    times the cost of weakening each replacement used under binders; the
    traversal uses an explicit stack.

    Parameters
    ----------
    term : Term
        The term.
    substitution : Substitution
        The substitution.
    signature : Signature
        The signature of the term.

    Returns
    -------
    Term
        The substituted term.

    Raises
    ------
    SubstitutionError
        If an operation is undeclared, an index position would receive a
        term that is not a variable, or an argument's kind does not match
        its position.
    """
    frames: list[tuple[Term, Substitution, tuple[tuple[str, int], ...]]] = []
    built: list[list[TermArg]] = []
    result: Term | None = None

    def deliver(value: Term) -> Term | None:
        """Hand a finished subterm to its parent, or return it at the root.

        Parameters
        ----------
        value : Term
            The finished subterm.

        Returns
        -------
        Term or None
            The value when it is the root, else ``None``.
        """
        if built:
            built[-1].append(value)
            return None
        return value

    def enter(node: Term, sigma: Substitution) -> Term | None:
        """Start a subterm, or finish it at once when it is a variable.

        Parameters
        ----------
        node : Term
            The subterm.
        sigma : Substitution
            The substitution in its scope.

        Returns
        -------
        Term or None
            The root's result when the root is a variable.

        Raises
        ------
        SubstitutionError
            If the operation is undeclared or has the wrong arity.
        """
        if node.op == "BoundVar":
            index = node.args[0]
            assert isinstance(index, int)
            return deliver(sigma.image(index))
        scopes = _scopes(signature, node.op)
        if len(scopes) != len(node.args):
            raise SubstitutionError(
                f"{node.op!r} takes {len(scopes)} arguments, got {len(node.args)}"
            )
        frames.append((node, sigma, scopes))
        built.append([])
        return None

    result = enter(term, substitution)
    while frames:
        node, sigma, scopes = frames[-1]
        position = len(built[-1])
        if position == len(node.args):
            frames.pop()
            arguments = tuple(built.pop())
            result = deliver(Term(op=node.op, args=arguments))
            continue
        sort, count = scopes[position]
        argument = node.args[position]
        inner = sigma.lift(count, signature)
        if isinstance(argument, Term):
            result = enter(argument, inner)
            continue
        declared = signature.sorts.get(sort)
        if declared is not None and declared.kind == "index":
            assert isinstance(argument, int)
            image = inner.image(argument)
            if image.op != "BoundVar":
                raise SubstitutionError(
                    f"index position of {node.op!r} would receive a term that "
                    "is not a variable"
                )
            built[-1].append(image.args[0])
        else:
            built[-1].append(argument)
    assert result is not None
    return result

binder_arity

binder_arity(signature: Signature, op: str) -> tuple[int, ...]

How many variables each argument of a constructor binds.

A binder pattern Lam(x. body) is well formed exactly when it gives each argument as many names as this arity says.

PARAMETER DESCRIPTION
signature

The signature.

TYPE: Signature

op

A constructor of it.

TYPE: str

RETURNS DESCRIPTION
tuple of int

One count per argument.

RAISES DESCRIPTION
KeyError

If op is not a constructor.

Source code in src/quivers/structural/binding.py
def binder_arity(signature: Signature, op: str) -> tuple[int, ...]:
    """How many variables each argument of a constructor binds.

    A binder pattern ``Lam(x. body)`` is well formed exactly when it gives
    each argument as many names as this arity says.

    Parameters
    ----------
    signature : Signature
        The signature.
    op : str
        A constructor of it.

    Returns
    -------
    tuple of int
        One count per argument.

    Raises
    ------
    KeyError
        If ``op`` is not a constructor.
    """
    return signature.constructor(op).binding_arity

argument_context

argument_context(signature: Signature, op: str, position: int, context: tuple[str, ...]) -> tuple[str, ...]

The context of one argument of a constructor.

PARAMETER DESCRIPTION
signature

The signature.

TYPE: Signature

op

The constructor.

TYPE: str

position

The argument.

TYPE: int

context

The sorts of the variables in scope at the constructor, outermost first.

TYPE: tuple of str

RETURNS DESCRIPTION
tuple of str

The context extended by the argument's bound variables.

Source code in src/quivers/structural/binding.py
def argument_context(
    signature: Signature, op: str, position: int, context: tuple[str, ...]
) -> tuple[str, ...]:
    """The context of one argument of a constructor.

    Parameters
    ----------
    signature : Signature
        The signature.
    op : str
        The constructor.
    position : int
        The argument.
    context : tuple of str
        The sorts of the variables in scope at the constructor, outermost
        first.

    Returns
    -------
    tuple of str
        The context extended by the argument's bound variables.
    """
    scope = signature.constructor(op).bound_at(position)
    return context + tuple(variable.sort for variable in scope)

check_term

check_term(term: Term, signature: Signature, context: tuple[str, ...] = (), sort: str | None = None) -> str

Check that a term is well scoped and well sorted, and give its sort.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

signature

Its signature.

TYPE: Signature

context

The sorts of its free variables, outermost first.

TYPE: tuple of str DEFAULT: ()

sort

The sort it must have, or None to accept any object sort.

TYPE: str or None DEFAULT: None

RETURNS DESCRIPTION
str

The term's sort.

RAISES DESCRIPTION
BindingError

If a constructor is undeclared or applied to the wrong number of arguments, an argument has the wrong kind or sort, or a variable is out of scope or of another sort.

Source code in src/quivers/structural/binding.py
def check_term(
    term: Term,
    signature: Signature,
    context: tuple[str, ...] = (),
    sort: str | None = None,
) -> str:
    """Check that a term is well scoped and well sorted, and give its sort.

    Parameters
    ----------
    term : Term
        The term.
    signature : Signature
        Its signature.
    context : tuple of str
        The sorts of its free variables, outermost first.
    sort : str or None
        The sort it must have, or ``None`` to accept any object sort.

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

    Raises
    ------
    BindingError
        If a constructor is undeclared or applied to the wrong number of
        arguments, an argument has the wrong kind or sort, or a variable is
        out of scope or of another sort.
    """
    stack: list[tuple[Term, tuple[str, ...], str | None]] = [(term, context, sort)]
    root_sort: str | None = None
    while stack:
        node, scope, expected = stack.pop()
        found = _node_sort(node, signature, scope)
        if expected is not None and found != expected:
            raise BindingError(
                f"{_describe(node)} has sort {found!r} where {expected!r} is required"
            )
        if root_sort is None:
            root_sort = found
        if node.op == BOUND_VAR:
            continue
        constructor = signature.constructor(node.op)
        for position, (argument_sort, argument) in enumerate(
            zip(constructor.domain, node.args, strict=True)
        ):
            inner = argument_context(signature, node.op, position, scope)
            declared = signature.sorts[argument_sort]
            if declared.kind == "object":
                if not isinstance(argument, Term):
                    raise BindingError(
                        f"{node.op!r} takes a term of sort {argument_sort!r} at "
                        f"position {position}, got {type(argument).__name__}"
                    )
                stack.append((argument, inner, argument_sort))
            elif declared.kind == "index":
                if not isinstance(argument, int) or isinstance(argument, bool):
                    raise BindingError(
                        f"{node.op!r} takes a variable index at position {position}"
                    )
                _variable_sort(argument, inner, argument_sort)
            elif isinstance(argument, Term):
                raise BindingError(
                    f"{node.op!r} takes a data value at position {position}, got a term"
                )
    assert root_sort is not None
    return root_sort

weaken

weaken(term: Term, amount: int, signature: Signature) -> Term

Move a term under amount new innermost variables.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

amount

How many variables are added; at least zero.

TYPE: int

signature

Its signature.

TYPE: Signature

RETURNS DESCRIPTION
Term

The term with each free index raised by amount.

Source code in src/quivers/structural/binding.py
def weaken(term: Term, amount: int, signature: Signature) -> Term:
    """Move a term under ``amount`` new innermost variables.

    Parameters
    ----------
    term : Term
        The term.
    amount : int
        How many variables are added; at least zero.
    signature : Signature
        Its signature.

    Returns
    -------
    Term
        The term with each free index raised by ``amount``.
    """
    return substitute(term, Substitution.weakening(amount), signature)

rename

rename(term: Term, targets: Sequence[int], signature: Signature, shift: int | None = None) -> Term

Apply a renaming: free variable i becomes targets[i].

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

targets

The new index of each of the innermost len(targets) variables.

TYPE: Sequence of int

signature

Its signature.

TYPE: Signature

shift

Where the variables beyond targets go: variable i becomes i - len(targets) + shift. None keeps them in place.

TYPE: int or None DEFAULT: None

RETURNS DESCRIPTION
Term

The renamed term.

Source code in src/quivers/structural/binding.py
def rename(
    term: Term, targets: Sequence[int], signature: Signature, shift: int | None = None
) -> Term:
    """Apply a renaming: free variable ``i`` becomes ``targets[i]``.

    Parameters
    ----------
    term : Term
        The term.
    targets : Sequence of int
        The new index of each of the innermost ``len(targets)`` variables.
    signature : Signature
        Its signature.
    shift : int or None
        Where the variables beyond ``targets`` go: variable ``i`` becomes
        ``i - len(targets) + shift``. ``None`` keeps them in place.

    Returns
    -------
    Term
        The renamed term.
    """
    count = len(targets)
    return substitute(
        term,
        Substitution.renaming(tuple(targets), count if shift is None else shift),
        signature,
    )

instantiate

instantiate(body: Term, values: Sequence[Term], signature: Signature) -> Term

Instantiate the variables of one binder in its argument.

body is an argument that binds len(values) variables, in declaration order, and values are terms in the binder's outer context. instantiate(M, (N,)) is the M[N] of beta reduction.

PARAMETER DESCRIPTION
body

The argument, in the extended context.

TYPE: Term

values

One term per bound variable, outermost first.

TYPE: Sequence of Term

signature

The signature.

TYPE: Signature

RETURNS DESCRIPTION
Term

The body with the bound variables replaced, in the outer context.

Source code in src/quivers/structural/binding.py
def instantiate(body: Term, values: Sequence[Term], signature: Signature) -> Term:
    """Instantiate the variables of one binder in its argument.

    ``body`` is an argument that binds ``len(values)`` variables, in
    declaration order, and ``values`` are terms in the binder's outer
    context. ``instantiate(M, (N,))`` is the ``M[N]`` of beta reduction.

    Parameters
    ----------
    body : Term
        The argument, in the extended context.
    values : Sequence of Term
        One term per bound variable, outermost first.
    signature : Signature
        The signature.

    Returns
    -------
    Term
        The body with the bound variables replaced, in the outer context.
    """
    return substitute(
        body, Substitution(replacements=tuple(reversed(tuple(values)))), signature
    )

free_variables

free_variables(term: Term, signature: Signature) -> frozenset[int]

The free variables of a term.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

signature

Its signature.

TYPE: Signature

RETURNS DESCRIPTION
frozenset of int

Their indices in the term's context.

Source code in src/quivers/structural/binding.py
def free_variables(term: Term, signature: Signature) -> frozenset[int]:
    """The free variables of a term.

    Parameters
    ----------
    term : Term
        The term.
    signature : Signature
        Its signature.

    Returns
    -------
    frozenset of int
        Their indices in the term's context.
    """
    return free_indices(term, signature)

strengthen

strengthen(term: Term, drop: frozenset[int], signature: Signature) -> Term | None

Remove unused variables from a term's context.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

drop

Variables of its context to remove; the others are renumbered.

TYPE: frozenset of int

signature

Its signature.

TYPE: Signature

RETURNS DESCRIPTION
Term or None

The term in the smaller context, or None when it uses one of the dropped variables.

Source code in src/quivers/structural/binding.py
def strengthen(term: Term, drop: frozenset[int], signature: Signature) -> Term | None:
    """Remove unused variables from a term's context.

    Parameters
    ----------
    term : Term
        The term.
    drop : frozenset of int
        Variables of its context to remove; the others are renumbered.
    signature : Signature
        Its signature.

    Returns
    -------
    Term or None
        The term in the smaller context, or ``None`` when it uses one of
        the dropped variables.
    """
    if not drop:
        return term
    used = free_indices(term, signature)
    if used & drop:
        return None
    bound = max(max(used, default=-1), max(drop)) + 1
    targets: list[int] = []
    kept = 0
    for index in range(bound):
        if index in drop:
            targets.append(0)
        else:
            targets.append(kept)
            kept += 1
    return rename(term, targets, signature, shift=kept)

level_name

level_name(level: int) -> str

The canonical name of the variable bound at a de Bruijn level.

Naming every bound variable by its level (the number of binders outside it) makes alpha-equivalent named terms identical, which is how a deduction's binders identify alpha-equivalent logical forms.

PARAMETER DESCRIPTION
level

The level, counted from the outermost binder.

TYPE: int

RETURNS DESCRIPTION
str

#v<level>, which no source name can spell.

Source code in src/quivers/structural/binding.py
def level_name(level: int) -> str:
    """The canonical name of the variable bound at a de Bruijn level.

    Naming every bound variable by its level (the number of binders
    outside it) makes alpha-equivalent named terms identical, which is how
    a deduction's ``binders`` identify alpha-equivalent logical forms.

    Parameters
    ----------
    level : int
        The level, counted from the outermost binder.

    Returns
    -------
    str
        ``#v<level>``, which no source name can spell.
    """
    return f"#v{level}"

alpha_equal

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

Whether two terms are alpha-equivalent.

Terms are de Bruijn, so alpha-equivalence is structural equality.

PARAMETER DESCRIPTION
left

The terms.

TYPE: Term

right

The terms.

TYPE: Term

RETURNS DESCRIPTION
bool

True when they differ at most in the names of bound variables.

Source code in src/quivers/structural/binding.py
def alpha_equal(left: Term, right: Term) -> bool:
    """Whether two terms are alpha-equivalent.

    Terms are de Bruijn, so alpha-equivalence is structural equality.

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

    Returns
    -------
    bool
        ``True`` when they differ at most in the names of bound variables.
    """
    return left == right

tokens

tokens(term: Term) -> Iterator[_Token]

The prefix encoding of a term, one token per node and leaf.

The encoding records each operator with its arity, so it is injective; comparing encodings lexicographically is a total order consistent with equality.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

YIELDS DESCRIPTION
tuple

The tokens, in prefix order.

Source code in src/quivers/structural/binding.py
def tokens(term: Term) -> Iterator[_Token]:
    """The prefix encoding of a term, one token per node and leaf.

    The encoding records each operator with its arity, so it is
    injective; comparing encodings lexicographically is a total order
    consistent with equality.

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

    Yields
    ------
    tuple
        The tokens, in prefix order.
    """
    stack: list[TermArg] = [term]
    while stack:
        node = stack.pop()
        if isinstance(node, Term):
            if node.op == BOUND_VAR:
                index = node.args[0]
                assert isinstance(index, int)
                yield (1, BOUND_VAR, index)
                continue
            yield (2, node.op, len(node.args))
            stack.extend(reversed(node.args))
        else:
            yield _leaf_token(node)

sort_key

sort_key(term: Term) -> tuple[_Token, ...]

A key that orders terms totally, consistently with equality.

Variables precede constructor applications; applications compare by operator name, then arity, then arguments from left to right.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

RETURNS DESCRIPTION
tuple

The key.

Source code in src/quivers/structural/binding.py
def sort_key(term: Term) -> tuple[_Token, ...]:
    """A key that orders terms totally, consistently with equality.

    Variables precede constructor applications; applications compare by
    operator name, then arity, then arguments from left to right.

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

    Returns
    -------
    tuple
        The key.
    """
    return tuple(tokens(term))

compare

compare(left: Term, right: Term) -> int

Compare two terms in the total order of sort_key.

PARAMETER DESCRIPTION
left

The terms.

TYPE: Term

right

The terms.

TYPE: Term

RETURNS DESCRIPTION
int

-1, 0, or 1.

Source code in src/quivers/structural/binding.py
def compare(left: Term, right: Term) -> int:
    """Compare two terms in the total order of `sort_key`.

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

    Returns
    -------
    int
        ``-1``, ``0``, or ``1``.
    """
    for one, two in zip(tokens(left), tokens(right)):
        if one != two:
            return -1 if one < two else 1
    one_key, two_key = sort_key(left), sort_key(right)
    if len(one_key) == len(two_key):
        return 0
    return -1 if len(one_key) < len(two_key) else 1

content_hash

content_hash(term: Term) -> str

A stable, alpha-invariant content hash of a term.

The hash is the SHA-256 digest of the prefix encoding, so it is the same in every process and for alpha-equivalent terms, unlike Python's salted hash.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

RETURNS DESCRIPTION
str

The hexadecimal digest.

Source code in src/quivers/structural/binding.py
def content_hash(term: Term) -> str:
    """A stable, alpha-invariant content hash of a term.

    The hash is the SHA-256 digest of the prefix encoding, so it is the
    same in every process and for alpha-equivalent terms, unlike Python's
    salted ``hash``.

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

    Returns
    -------
    str
        The hexadecimal digest.
    """
    digest = hashlib.sha256()
    for kind, name, payload in tokens(term):
        encoded_name = name.encode()
        digest.update(bytes((kind,)))
        digest.update(len(encoded_name).to_bytes(4, "big"))
        digest.update(encoded_name)
        if isinstance(payload, bytes):
            data = payload
        elif isinstance(payload, int):
            data = str(payload).encode()
        else:
            data = payload.encode()
        digest.update(len(data).to_bytes(8, "big"))
        digest.update(data)
    return digest.hexdigest()

from_named

from_named(term: NamedTerm | Name, signature: Signature, context: Sequence[str] = ()) -> Term

The de Bruijn term of a named term.

A name refers to the innermost enclosing binder of that name, then to context.

PARAMETER DESCRIPTION
term

The named term.

TYPE: NamedTerm or Name

signature

Its signature.

TYPE: Signature

context

The names of the free variables, outermost first.

TYPE: Sequence of str DEFAULT: ()

RETURNS DESCRIPTION
Term

The term.

RAISES DESCRIPTION
BindingError

If a name is unbound, an abstraction binds the wrong number of names, or a binding argument is given without an abstraction.

Source code in src/quivers/structural/binding.py
def from_named(
    term: NamedTerm | Name,
    signature: Signature,
    context: Sequence[str] = (),
) -> Term:
    """The de Bruijn term of a named term.

    A name refers to the innermost enclosing binder of that name, then to
    ``context``.

    Parameters
    ----------
    term : NamedTerm or Name
        The named term.
    signature : Signature
        Its signature.
    context : Sequence of str
        The names of the free variables, outermost first.

    Returns
    -------
    Term
        The term.

    Raises
    ------
    BindingError
        If a name is unbound, an abstraction binds the wrong number of
        names, or a binding argument is given without an abstraction.
    """
    names = tuple(context)
    if isinstance(term, Name):
        return bound_var(_index_of(term.name, names))
    constructor = signature.constructors.get(term.op)
    if constructor is None:
        raise BindingError(
            f"{term.op!r} is not a constructor of signature {signature.name!r}"
        )
    if len(term.args) != constructor.arity:
        raise BindingError(
            f"{term.op!r} takes {constructor.arity} arguments, got {len(term.args)}"
        )
    arguments: list[TermArg] = []
    for position, argument in enumerate(term.args):
        scope = constructor.bound_at(position)
        declared = signature.sorts[constructor.domain[position]]
        if isinstance(argument, Abstraction):
            if len(argument.names) != len(scope):
                raise BindingError(
                    f"{term.op!r} binds {len(scope)} variables at position "
                    f"{position}, got {len(argument.names)} names"
                )
            arguments.append(
                from_named(argument.body, signature, names + argument.names)
            )
            continue
        if scope:
            raise BindingError(
                f"{term.op!r} binds {len(scope)} variables at position {position}; "
                "write them as names before a dot"
            )
        if isinstance(argument, NamedTerm):
            arguments.append(from_named(argument, signature, names))
        elif isinstance(argument, Name):
            index = _index_of(argument.name, names)
            arguments.append(index if declared.kind == "index" else bound_var(index))
        else:
            arguments.append(argument)
    return Term(op=term.op, args=tuple(arguments))

to_named

to_named(term: Term, signature: Signature, context: Sequence[str] = (), naming: Literal['fresh', 'level'] = 'fresh') -> NamedTerm | Name

A named term for a de Bruijn term, with fresh bound names.

With naming="fresh" each binder uses its declared variable names, renamed apart from every name in scope. With naming="level" a bound variable is named by its declared name followed by its de Bruijn level inside the term, so names are distinct by construction; this is how the generated QIEC show names them. Either way no variable is captured: the result read back by from_named is the original term.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

signature

Its signature.

TYPE: Signature

context

The names of the free variables, outermost first; a free variable beyond them is named #k for its index k past the context.

TYPE: Sequence of str DEFAULT: ()

naming

"fresh" or "level".

TYPE: str DEFAULT: 'fresh'

RETURNS DESCRIPTION
NamedTerm or Name

The named term.

Source code in src/quivers/structural/binding.py
def to_named(
    term: Term,
    signature: Signature,
    context: Sequence[str] = (),
    naming: Literal["fresh", "level"] = "fresh",
) -> NamedTerm | Name:
    """A named term for a de Bruijn term, with fresh bound names.

    With ``naming="fresh"`` each binder uses its declared variable names,
    renamed apart from every name in scope. With ``naming="level"`` a bound
    variable is named by its declared name followed by its de Bruijn level
    inside the term, so names are distinct by construction; this is how
    the generated QIEC ``show`` names them. Either way no variable is
    captured: the result read back by `from_named` is the original term.

    Parameters
    ----------
    term : Term
        The term.
    signature : Signature
        Its signature.
    context : Sequence of str
        The names of the free variables, outermost first; a free variable
        beyond them is named ``#k`` for its index ``k`` past the context.
    naming : str
        ``"fresh"`` or ``"level"``.

    Returns
    -------
    NamedTerm or Name
        The named term.
    """
    names = tuple(context)
    outer = len(names)

    def name_of(index: int, scope: tuple[str, ...]) -> str:
        """The name of a variable in scope.

        Parameters
        ----------
        index : int
            Its de Bruijn index.
        scope : tuple of str
            The names in scope.

        Returns
        -------
        str
            Its name.
        """
        if index < len(scope):
            return scope[-1 - index]
        return f"#{index - len(scope)}"

    def visit(node: Term, scope: tuple[str, ...]) -> NamedTerm | Name:
        """Name one subterm.

        Parameters
        ----------
        node : Term
            The subterm.
        scope : tuple of str
            The names in scope.

        Returns
        -------
        NamedTerm or Name
            Its named form.
        """
        if node.op == BOUND_VAR:
            index = node.args[0]
            assert isinstance(index, int)
            return Name(name=name_of(index, scope))
        constructor = signature.constructor(node.op)
        arguments: list[NamedArgument] = []
        for position, argument in enumerate(node.args):
            bound = constructor.bound_at(position)
            declared = signature.sorts[constructor.domain[position]]
            if bound:
                taken = set(scope)
                fresh: list[str] = []
                for offset, variable in enumerate(bound):
                    if naming == "level":
                        chosen = f"{variable.name}{len(scope) - outer + offset}"
                    else:
                        chosen = _fresh(variable.name, taken)
                    taken.add(chosen)
                    fresh.append(chosen)
                assert isinstance(argument, Term)
                arguments.append(
                    Abstraction(
                        names=tuple(fresh),
                        body=visit(argument, scope + tuple(fresh)),
                    )
                )
            elif isinstance(argument, Term):
                arguments.append(visit(argument, scope))
            elif declared.kind == "index":
                assert isinstance(argument, int)
                arguments.append(Name(name=name_of(argument, scope)))
            else:
                arguments.append(argument)
        return NamedTerm(op=node.op, args=tuple(arguments))

    return visit(term, names)

render

render(term: NamedTerm | Name, quote: str = '') -> str

The text of a named term.

PARAMETER DESCRIPTION
term

The named term.

TYPE: NamedTerm or Name

quote

Empty to write data leaves as Python literals, or a quotation mark written around string leaves instead, with other leaves bare.

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION
str

Op(arg, ...) with x, y. body for an abstraction and names bare.

Source code in src/quivers/structural/binding.py
def render(term: NamedTerm | Name, quote: str = "") -> str:
    """The text of a named term.

    Parameters
    ----------
    term : NamedTerm or Name
        The named term.
    quote : str
        Empty to write data leaves as Python literals, or a quotation mark
        written around string leaves instead, with other leaves bare.

    Returns
    -------
    str
        ``Op(arg, ...)`` with ``x, y. body`` for an abstraction and names
        bare.
    """
    if isinstance(term, Name):
        return term.name
    if not term.args:
        return term.op
    parts: list[str] = []
    for argument in term.args:
        if isinstance(argument, Abstraction):
            parts.append(f"{', '.join(argument.names)}. {render(argument.body, quote)}")
        elif isinstance(argument, NamedTerm | Name):
            parts.append(render(argument, quote))
        elif quote and isinstance(argument, str):
            parts.append(f"{quote}{argument}{quote}")
        elif quote:
            parts.append(str(argument))
        else:
            parts.append(repr(argument))
    return f"{term.op}({', '.join(parts)})"

show

show(term: Term, signature: Signature, context: Sequence[str] = (), naming: Literal['fresh', 'level'] = 'fresh') -> str

Print a term with fresh names for its bound variables.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

signature

Its signature.

TYPE: Signature

context

Names of the free variables, outermost first.

TYPE: Sequence of str DEFAULT: ()

naming

"fresh" for minimal renaming apart, or "level" for the names and string quoting of the generated QIEC show.

TYPE: str DEFAULT: 'fresh'

RETURNS DESCRIPTION
str

The text, as render writes to_named of the term.

Source code in src/quivers/structural/binding.py
def show(
    term: Term,
    signature: Signature,
    context: Sequence[str] = (),
    naming: Literal["fresh", "level"] = "fresh",
) -> str:
    """Print a term with fresh names for its bound variables.

    Parameters
    ----------
    term : Term
        The term.
    signature : Signature
        Its signature.
    context : Sequence of str
        Names of the free variables, outermost first.
    naming : str
        ``"fresh"`` for minimal renaming apart, or ``"level"`` for the
        names and string quoting of the generated QIEC ``show``.

    Returns
    -------
    str
        The text, as `render` writes `to_named` of the term.
    """
    named = to_named(term, signature, context, naming)
    return render(named, '"' if naming == "level" else "")

fold

fold(term: Term, signature: Signature, algebra: SubstitutionAlgebra[V], environment: Sequence[V] = ()) -> V

The unique substitution-respecting map from terms into an algebra.

Unbound object arguments are folded before their parent with an explicit stack, so long first-order spines do not exhaust the interpreter's recursion limit; a binding argument is folded when the algebra applies its Scoped value.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

signature

Its signature.

TYPE: Signature

algebra

The algebra.

TYPE: SubstitutionAlgebra

environment

The value of each free variable, outermost first.

TYPE: Sequence DEFAULT: ()

RETURNS DESCRIPTION
V

The fold.

RAISES DESCRIPTION
BindingError

If a variable is outside the environment.

Source code in src/quivers/structural/binding.py
def fold[V](
    term: Term,
    signature: Signature,
    algebra: SubstitutionAlgebra[V],
    environment: Sequence[V] = (),
) -> V:
    """The unique substitution-respecting map from terms into an algebra.

    Unbound object arguments are folded before their parent with an
    explicit stack, so long first-order spines do not exhaust the
    interpreter's recursion limit; a binding argument is folded when the
    algebra applies its `Scoped` value.

    Parameters
    ----------
    term : Term
        The term.
    signature : Signature
        Its signature.
    algebra : SubstitutionAlgebra
        The algebra.
    environment : Sequence
        The value of each free variable, outermost first.

    Returns
    -------
    V
        The fold.

    Raises
    ------
    BindingError
        If a variable is outside the environment.
    """

    def run(node: Term, scope: tuple[V, ...]) -> V:
        """Fold one term in an environment.

        Parameters
        ----------
        node : Term
            The term.
        scope : tuple
            The environment.

        Returns
        -------
        V
            Its fold.
        """
        frames: list[tuple[Term, list[FoldArgument[V]]]] = []
        result: V | None = None
        current: Term | None = node
        while True:
            if current is not None:
                if current.op == BOUND_VAR:
                    index = current.args[0]
                    assert isinstance(index, int)
                    value = _lookup(scope, index)
                    current = None
                    if not frames:
                        return value
                    frames[-1][1].append(value)
                else:
                    frames.append((current, []))
                    current = None
                continue
            parent, done = frames[-1]
            constructor = signature.constructor(parent.op)
            position = len(done)
            if position == len(parent.args):
                frames.pop()
                result = algebra.operation(parent.op, tuple(done))
                if not frames:
                    return result
                frames[-1][1].append(result)
                continue
            argument = parent.args[position]
            bound = constructor.bound_at(position)
            declared = signature.sorts[constructor.domain[position]]
            if bound:
                assert isinstance(argument, Term)
                done.append(_scoped(argument, scope, run, len(bound)))
            elif isinstance(argument, Term):
                current = argument
            elif declared.kind == "index":
                assert isinstance(argument, int)
                done.append(_lookup(scope, argument))
            else:
                done.append(argument)

    return run(term, tuple(environment))

rebuild

rebuild(term: Term, signature: Signature, depth: int = 0) -> Term

Fold a term into the initial algebra, which gives it back.

PARAMETER DESCRIPTION
term

A term in a context of depth variables.

TYPE: Term

signature

Its signature.

TYPE: Signature

depth

The size of its context.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
Term

The same term.

Source code in src/quivers/structural/binding.py
def rebuild(term: Term, signature: Signature, depth: int = 0) -> Term:
    """Fold a term into the initial algebra, which gives it back.

    Parameters
    ----------
    term : Term
        A term in a context of ``depth`` variables.
    signature : Signature
        Its signature.
    depth : int
        The size of its context.

    Returns
    -------
    Term
        The same term.
    """
    environment = tuple(_level(level) for level in range(depth))
    return fold(term, signature, TermAlgebra(signature), environment).at(depth)

environment_of

environment_of(substitution: Mapping[int, Term] | Sequence[Term]) -> tuple[Term, ...]

Replacements of a finite context as an environment.

PARAMETER DESCRIPTION
substitution

The replacement of each variable, by index.

TYPE: Mapping or Sequence

RETURNS DESCRIPTION
tuple of Term

The replacements, outermost first.

Source code in src/quivers/structural/binding.py
def environment_of(
    substitution: Mapping[int, Term] | Sequence[Term],
) -> tuple[Term, ...]:
    """Replacements of a finite context as an environment.

    Parameters
    ----------
    substitution : Mapping or Sequence
        The replacement of each variable, by index.

    Returns
    -------
    tuple of Term
        The replacements, outermost first.
    """
    if isinstance(substitution, Mapping):
        size = max(substitution, default=-1) + 1
        return tuple(substitution[size - 1 - i] for i in range(size))
    return tuple(reversed(tuple(substitution)))