Skip to content

Second-order patterns

Patterns are terms of a signature with metavariables, the sides of equations and of judgment rules. This module sorts and checks them, matches them against terms, decides membership in Miller's pattern fragment, and solves higher-order pattern unification problems, and it reads written patterns against a signature (Equations and normalization §1).

patterns

Second-order patterns: matching, instantiation, and Miller unification.

A pattern is a term of a binding signature that may contain metavariables of context arity, written M[x, y]: an unknown term in the scope of k extra variables, instantiated by second-order substitution [@fiore2010second]. The left side of an equation or rule is in Miller's pattern fragment when every metavariable occurrence is applied to distinct variables bound inside the pattern [@miller1991logic]; then matching a term against it has at most one solution and unification of two patterns has a most general unifier when one exists.

Patterns use the de Bruijn discipline of quivers.structural.signature: a PatternVariable refers to a binder of the pattern by index, counting from the innermost. A metavariable's solution is a Solution, a term in the context of the matched redex extended by the metavariable's arity, so M[N] instantiates it with quivers.structural.binding.instantiate.

A metavariable may also stand at a data position, as the n of Const(n, A): it is a data metavariable, of the data sort of that position, and takes no arguments. Matching binds it to the data value there, so its solution's body is that value; it unifies with a data value by equality, type included; and instantiation puts the value back. A metavariable is a data metavariable everywhere or nowhere: one used at a data position and at a term position is refused.

Unification is computed in a locally nameless form: while it descends under a binder it opens the binder's variables as FreeVariable names, so a variable never changes its name as it moves between depths.

Pattern

A second-order pattern.

PatternArgument

PatternArgument = Pattern | DataLeaf

An argument of a pattern application.

PatternError

Bases: ValueError

A pattern is ill-formed, ill-sorted, or outside the pattern fragment.

PatternVariable didactic-model

PatternVariable(*, index: int)

Bases: Model

A variable bound inside a pattern, by de Bruijn index.

PARAMETER DESCRIPTION
index

The index, counting from the innermost enclosing binder.

TYPE: int

FreeVariable didactic-model

FreeVariable(*, name: int)

Bases: Model

A variable opened by unification under a binder.

PARAMETER DESCRIPTION
name

Its identity, unique in one unification problem.

TYPE: int

Metavariable didactic-model

Metavariable(*, name: str, args: tuple = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

A metavariable applied to arguments: M[a_1, ..., a_k].

PARAMETER DESCRIPTION
name

The metavariable.

TYPE: str

args

The terms its bound variables are replaced by.

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

PatternApplication didactic-model

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

Bases: ValueModel

A constructor applied to patterns and data leaves.

PARAMETER DESCRIPTION
op

The constructor.

TYPE: str

args

Its arguments; an argument that binds variables is a pattern in the extended scope.

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

MetaSort didactic-model

MetaSort(*, arguments: tuple[str, ...] = (), result: str)

Bases: Model

The type of a metavariable: the sorts of its arguments and of its body.

PARAMETER DESCRIPTION
arguments

The sort of each bound variable, outermost first.

TYPE: tuple of str DEFAULT: ()

result

The sort of the body.

TYPE: str

Solution didactic-model

Solution(*, arity: int, body: Term | DataLeaf = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

The value of a metavariable: a body in the scope of arity variables.

PARAMETER DESCRIPTION
arity

The number of variables the body binds; the last is index 0.

TYPE: int

body

The body, in the matched redex's context extended by arity; for a data metavariable, the data value, with arity zero.

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

same

same(other: Solution) -> bool

Whether two solutions are equal, a data value's type included.

PARAMETER DESCRIPTION
other

The other solution.

TYPE: Solution

RETURNS DESCRIPTION
bool

True when both bind the same number of variables and have equal bodies; data bodies must also have the same type, so 1 and True differ.

Source code in src/quivers/structural/patterns.py
def same(self, other: Solution) -> bool:
    """Whether two solutions are equal, a data value's type included.

    Parameters
    ----------
    other : Solution
        The other solution.

    Returns
    -------
    bool
        ``True`` when both bind the same number of variables and have
        equal bodies; data bodies must also have the same type, so
        ``1`` and ``True`` differ.
    """
    if self.arity != other.arity:
        return False
    if isinstance(self.body, Term) or isinstance(other.body, Term):
        return self.body == other.body
    return _equal_leaf(self.body, other.body)

UnificationProblem

UnificationProblem(signature: Signature, sorts: Mapping[str, MetaSort])

The state of one higher-order pattern unification.

Metavariables are solved by bodies that bind their arguments and mention no other free variable: a metavariable that may depend on a variable takes it as an argument (it is raised over it). Fresh metavariables are introduced by pruning. A data metavariable is solved by a data value, and unifies with one only when they are equal.

PARAMETER DESCRIPTION
signature

The signature.

TYPE: Signature

sorts

The type of every metavariable.

TYPE: Mapping of str to MetaSort

Source code in src/quivers/structural/patterns.py
def __init__(self, signature: Signature, sorts: Mapping[str, MetaSort]) -> None:
    self.signature = signature
    self.sorts: dict[str, MetaSort] = dict(sorts)
    self.solved: dict[str, PatternArgument] = {}
    self.free_sorts: dict[int, str] = {}
    self._fresh_free = itertools.count(1_000_000)
    self._fresh_meta = itertools.count()

fresh_free

fresh_free(sort: str) -> FreeVariable

A new free variable.

PARAMETER DESCRIPTION
sort

Its sort.

TYPE: str

RETURNS DESCRIPTION
FreeVariable

The variable.

Source code in src/quivers/structural/patterns.py
def fresh_free(self, sort: str) -> FreeVariable:
    """A new free variable.

    Parameters
    ----------
    sort : str
        Its sort.

    Returns
    -------
    FreeVariable
        The variable.
    """
    name = next(self._fresh_free)
    self.free_sorts[name] = sort
    return FreeVariable(name=name)

open

open(body: PatternArgument, values: Sequence[Pattern]) -> PatternArgument

Replace the innermost len(values) bound variables of a body.

values[-1] replaces index 0. The values must not contain pattern variables, so nothing is shifted.

PARAMETER DESCRIPTION
body

The body.

TYPE: PatternArgument

values

The replacements, outermost first.

TYPE: Sequence of Pattern

RETURNS DESCRIPTION
PatternArgument

The opened body.

Source code in src/quivers/structural/patterns.py
def open(self, body: PatternArgument, values: Sequence[Pattern]) -> PatternArgument:
    """Replace the innermost ``len(values)`` bound variables of a body.

    ``values[-1]`` replaces index 0. The values must not contain
    pattern variables, so nothing is shifted.

    Parameters
    ----------
    body : PatternArgument
        The body.
    values : Sequence of Pattern
        The replacements, outermost first.

    Returns
    -------
    PatternArgument
        The opened body.
    """
    return _replace_indices(body, tuple(values), 0, self.signature)

close

close(body: PatternArgument, names: Sequence[int]) -> PatternArgument

Bind free variables: the inverse of open.

PARAMETER DESCRIPTION
body

The body.

TYPE: PatternArgument

names

The free variables to bind, outermost first.

TYPE: Sequence of int

RETURNS DESCRIPTION
PatternArgument

The body with names[-1] as index 0.

Source code in src/quivers/structural/patterns.py
def close(self, body: PatternArgument, names: Sequence[int]) -> PatternArgument:
    """Bind free variables: the inverse of `open`.

    Parameters
    ----------
    body : PatternArgument
        The body.
    names : Sequence of int
        The free variables to bind, outermost first.

    Returns
    -------
    PatternArgument
        The body with ``names[-1]`` as index 0.
    """
    return _bind_frees(body, tuple(names), 0, self.signature)

resolve

resolve(pattern: PatternArgument) -> PatternArgument

Instantiate a solved metavariable at the head, repeatedly.

PARAMETER DESCRIPTION
pattern

The pattern.

TYPE: PatternArgument

RETURNS DESCRIPTION
PatternArgument

A pattern whose head is not a solved metavariable.

Source code in src/quivers/structural/patterns.py
def resolve(self, pattern: PatternArgument) -> PatternArgument:
    """Instantiate a solved metavariable at the head, repeatedly.

    Parameters
    ----------
    pattern : PatternArgument
        The pattern.

    Returns
    -------
    PatternArgument
        A pattern whose head is not a solved metavariable.
    """
    while isinstance(pattern, Metavariable) and pattern.name in self.solved:
        body = self.solved[pattern.name]
        pattern = _replace_indices(body, pattern.args, 0, self.signature)
    return pattern

full

full(pattern: PatternArgument) -> PatternArgument

Instantiate every solved metavariable of a pattern.

PARAMETER DESCRIPTION
pattern

The pattern.

TYPE: PatternArgument

RETURNS DESCRIPTION
PatternArgument

The pattern with only unsolved metavariables.

Source code in src/quivers/structural/patterns.py
def full(self, pattern: PatternArgument) -> PatternArgument:
    """Instantiate every solved metavariable of a pattern.

    Parameters
    ----------
    pattern : PatternArgument
        The pattern.

    Returns
    -------
    PatternArgument
        The pattern with only unsolved metavariables.
    """
    pattern = self.resolve(pattern)
    if isinstance(pattern, Metavariable):
        return Metavariable(
            name=pattern.name, args=tuple(self.full(a) for a in pattern.args)
        )
    if isinstance(pattern, PatternApplication):
        return PatternApplication(
            op=pattern.op, args=tuple(self.full(a) for a in pattern.args)
        )
    return pattern

fresh_meta

fresh_meta(arguments: tuple[str, ...], result: str) -> str

A new metavariable.

PARAMETER DESCRIPTION
arguments

The sorts of its arguments.

TYPE: tuple of str

result

The sort of its body.

TYPE: str

RETURNS DESCRIPTION
str

Its name.

Source code in src/quivers/structural/patterns.py
def fresh_meta(self, arguments: tuple[str, ...], result: str) -> str:
    """A new metavariable.

    Parameters
    ----------
    arguments : tuple of str
        The sorts of its arguments.
    result : str
        The sort of its body.

    Returns
    -------
    str
        Its name.
    """
    name = f"?{next(self._fresh_meta)}"
    self.sorts[name] = MetaSort(arguments=arguments, result=result)
    return name

unify

unify(left: PatternArgument, right: PatternArgument) -> bool

Unify two patterns, extending the solution.

PARAMETER DESCRIPTION
left

The patterns, with every enclosing binder opened.

TYPE: PatternArgument

right

The patterns, with every enclosing binder opened.

TYPE: PatternArgument

RETURNS DESCRIPTION
bool

Whether a unifier exists.

Source code in src/quivers/structural/patterns.py
def unify(self, left: PatternArgument, right: PatternArgument) -> bool:
    """Unify two patterns, extending the solution.

    Parameters
    ----------
    left, right : PatternArgument
        The patterns, with every enclosing binder opened.

    Returns
    -------
    bool
        Whether a unifier exists.
    """
    left = self.resolve(left)
    right = self.resolve(right)
    if isinstance(left, Metavariable) and isinstance(right, Metavariable):
        if left.name == right.name:
            return self._flex_same(left, right)
        return self._flex(left, right)
    if isinstance(left, Metavariable):
        return self._flex(left, right)
    if isinstance(right, Metavariable):
        return self._flex(right, left)
    if isinstance(left, FreeVariable) or isinstance(right, FreeVariable):
        return left == right
    if isinstance(left, PatternVariable) or isinstance(right, PatternVariable):
        return left == right
    if isinstance(left, PatternApplication) and isinstance(
        right, PatternApplication
    ):
        if left.op != right.op or len(left.args) != len(right.args):
            return False
        constructor = self.signature.constructor(left.op)
        for position, (one, two) in enumerate(
            zip(left.args, right.args, strict=True)
        ):
            bound = constructor.bound_at(position)
            nodes = (
                PatternApplication | Metavariable | PatternVariable | FreeVariable
            )
            if not isinstance(one, nodes) and not isinstance(two, nodes):
                if not _equal_leaf(one, two):
                    return False
                continue
            if bound:
                frees = [self.fresh_free(v.sort) for v in bound]
                one = self.open(one, frees)
                two = self.open(two, frees)
            if not self.unify(one, two):
                return False
        return True
    return _equal_leaf(left, right)

PatternSyntax didactic-model

PatternSyntax(*, kind: Literal['name', 'apply', 'instance', 'abstract', 'extend', 'leaf'], name: str = '', names: tuple[str, ...] = (), args: tuple[PatternSyntax, ...] = (), leaf: str | int | None = None, line: int = 0, col: int = 0)

Bases: Model

A pattern as written, before names are resolved.

kind is "name" for a bare name, "apply" for Op(...), "instance" for M[...], "abstract" for x y. body, "extend" for a context extension (ctx, x : A) (its name is the context, names the entries and args their values), and "leaf" for a literal.

PARAMETER DESCRIPTION
kind

The form.

TYPE: str

name

The name or head, empty for a leaf.

TYPE: str DEFAULT: ''

names

The names an abstraction binds.

TYPE: tuple of str DEFAULT: ()

args

The arguments, or the single body of an abstraction.

TYPE: tuple of PatternSyntax DEFAULT: ()

leaf

The literal of a leaf.

TYPE: str or int or None DEFAULT: None

line

The source position, zero when unknown.

TYPE: int DEFAULT: 0

col

The source position, zero when unknown.

TYPE: int DEFAULT: 0

from_term

from_term(term: Term) -> Pattern

Read a term as a pattern without metavariables.

PARAMETER DESCRIPTION
term

The term.

TYPE: Term

RETURNS DESCRIPTION
Pattern

The same tree.

Source code in src/quivers/structural/patterns.py
def from_term(term: Term) -> Pattern:
    """Read a term as a pattern without metavariables.

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

    Returns
    -------
    Pattern
        The same tree.
    """
    if term.op == BOUND_VAR:
        index = term.args[0]
        assert isinstance(index, int)
        return PatternVariable(index=index)
    return PatternApplication(
        op=term.op,
        args=tuple(from_term(a) if isinstance(a, Term) else a for a in term.args),
    )

metavariables

metavariables(pattern: PatternArgument) -> Iterator[Metavariable]

Every metavariable occurrence of a pattern, in prefix order.

PARAMETER DESCRIPTION
pattern

The pattern.

TYPE: PatternArgument

YIELDS DESCRIPTION
Metavariable

Each occurrence.

Source code in src/quivers/structural/patterns.py
def metavariables(pattern: PatternArgument) -> Iterator[Metavariable]:
    """Every metavariable occurrence of a pattern, in prefix order.

    Parameters
    ----------
    pattern : PatternArgument
        The pattern.

    Yields
    ------
    Metavariable
        Each occurrence.
    """
    stack: list[PatternArgument] = [pattern]
    while stack:
        node = stack.pop()
        if isinstance(node, Metavariable):
            yield node
            stack.extend(reversed(node.args))
        elif isinstance(node, PatternApplication):
            stack.extend(reversed(node.args))

render_pattern

render_pattern(pattern: PatternArgument, signature: Signature) -> str

The text of a pattern, with #i for a bound variable by index.

PARAMETER DESCRIPTION
pattern

The pattern.

TYPE: PatternArgument

signature

Its signature.

TYPE: Signature

RETURNS DESCRIPTION
str

The text.

Source code in src/quivers/structural/patterns.py
def render_pattern(pattern: PatternArgument, signature: Signature) -> str:
    """The text of a pattern, with ``#i`` for a bound variable by index.

    Parameters
    ----------
    pattern : PatternArgument
        The pattern.
    signature : Signature
        Its signature.

    Returns
    -------
    str
        The text.
    """
    if isinstance(pattern, PatternVariable):
        return f"#{pattern.index}"
    if isinstance(pattern, FreeVariable):
        return f"_{pattern.name}"
    if isinstance(pattern, Metavariable):
        inner = ", ".join(render_pattern(a, signature) for a in pattern.args)
        return f"{pattern.name}[{inner}]" if pattern.args else pattern.name
    if isinstance(pattern, PatternApplication):
        if not pattern.args:
            return pattern.op
        parts: list[str] = []
        constructor = signature.constructors.get(pattern.op)
        for position, argument in enumerate(pattern.args):
            bound = constructor.bound_at(position) if constructor is not None else ()
            text = render_pattern(argument, signature)
            if bound:
                text = f"{' '.join(v.name for v in bound)}. {text}"
            parts.append(text)
        return f"{pattern.op}({', '.join(parts)})"
    return repr(pattern)

infer_metavariable_sorts

infer_metavariable_sorts(pattern: Pattern, signature: Signature, sort: str | None = None) -> dict[str, MetaSort]

Infer the type of every metavariable of a pattern from its positions.

PARAMETER DESCRIPTION
pattern

A closed pattern: its variables are bound inside it.

TYPE: Pattern

signature

The signature.

TYPE: Signature

sort

The sort the pattern must have, or None to read it from the root constructor.

TYPE: str or None DEFAULT: None

RETURNS DESCRIPTION
dict of str to MetaSort

The type of each metavariable.

RAISES DESCRIPTION
PatternError

If a constructor is undeclared or misapplied, a variable is out of scope or of the wrong sort, or a metavariable is used at two types.

Source code in src/quivers/structural/patterns.py
def infer_metavariable_sorts(
    pattern: Pattern, signature: Signature, sort: str | None = None
) -> dict[str, MetaSort]:
    """Infer the type of every metavariable of a pattern from its positions.

    Parameters
    ----------
    pattern : Pattern
        A closed pattern: its variables are bound inside it.
    signature : Signature
        The signature.
    sort : str or None
        The sort the pattern must have, or ``None`` to read it from the
        root constructor.

    Returns
    -------
    dict of str to MetaSort
        The type of each metavariable.

    Raises
    ------
    PatternError
        If a constructor is undeclared or misapplied, a variable is out of
        scope or of the wrong sort, or a metavariable is used at two types.
    """
    found: dict[str, MetaSort] = {}
    check_pattern_sorts(pattern, signature, (), sort, found)
    return found

check_pattern_sorts

check_pattern_sorts(pattern: PatternArgument, signature: Signature, context: tuple[str, ...], sort: str | None, metas: dict[str, MetaSort]) -> str

Check a pattern's sorts, recording or checking metavariable types.

PARAMETER DESCRIPTION
pattern

The pattern.

TYPE: PatternArgument

signature

The signature.

TYPE: Signature

context

The sorts of its bound variables in scope, outermost first.

TYPE: tuple of str

sort

The sort it must have.

TYPE: str or None

metas

Known metavariable types; new ones are added.

TYPE: dict of str to MetaSort

RETURNS DESCRIPTION
str

The pattern's sort.

RAISES DESCRIPTION
PatternError

If the pattern is ill-sorted.

Source code in src/quivers/structural/patterns.py
def check_pattern_sorts(
    pattern: PatternArgument,
    signature: Signature,
    context: tuple[str, ...],
    sort: str | None,
    metas: dict[str, MetaSort],
) -> str:
    """Check a pattern's sorts, recording or checking metavariable types.

    Parameters
    ----------
    pattern : PatternArgument
        The pattern.
    signature : Signature
        The signature.
    context : tuple of str
        The sorts of its bound variables in scope, outermost first.
    sort : str or None
        The sort it must have.
    metas : dict of str to MetaSort
        Known metavariable types; new ones are added.

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

    Raises
    ------
    PatternError
        If the pattern is ill-sorted.
    """
    if isinstance(pattern, PatternVariable):
        if not 0 <= pattern.index < len(context):
            raise PatternError(f"variable #{pattern.index} is out of scope")
        found = context[-1 - pattern.index]
    elif isinstance(pattern, Metavariable):
        argument_sorts = tuple(
            check_pattern_sorts(a, signature, context, None, metas)
            for a in pattern.args
        )
        for argument, argument_sort in zip(pattern.args, argument_sorts, strict=True):
            if signature.sorts[argument_sort].kind == "data":
                raise PatternError(
                    f"metavariable {pattern.name!r} is applied to "
                    f"{render_pattern(argument, signature)}, a data value of sort "
                    f"{argument_sort!r}; a metavariable's arguments are terms"
                )
        known = metas.get(pattern.name)
        if known is None:
            if sort is None:
                raise PatternError(
                    f"the sort of metavariable {pattern.name!r} is not determined "
                    "by its position"
                )
            if signature.sorts[sort].kind == "data" and argument_sorts:
                raise PatternError(
                    f"metavariable {pattern.name!r} stands for a data value of sort "
                    f"{sort!r} and takes no arguments"
                )
            metas[pattern.name] = MetaSort(arguments=argument_sorts, result=sort)
            found = sort
        else:
            if sort is not None:
                _check_kind(pattern.name, known.result, sort, signature)
            if known.arguments != argument_sorts:
                raise PatternError(
                    f"metavariable {pattern.name!r} is applied to "
                    f"{len(argument_sorts)} arguments of sorts "
                    f"{list(argument_sorts)} here and "
                    f"{list(known.arguments)} elsewhere"
                )
            found = known.result
    elif isinstance(pattern, PatternApplication):
        constructor = signature.constructors.get(pattern.op)
        if constructor is None:
            raise PatternError(
                f"{pattern.op!r} is not a constructor of signature {signature.name!r}"
            )
        if len(pattern.args) != constructor.arity:
            raise PatternError(
                f"{pattern.op!r} takes {constructor.arity} arguments, "
                f"got {len(pattern.args)}"
            )
        for position, (argument_sort, argument) in enumerate(
            zip(constructor.domain, pattern.args, strict=True)
        ):
            declared = signature.sorts[argument_sort]
            inner = context + tuple(v.sort for v in constructor.bound_at(position))
            if declared.kind == "data":
                if isinstance(argument, Metavariable):
                    check_pattern_sorts(
                        argument, signature, inner, argument_sort, metas
                    )
                    continue
                if isinstance(argument, PatternApplication | PatternVariable):
                    raise PatternError(
                        f"{pattern.op!r} takes a data value or a data metavariable "
                        f"at position {position}, got "
                        f"{render_pattern(argument, signature)}"
                    )
                continue
            if declared.kind == "index":
                if not isinstance(argument, PatternVariable):
                    raise PatternError(
                        f"{pattern.op!r} takes a variable at position {position}"
                    )
                check_pattern_sorts(argument, signature, inner, argument_sort, metas)
                continue
            if not isinstance(
                argument, PatternApplication | Metavariable | PatternVariable
            ):
                raise PatternError(
                    f"{pattern.op!r} takes a term of sort {argument_sort!r} at "
                    f"position {position}"
                )
            check_pattern_sorts(argument, signature, inner, argument_sort, metas)
        found = constructor.codomain
    else:
        raise PatternError("a free variable cannot appear in a declared pattern")
    if sort is not None and found != sort:
        raise PatternError(
            f"{render_pattern(pattern, signature)} has sort {found!r} where "
            f"{sort!r} is required"
        )
    return found

check_miller_pattern

check_miller_pattern(pattern: Pattern, signature: Signature) -> None

Require a left side in Miller's pattern fragment.

The root is a constructor application, and every metavariable is applied to distinct variables bound inside the pattern.

PARAMETER DESCRIPTION
pattern

The left side.

TYPE: Pattern

signature

The signature.

TYPE: Signature

RAISES DESCRIPTION
PatternError

If the pattern is outside the fragment, naming the occurrence.

Source code in src/quivers/structural/patterns.py
def check_miller_pattern(pattern: Pattern, signature: Signature) -> None:
    """Require a left side in Miller's pattern fragment.

    The root is a constructor application, and every metavariable is
    applied to distinct variables bound inside the pattern.

    Parameters
    ----------
    pattern : Pattern
        The left side.
    signature : Signature
        The signature.

    Raises
    ------
    PatternError
        If the pattern is outside the fragment, naming the occurrence.
    """
    if not isinstance(pattern, PatternApplication):
        raise PatternError(
            "a left side must be a constructor application, got "
            f"{render_pattern(pattern, signature)}"
        )
    for occurrence in metavariables(pattern):
        indices: list[int] = []
        for argument in occurrence.args:
            if not isinstance(argument, PatternVariable):
                raise PatternError(
                    f"{render_pattern(occurrence, signature)} is outside the pattern "
                    "fragment: a metavariable on a left side is applied to "
                    "variables only"
                )
            indices.append(argument.index)
        if len(set(indices)) != len(indices):
            raise PatternError(
                f"{render_pattern(occurrence, signature)} is outside the pattern "
                "fragment: its variables must be distinct"
            )

match

match(pattern: Pattern, term: Term, signature: Signature, solutions: Mapping[str, Solution] | None = None) -> dict[str, Solution] | None

Match a term against a left side in the pattern fragment.

Matching a metavariable M[x_1, ..., x_k] succeeds when the term uses no variable bound inside the pattern other than the x_i; its solution abstracts them. A data metavariable binds the data value at its position. A metavariable that occurs twice must match alpha-equal terms, or equal data values of the same type. The term's own free variables pass through.

PARAMETER DESCRIPTION
pattern

The left side.

TYPE: Pattern

term

The term.

TYPE: Term

signature

The signature.

TYPE: Signature

solutions

Metavariables already solved.

TYPE: Mapping or None DEFAULT: None

RETURNS DESCRIPTION
dict of str to Solution or None

The unique solution, or None when the term does not match.

Source code in src/quivers/structural/patterns.py
def match(
    pattern: Pattern,
    term: Term,
    signature: Signature,
    solutions: Mapping[str, Solution] | None = None,
) -> dict[str, Solution] | None:
    """Match a term against a left side in the pattern fragment.

    Matching a metavariable ``M[x_1, ..., x_k]`` succeeds when the term uses
    no variable bound inside the pattern other than the ``x_i``; its
    solution abstracts them. A data metavariable binds the data value at
    its position. A metavariable that occurs twice must match alpha-equal
    terms, or equal data values of the same type. The term's own free
    variables pass through.

    Parameters
    ----------
    pattern : Pattern
        The left side.
    term : Term
        The term.
    signature : Signature
        The signature.
    solutions : Mapping or None
        Metavariables already solved.

    Returns
    -------
    dict of str to Solution or None
        The unique solution, or ``None`` when the term does not match.
    """
    found: dict[str, Solution] = dict(solutions or {})
    stack: list[tuple[PatternArgument, TermArg, int]] = [(pattern, term, 0)]
    while stack:
        current, value, depth = stack.pop()
        if isinstance(current, PatternVariable):
            if isinstance(value, Term):
                if value.op != BOUND_VAR or value.args[0] != current.index:
                    return None
            elif value != current.index or isinstance(value, bool):
                return None
            continue
        if isinstance(current, Metavariable):
            if isinstance(value, Term):
                solution = _abstract(value, current, depth, signature)
                if solution is None:
                    return None
            elif current.args:
                return None
            else:
                solution = Solution(arity=0, body=value)
            known = found.get(current.name)
            if known is None:
                found[current.name] = solution
            elif not known.same(solution):
                return None
            continue
        if isinstance(current, PatternApplication):
            if not isinstance(value, Term) or value.op != current.op:
                return None
            if len(value.args) != len(current.args):
                return None
            constructor = signature.constructor(current.op)
            for position, (sub, arg) in enumerate(
                zip(current.args, value.args, strict=True)
            ):
                inner = depth + len(constructor.bound_at(position))
                if isinstance(sub, PatternApplication | Metavariable | PatternVariable):
                    stack.append((sub, arg, inner))
                elif not _equal_leaf(arg, sub):
                    return None
            continue
        return None
    return found

instantiate_pattern

instantiate_pattern(pattern: PatternArgument, solutions: Mapping[str, Solution], signature: Signature, depth: int = 0) -> TermArg

The term a pattern denotes under metavariable solutions.

PARAMETER DESCRIPTION
pattern

The pattern, typically a right side.

TYPE: PatternArgument

solutions

A solution for every metavariable it uses.

TYPE: Mapping of str to Solution

signature

The signature.

TYPE: Signature

depth

The number of pattern binders around it.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
TermArg

The term, in the redex's context extended by depth.

RAISES DESCRIPTION
PatternError

If a metavariable has no solution or the wrong number of arguments.

Source code in src/quivers/structural/patterns.py
def instantiate_pattern(
    pattern: PatternArgument,
    solutions: Mapping[str, Solution],
    signature: Signature,
    depth: int = 0,
) -> TermArg:
    """The term a pattern denotes under metavariable solutions.

    Parameters
    ----------
    pattern : PatternArgument
        The pattern, typically a right side.
    solutions : Mapping of str to Solution
        A solution for every metavariable it uses.
    signature : Signature
        The signature.
    depth : int
        The number of pattern binders around it.

    Returns
    -------
    TermArg
        The term, in the redex's context extended by ``depth``.

    Raises
    ------
    PatternError
        If a metavariable has no solution or the wrong number of arguments.
    """
    if isinstance(pattern, PatternVariable):
        return bound_var(pattern.index)
    if isinstance(pattern, Metavariable):
        solution = solutions.get(pattern.name)
        if solution is None:
            raise PatternError(f"metavariable {pattern.name!r} has no solution")
        if solution.arity != len(pattern.args):
            raise PatternError(
                f"metavariable {pattern.name!r} binds {solution.arity} variables, "
                f"applied to {len(pattern.args)}"
            )
        if not isinstance(solution.body, Term):
            return solution.body
        values = []
        for argument in pattern.args:
            value = instantiate_pattern(argument, solutions, signature, depth)
            assert isinstance(value, Term)
            values.append(value)
        moved = substitute(
            solution.body,
            Substitution(
                replacements=tuple(bound_var(i) for i in range(solution.arity)),
                shift=solution.arity + depth,
            ),
            signature,
        )
        return instantiate(moved, values, signature)
    if isinstance(pattern, PatternApplication):
        constructor = signature.constructor(pattern.op)
        arguments: list[TermArg] = []
        for position, argument in enumerate(pattern.args):
            inner = depth + len(constructor.bound_at(position))
            arguments.append(
                instantiate_pattern(argument, solutions, signature, inner)
                if isinstance(
                    argument, PatternApplication | Metavariable | PatternVariable
                )
                else argument
            )
        return Term(op=pattern.op, args=tuple(arguments))
    if isinstance(pattern, FreeVariable):
        raise PatternError("a free variable has no term without a context")
    return pattern

resolve

resolve(syntax: PatternSyntax, signature: Signature, scope: tuple[str, ...] = ()) -> PatternArgument

Resolve the names of a written pattern against a signature.

A bare name is a bound variable when a binder in scope binds it, a nullary constructor when the signature declares one, and a metavariable of arity zero otherwise. M[...] is a metavariable instantiation and Op(...) a constructor application, whose abstractions must bind as many names as the argument's arity.

PARAMETER DESCRIPTION
syntax

The written pattern.

TYPE: PatternSyntax

signature

The signature.

TYPE: Signature

scope

The names bound around it, outermost first.

TYPE: tuple of str DEFAULT: ()

RETURNS DESCRIPTION
PatternArgument

The pattern.

RAISES DESCRIPTION
PatternError

If a constructor is applied to the wrong number of arguments, an abstraction has the wrong number of names, a binding argument has none, or a name in a metavariable's head is bound.

Source code in src/quivers/structural/patterns.py
def resolve(
    syntax: PatternSyntax,
    signature: Signature,
    scope: tuple[str, ...] = (),
) -> PatternArgument:
    """Resolve the names of a written pattern against a signature.

    A bare name is a bound variable when a binder in scope binds it, a
    nullary constructor when the signature declares one, and a
    metavariable of arity zero otherwise. ``M[...]`` is a metavariable
    instantiation and ``Op(...)`` a constructor application, whose
    abstractions must bind as many names as the argument's arity.

    Parameters
    ----------
    syntax : PatternSyntax
        The written pattern.
    signature : Signature
        The signature.
    scope : tuple of str
        The names bound around it, outermost first.

    Returns
    -------
    PatternArgument
        The pattern.

    Raises
    ------
    PatternError
        If a constructor is applied to the wrong number of arguments, an
        abstraction has the wrong number of names, a binding argument has
        none, or a name in a metavariable's head is bound.
    """
    if syntax.kind == "leaf":
        assert syntax.leaf is not None
        return syntax.leaf
    if syntax.kind == "name":
        if syntax.name in scope:
            return PatternVariable(index=scope[::-1].index(syntax.name))
        constructor = signature.constructors.get(syntax.name)
        if constructor is not None:
            if constructor.arity:
                raise PatternError(
                    f"{syntax.name!r} takes {constructor.arity} arguments"
                )
            return PatternApplication(op=syntax.name)
        return Metavariable(name=syntax.name)
    if syntax.kind == "instance":
        if syntax.name in scope or syntax.name in signature.constructors:
            raise PatternError(
                f"{syntax.name}[...] instantiates a metavariable, but "
                f"{syntax.name!r} is a bound variable or a constructor"
            )
        return Metavariable(
            name=syntax.name,
            args=tuple(resolve(a, signature, scope) for a in syntax.args),
        )
    if syntax.kind == "abstract":
        raise PatternError("an abstraction `x. body` is an argument of a constructor")
    if syntax.kind == "extend":
        raise PatternError("a context extension `(ctx, x : A)` is a judgment argument")
    constructor = signature.constructors.get(syntax.name)
    if constructor is None:
        raise PatternError(
            f"{syntax.name!r} is not a constructor of signature {signature.name!r}"
        )
    if len(syntax.args) != constructor.arity:
        raise PatternError(
            f"{syntax.name!r} takes {constructor.arity} arguments, "
            f"got {len(syntax.args)}"
        )
    arguments: list[PatternArgument] = []
    for position, argument in enumerate(syntax.args):
        bound = constructor.bound_at(position)
        if argument.kind == "abstract":
            if len(argument.names) != len(bound):
                raise PatternError(
                    f"{syntax.name!r} binds {len(bound)} variable(s) at argument "
                    f"{position + 1}, the pattern names {len(argument.names)}"
                )
            (body,) = argument.args
            arguments.append(resolve(body, signature, scope + argument.names))
            continue
        if bound:
            raise PatternError(
                f"{syntax.name!r} binds {len(bound)} variable(s) at argument "
                f"{position + 1}; write them before a dot, as in "
                f"`{' '.join(v.name for v in bound)}. body`"
            )
        arguments.append(resolve(argument, signature, scope))
    return PatternApplication(op=syntax.name, args=tuple(arguments))

parse_pattern

parse_pattern(text: str) -> PatternSyntax

Read a pattern written in source syntax.

Op(a, x y. body) applies a constructor, M[a, b] instantiates a metavariable, a bare name is resolved later by resolve, and string and integer literals are data leaves.

PARAMETER DESCRIPTION
text

The pattern.

TYPE: str

RETURNS DESCRIPTION
PatternSyntax

The written pattern.

RAISES DESCRIPTION
PatternError

If the text is not a pattern.

Source code in src/quivers/structural/patterns.py
def parse_pattern(text: str) -> PatternSyntax:
    """Read a pattern written in source syntax.

    ``Op(a, x y. body)`` applies a constructor, ``M[a, b]`` instantiates a
    metavariable, a bare name is resolved later by `resolve`, and string
    and integer literals are data leaves.

    Parameters
    ----------
    text : str
        The pattern.

    Returns
    -------
    PatternSyntax
        The written pattern.

    Raises
    ------
    PatternError
        If the text is not a pattern.
    """
    tokens: list[tuple[str, str]] = []
    position = 0
    while position < len(text):
        found = _TOKEN.match(text, position)
        if found is None or found.end() == position:
            if text[position:].strip():
                raise PatternError(f"unexpected text {text[position:]!r}")
            break
        kind = found.lastgroup
        assert kind is not None
        tokens.append((kind, found.group(kind)))
        position = found.end()
    cursor = 0

    def peek() -> tuple[str, str] | None:
        """The next token.

        Returns
        -------
        tuple of str or None
            Its kind and text, or ``None`` at the end.
        """
        return tokens[cursor] if cursor < len(tokens) else None

    def take(value: str | None = None) -> tuple[str, str]:
        """Consume the next token.

        Parameters
        ----------
        value : str or None
            The text it must have.

        Returns
        -------
        tuple of str
            Its kind and text.

        Raises
        ------
        PatternError
            If there is none or it differs.
        """
        nonlocal cursor
        token = peek()
        if token is None or (value is not None and token[1] != value):
            raise PatternError(f"expected {value or 'a term'} in {text!r}")
        cursor += 1
        return token

    def term() -> PatternSyntax:
        """Read one term.

        Returns
        -------
        PatternSyntax
            The term.
        """
        if peek() == ("punct", "("):
            take("(")
            base = term()
            if base.kind != "name":
                raise PatternError("a context extension starts with a context name")
            names: list[str] = []
            values: list[PatternSyntax] = []
            while peek() == ("punct", ","):
                take(",")
                names.append(take()[1])
                take(":")
                values.append(term())
            take(")")
            if not names:
                raise PatternError("a context extension adds at least one entry")
            return PatternSyntax(
                kind="extend", name=base.name, names=tuple(names), args=tuple(values)
            )
        kind, value = take()
        if kind == "string":
            return PatternSyntax(kind="leaf", leaf=ast.literal_eval(value))
        if kind == "int":
            return PatternSyntax(kind="leaf", leaf=int(value))
        if kind != "name":
            raise PatternError(f"unexpected {value!r} in {text!r}")
        after = peek()
        if after is not None and after[1] == "(":
            take("(")
            arguments: list[PatternSyntax] = []
            if peek() is not None and peek() != ("punct", ")"):
                arguments.append(argument())
                while peek() == ("punct", ","):
                    take(",")
                    arguments.append(argument())
            take(")")
            return PatternSyntax(kind="apply", name=value, args=tuple(arguments))
        if after is not None and after[1] == "[":
            take("[")
            arguments = [term()]
            while peek() == ("punct", ","):
                take(",")
                arguments.append(term())
            take("]")
            return PatternSyntax(kind="instance", name=value, args=tuple(arguments))
        return PatternSyntax(kind="name", name=value)

    def argument() -> PatternSyntax:
        """Read an argument: an abstraction or a term.

        Returns
        -------
        PatternSyntax
            The argument.
        """
        nonlocal cursor
        start = cursor
        names: list[str] = []
        while peek() is not None and peek()[0] == "name":  # type: ignore[index]
            names.append(take()[1])
            if peek() == ("punct", "."):
                take(".")
                return PatternSyntax(
                    kind="abstract", names=tuple(names), args=(term(),)
                )
            following = peek()
            if following is None or following[0] != "name":
                break
        cursor = start
        return term()

    result = term()
    if cursor != len(tokens):
        raise PatternError(f"unexpected {tokens[cursor][1]!r} in {text!r}")
    return result

pattern

pattern(text: str, signature: Signature) -> Pattern

Read and resolve a pattern.

PARAMETER DESCRIPTION
text

The pattern in source syntax.

TYPE: str

signature

The signature.

TYPE: Signature

RETURNS DESCRIPTION
Pattern

The pattern.

RAISES DESCRIPTION
PatternError

If it does not parse or resolve.

Source code in src/quivers/structural/patterns.py
def pattern(text: str, signature: Signature) -> Pattern:
    """Read and resolve a pattern.

    Parameters
    ----------
    text : str
        The pattern in source syntax.
    signature : Signature
        The signature.

    Returns
    -------
    Pattern
        The pattern.

    Raises
    ------
    PatternError
        If it does not parse or resolve.
    """
    resolved = resolve(parse_pattern(text), signature)
    if not isinstance(resolved, PatternApplication | Metavariable | PatternVariable):
        raise PatternError(f"{text!r} is a data value, not a pattern")
    return resolved

generic_name

generic_name(meta: str) -> str

The generic constant of a metavariable.

PARAMETER DESCRIPTION
meta

The metavariable.

TYPE: str

RETURNS DESCRIPTION
str

?M, never a declarable constructor name.

Source code in src/quivers/structural/patterns.py
def generic_name(meta: str) -> str:
    """The generic constant of a metavariable.

    Parameters
    ----------
    meta : str
        The metavariable.

    Returns
    -------
    str
        ``?M``, never a declarable constructor name.
    """
    return meta if meta.startswith("?") else f"?{meta}"