Skip to content

Patterns

Pattern matching for QIEC values: each authored pattern is resolved against the type it is checked against, the clauses are checked for exhaustiveness and redundancy, and the clause matrix is compiled to a decision tree that lowers to the one-level core case. The types reference describes the surface.

patterns

Pattern matching for QIEC values: resolution, coverage, and compilation.

A case or destructuring let is elaborated in four steps, none of which changes the QIEC core:

  1. resolution resolves each authored pattern against the type it is checked against, so a constructor name is read in the family the type selects and a bare name becomes either a nullary constructor or a variable;
  2. coverage checks exhaustiveness and redundancy with guard trees, as in Lower Your Guards, reporting a witness for every missing case;
  3. decision compiles the clause matrix to a decision tree, as in Maranget's compilation of pattern matching, testing each value at most once on every path;
  4. the elaborator lowers the tree to the existing one-level core case and if, sharing branch bodies through generated selector families when the tree would otherwise copy them.

The matching structure of a type (its alternatives, which of them a static index rules out, and the types of their fields) comes from structures, which other features extend through its provider registry.

resolution

Resolve authored patterns against the types they are checked against.

Patterns are checked, never synthesized: the type a pattern is matched against selects the alternatives its names refer to. A constructor name is read among the alternatives of that type, so two families may declare the same constructor name without a pattern ever being ambiguous; a bare name is a nullary alternative of that type when it declares one and a variable otherwise; a literal is admitted only by a type whose values are literals.

Pattern synonyms are expanded during resolution, in the environment of their use, so coverage and compilation see the patterns they stand for.

StructureOf

StructureOf = Callable[[TypeExpr], MatchStructure]

Describe the matching structure of a type.

PatternError

PatternError(node: object, message: str, code: str = 'qiec-pattern')

Bases: Exception

A pattern that cannot be resolved, located at an authored node.

PARAMETER DESCRIPTION
node

The authored node to blame, carrying line and col.

TYPE: object

message

What is wrong and what to write instead.

TYPE: str

code

The diagnostic code.

TYPE: str DEFAULT: 'qiec-pattern'

Source code in src/quivers/dsl/patterns/resolution.py
def __init__(self, node: object, message: str, code: str = "qiec-pattern"):
    super().__init__(message)
    self.node = node
    self.message = message
    self.code = code

ResolvedPattern didactic-model

ResolvedPattern()

Bases: TaggedUnion

A pattern whose names are resolved against its type.

RWildcard didactic-model

RWildcard(*, line: int = 0, col: int = 0, kind: Literal['wildcard'] = 'wildcard')

Bases: ResolvedPattern

Matches anything and binds nothing.

PARAMETER DESCRIPTION
line

The source position.

TYPE: int DEFAULT: 0

col

The source position.

TYPE: int DEFAULT: 0

kind

The discriminator.

TYPE: Literal['wildcard'] DEFAULT: 'wildcard'

RVariable didactic-model

RVariable(*, name: str, annotation: QiecTypeExpr | None = None, line: int = 0, col: int = 0, kind: Literal['variable'] = 'variable')

Bases: ResolvedPattern

Matches anything and binds it to a name.

PARAMETER DESCRIPTION
name

The name bound.

TYPE: str

annotation

The authored type the value must have, or None.

TYPE: QiecTypeExpr | None DEFAULT: None

line

The source position.

TYPE: int DEFAULT: 0

col

The source position.

TYPE: int DEFAULT: 0

kind

The discriminator.

TYPE: Literal['variable'] DEFAULT: 'variable'

RAlternative didactic-model

RAlternative(*, alternative: Alternative, statics: tuple[str, ...] = (), arguments: tuple[ResolvedPattern, ...] = (), line: int = 0, col: int = 0, kind: Literal['alternative'] = 'alternative')

Bases: ResolvedPattern

Matches values built by one alternative, field by field.

PARAMETER DESCRIPTION
alternative

The alternative matched.

TYPE: Alternative

statics

The names given to the alternative's static binders, in order, or empty when the pattern names none.

TYPE: tuple[str, ...] DEFAULT: ()

arguments

One sub-pattern per field.

TYPE: tuple[ResolvedPattern, ...] DEFAULT: ()

line

The source position.

TYPE: int DEFAULT: 0

col

The source position.

TYPE: int DEFAULT: 0

kind

The discriminator.

TYPE: Literal['alternative'] DEFAULT: 'alternative'

RLiteral didactic-model

RLiteral(*, value: int | str, line: int = 0, col: int = 0, kind: Literal['literal'] = 'literal')

Bases: ResolvedPattern

Matches one literal of an infinite literal domain.

PARAMETER DESCRIPTION
value

The literal.

TYPE: int | str

line

The source position.

TYPE: int DEFAULT: 0

col

The source position.

TYPE: int DEFAULT: 0

kind

The discriminator.

TYPE: Literal['literal'] DEFAULT: 'literal'

ROr didactic-model

ROr(*, alternatives: tuple[ResolvedPattern, ...], line: int = 0, col: int = 0, kind: Literal['or'] = 'or')

Bases: ResolvedPattern

Matches when one of its alternatives does, trying them in order.

PARAMETER DESCRIPTION
alternatives

The alternatives.

TYPE: tuple[ResolvedPattern, ...]

line

The source position.

TYPE: int DEFAULT: 0

col

The source position.

TYPE: int DEFAULT: 0

kind

The discriminator.

TYPE: Literal['or'] DEFAULT: 'or'

RAs didactic-model

RAs(*, pattern: ResolvedPattern, name: str, line: int = 0, col: int = 0, kind: Literal['as'] = 'as')

Bases: ResolvedPattern

Matches a pattern and binds the whole value to a name.

PARAMETER DESCRIPTION
pattern

The pattern matched.

TYPE: ResolvedPattern

name

The name bound to the whole value.

TYPE: str

line

The source position.

TYPE: int DEFAULT: 0

col

The source position.

TYPE: int DEFAULT: 0

kind

The discriminator.

TYPE: Literal['as'] DEFAULT: 'as'

RBinder didactic-model

RBinder(*, names: tuple[str, ...], variables: tuple[str, ...], body: ResolvedPattern, line: int = 0, col: int = 0, kind: Literal['binder'] = 'binder')

Bases: ResolvedPattern

Opens a field that binds variables, naming them.

PARAMETER DESCRIPTION
names

The names given to the bound variables, in binding order.

TYPE: tuple[str, ...]

variables

The keys of the alternatives that build each bound variable.

TYPE: tuple[str, ...]

body

The pattern the field is matched against.

TYPE: ResolvedPattern

line

The source position.

TYPE: int DEFAULT: 0

col

The source position.

TYPE: int DEFAULT: 0

kind

The discriminator.

TYPE: Literal['binder'] DEFAULT: 'binder'

PatternResolver didactic-model

PatternResolver(*, structure_of: StructureOf = field(opaque=True, extras=OPAQUE_BY_IDENTITY), synonyms: Mapping[str, QiecPatternSynonymDecl] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

Resolves the authored patterns of one module.

PARAMETER DESCRIPTION
structure_of

Describes the matching structure of a type.

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

synonyms

The module's pattern synonyms, by name.

TYPE: Mapping[str, QiecPatternSynonymDecl] DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE)

resolve

resolve(pattern: QiecPattern, type_: TypeExpr) -> ResolvedPattern

Resolve a pattern against the type it is checked against.

PARAMETER DESCRIPTION
pattern

The authored pattern.

TYPE: QiecPattern

type_

The type of the values it matches.

TYPE: TypeExpr

RETURNS DESCRIPTION
ResolvedPattern

The pattern with every name resolved.

RAISES DESCRIPTION
PatternError

If a name is not an alternative of the type, a constructor is given the wrong number of fields or static names, a literal does not belong to the type, a binder pattern does not match the field's declared binding arity, the alternatives of an or-pattern bind different names or types, a name is bound twice, or a synonym is used wrongly.

Source code in src/quivers/dsl/patterns/resolution.py
def resolve(self, pattern: QiecPattern, type_: TypeExpr) -> ResolvedPattern:
    """Resolve a pattern against the type it is checked against.

    Parameters
    ----------
    pattern : QiecPattern
        The authored pattern.
    type_ : TypeExpr
        The type of the values it matches.

    Returns
    -------
    ResolvedPattern
        The pattern with every name resolved.

    Raises
    ------
    PatternError
        If a name is not an alternative of the type, a constructor is
        given the wrong number of fields or static names, a literal
        does not belong to the type, a binder pattern does not match
        the field's declared binding arity, the alternatives of an
        or-pattern bind different names or types, a name is bound
        twice, or a synonym is used wrongly.
    """
    resolved = self._resolve(pattern, type_, None, ())
    self._check_linear(resolved, pattern)
    return resolved

bound_types

bound_types(pattern: ResolvedPattern, type_: TypeExpr) -> dict[str, TypeExpr]

The type of every variable a resolved pattern binds.

PARAMETER DESCRIPTION
pattern

The resolved pattern.

TYPE: ResolvedPattern

type_

The type it matches.

TYPE: TypeExpr

RETURNS DESCRIPTION
dict[str, TypeExpr]

The variables and their types at resolution skolems.

Source code in src/quivers/dsl/patterns/resolution.py
def bound_types(
    self, pattern: ResolvedPattern, type_: TypeExpr
) -> dict[str, TypeExpr]:
    """The type of every variable a resolved pattern binds.

    Parameters
    ----------
    pattern : ResolvedPattern
        The resolved pattern.
    type_ : TypeExpr
        The type it matches.

    Returns
    -------
    dict[str, TypeExpr]
        The variables and their types at resolution skolems.
    """
    found: dict[str, TypeExpr] = {}
    self._collect_types(pattern, type_, found)
    return found

resolution_statics

resolution_statics(structure: MatchStructure, alternative: Alternative) -> tuple[TypeExpr, ...]

The field types of an alternative at canonical resolution skolems.

PARAMETER DESCRIPTION
structure

The structure of the type matched.

TYPE: MatchStructure

alternative

One of its alternatives.

TYPE: Alternative

RETURNS DESCRIPTION
tuple[TypeExpr, ...]

The field types, with the alternative's statics as rigid variables of a scope derived from the type and the alternative.

Source code in src/quivers/dsl/patterns/resolution.py
def resolution_statics(
    structure: MatchStructure, alternative: Alternative
) -> tuple[TypeExpr, ...]:
    """The field types of an alternative at canonical resolution skolems.

    Parameters
    ----------
    structure : MatchStructure
        The structure of the type matched.
    alternative : Alternative
        One of its alternatives.

    Returns
    -------
    tuple[TypeExpr, ...]
        The field types, with the alternative's statics as rigid
        variables of a scope derived from the type and the alternative.
    """
    scope = StaticScopeId.derive("pattern-resolution", structure.type, alternative.key)
    return structure.field_types(alternative, structure.skolems(alternative, scope))

coverage

Coverage and redundancy of pattern matches, after Lower Your Guards.

Each clause is desugared to a guard tree: a sequence of guards x <- K(y1, ..., yn) (x was built by the alternative K, whose fields are the fresh variables yi) ending in the clause's right-hand side, with an or-pattern contributing one sequence per alternative and a Boolean guard contributing a test whose outcome is unknown. Two functions over refinement types follow the tree (Graf, Peyton Jones, and Scott 2020):

  • the uncovered set: the values no clause matches. A match whose uncovered set is inhabited is not exhaustive, and an inhabitant is the witness reported;
  • the reaching set of each right-hand side: the values that reach it. A clause whose reaching set is empty is redundant.

A refinement type is a disjunction of constraint sets, each recording for every variable either the alternative that built it (with its fields) or the alternatives it was not built by. Inhabitation is decided per variable by the matching structure of its type, which knows the static indices: an alternative the type's indices rule out never inhabits it, so a branch that is unreachable at a given index is not demanded. The test recurses into fields with bounded fuel and treats exhausted fuel as inhabited, so coverage is sound: a match is never reported exhaustive when it is not.

StructureUnder

StructureUnder = Callable[[TypeExpr, tuple[IndexEquation, ...]], MatchStructure]

Describe a type's matching structure under index equations in force.

Clause didactic-model

Clause(*, pattern: ResolvedPattern, guarded: bool = False)

Bases: Model

One clause, as coverage sees it.

PARAMETER DESCRIPTION
pattern

The resolved pattern.

TYPE: ResolvedPattern

guarded

Whether a guard may reject a value the pattern matches.

TYPE: bool DEFAULT: False

Redundancy didactic-model

Redundancy(*, clause: int, alternative: tuple[int, ...] = ())

Bases: Model

A clause, or one alternative of an or-pattern, no value reaches.

PARAMETER DESCRIPTION
clause

The clause's position.

TYPE: int

alternative

The choices of or-pattern alternatives that lead to the redundant path, or empty when the whole clause is redundant.

TYPE: tuple[int, ...] DEFAULT: ()

CoverageReport didactic-model

CoverageReport(*, witnesses: tuple[str, ...] = (), redundant: tuple[Redundancy, ...] = ())

Bases: Model

The outcome of checking a match.

PARAMETER DESCRIPTION
witnesses

Values no clause matches, rendered as patterns; empty when the match is exhaustive.

TYPE: tuple[str, ...] DEFAULT: ()

redundant

The clauses and or-pattern alternatives no value reaches.

TYPE: tuple[Redundancy, ...] DEFAULT: ()

check_coverage

check_coverage(clauses: tuple[Clause, ...], scrutinee: TypeExpr, structure_of: StructureUnder, assumptions: tuple[IndexEquation, ...] = ()) -> CoverageReport

Check a match for exhaustiveness and redundancy.

PARAMETER DESCRIPTION
clauses

The clauses, in order.

TYPE: tuple[Clause, ...]

scrutinee

The type of the value matched.

TYPE: TypeExpr

structure_of

Describes the matching structure of a type under index equations.

TYPE: StructureUnder

assumptions

The index equations the enclosing matches established.

TYPE: tuple[IndexEquation, ...] DEFAULT: ()

RETURNS DESCRIPTION
CoverageReport

Witnesses of the values no clause matches, and the clauses and or-pattern alternatives no value reaches.

Source code in src/quivers/dsl/patterns/coverage.py
def check_coverage(
    clauses: tuple[Clause, ...],
    scrutinee: TypeExpr,
    structure_of: StructureUnder,
    assumptions: tuple[IndexEquation, ...] = (),
) -> CoverageReport:
    """Check a match for exhaustiveness and redundancy.

    Parameters
    ----------
    clauses : tuple[Clause, ...]
        The clauses, in order.
    scrutinee : TypeExpr
        The type of the value matched.
    structure_of : StructureUnder
        Describes the matching structure of a type under index equations.
    assumptions : tuple[IndexEquation, ...]
        The index equations the enclosing matches established.

    Returns
    -------
    CoverageReport
        Witnesses of the values no clause matches, and the clauses and
        or-pattern alternatives no value reaches.
    """
    space = _Space(structure_of=structure_of)
    root = space.fresh(scrutinee)
    uncovered: list[_Nabla] = [_Nabla(assumptions=assumptions)]
    redundant: list[Redundancy] = []
    for position, clause in enumerate(clauses):
        reached_any = False
        unreached: list[tuple[int, ...]] = []
        for choices, guards in list(_expansions(clause.pattern, root, space)):
            covered = uncovered
            remaining: list[_Nabla] = []
            for guard in guards:
                for nabla in covered:
                    refuted = _refute(nabla, guard, space)
                    if refuted is not None:
                        remaining.append(refuted)
                covered = [
                    assumed
                    for nabla in covered
                    if (assumed := _assume(nabla, guard, space)) is not None
                ]
            reaching = [nabla for nabla in covered if _inhabited(nabla, space)]
            if reaching:
                reached_any = True
            else:
                unreached.append(choices)
            if clause.guarded:
                remaining.extend(covered)
            if len(remaining) > _LIMIT:
                remaining = uncovered
            uncovered = remaining
        if not reached_any:
            redundant.append(Redundancy(clause=position))
        else:
            redundant.extend(
                Redundancy(clause=position, alternative=choices)
                for choices in unreached
                if choices
            )
    witnesses: list[str] = []
    for nabla in uncovered:
        if not _inhabited(nabla, space):
            continue
        rendered = _render(nabla, root, space, _FUEL)
        if rendered not in witnesses:
            witnesses.append(rendered)
        if len(witnesses) >= 3:
            break
    return CoverageReport(witnesses=tuple(witnesses), redundant=tuple(redundant))

decision

Compile a clause matrix to a decision tree, after Maranget.

The clause matrix has one column per value still to be examined (an occurrence, named by its path from the scrutinee) and one row per clause. Compilation picks a column the first row needs, tests that value once, and continues with the specialized matrix in each outcome: for an alternative K, the rows whose pattern in the column is K(...) or a wildcard, with K's fields as new columns; for the alternatives no row names, the default matrix of the wildcard rows. A row whose remaining patterns are all wildcards selects its clause, behind the clause's guard when it has one (Maranget 2008).

Each value is tested at most once on any path from the root. The default subtree is compiled once and shared by every alternative that reaches it, so the result is a directed acyclic graph; the elaborator lowers a shared subtree once.

Occurrence

Occurrence = tuple[str, ...]

A path from the scrutinee: each step names an alternative and a field.

TypeAt

TypeAt = Callable[[Occurrence], TypeExpr]

The type of an occurrence.

ValueBinding didactic-model

ValueBinding(*, name: str, occurrence: Occurrence = (), variable: str | None = None, index: int = 0, annotation: QiecTypeExpr | None = None, line: int = 0, col: int = 0)

Bases: Model

A name a clause binds and where its value comes from.

PARAMETER DESCRIPTION
name

The name.

TYPE: str

occurrence

The occurrence whose value it binds, when it binds one.

TYPE: Occurrence DEFAULT: ()

variable

For a name a binder pattern gives a bound variable, the key of the alternative building that variable.

TYPE: str | None DEFAULT: None

index

The bound variable's de Bruijn index.

TYPE: int DEFAULT: 0

annotation

The authored type the value must have, or None.

TYPE: QiecTypeExpr | None DEFAULT: None

line

Where the name is written.

TYPE: int DEFAULT: 0

col

Where the name is written.

TYPE: int DEFAULT: 0

StaticBinding didactic-model

StaticBinding(*, name: str, occurrence: Occurrence, key: str, position: int)

Bases: Model

A static name a clause binds to one of an alternative's statics.

PARAMETER DESCRIPTION
name

The name.

TYPE: str

occurrence

The occurrence tested.

TYPE: Occurrence

key

The alternative whose telescope binds it.

TYPE: str

position

Its position in the telescope.

TYPE: int

Row didactic-model

Row(*, patterns: tuple[ResolvedPattern, ...], arm: int, guarded: bool = False, values: tuple[ValueBinding, ...] = (), statics: tuple[StaticBinding, ...] = ())

Bases: Model

One row of a clause matrix.

PARAMETER DESCRIPTION
patterns

One pattern per column.

TYPE: tuple[ResolvedPattern, ...]

arm

The clause the row belongs to.

TYPE: int

guarded

Whether the clause has a guard.

TYPE: bool DEFAULT: False

values

The value names bound so far.

TYPE: tuple[ValueBinding, ...] DEFAULT: ()

statics

The static names bound so far.

TYPE: tuple[StaticBinding, ...] DEFAULT: ()

Node didactic-model

Node()

Bases: TaggedUnion

A decision tree node.

Leaf didactic-model

Leaf(*, id: int, arm: int, values: tuple[ValueBinding, ...] = (), statics: tuple[StaticBinding, ...] = (), guarded: bool = False, otherwise: int | None = None, kind: Literal['leaf'] = 'leaf')

Bases: Node

Select a clause.

PARAMETER DESCRIPTION
id

The node's position in the tree's node table.

TYPE: int

arm

The clause selected.

TYPE: int

values

The value names the clause binds.

TYPE: tuple[ValueBinding, ...] DEFAULT: ()

statics

The static names the clause binds.

TYPE: tuple[StaticBinding, ...] DEFAULT: ()

guarded

Whether the clause's guard is tested first.

TYPE: bool DEFAULT: False

otherwise

The node continued at when the guard fails.

TYPE: int | None DEFAULT: None

kind

The discriminator.

TYPE: Literal['leaf'] DEFAULT: 'leaf'

Branch didactic-model

Branch(*, key: str | None = None, literal: int | str | None = None, target: int)

Bases: Model

One outcome of a switch.

PARAMETER DESCRIPTION
key

The alternative, for a finite switch.

TYPE: str | None DEFAULT: None

literal

The literal, for a literal switch.

TYPE: int | str | None DEFAULT: None

target

The node continued at.

TYPE: int

Switch didactic-model

Switch(*, id: int, occurrence: Occurrence, branches: tuple[Branch, ...], default: int | None = None, kind: Literal['switch'] = 'switch')

Bases: Node

Test one occurrence.

PARAMETER DESCRIPTION
id

The node's position in the tree's node table.

TYPE: int

occurrence

The occurrence tested.

TYPE: Occurrence

branches

One branch per possible alternative, or per literal written.

TYPE: tuple[Branch, ...]

default

For a literal switch, the node continued at when no literal matches.

TYPE: int | None DEFAULT: None

kind

The discriminator.

TYPE: Literal['switch'] DEFAULT: 'switch'

DecisionTree didactic-model

DecisionTree(*, nodes: tuple[Node, ...], root: int)

Bases: Model

A compiled match.

PARAMETER DESCRIPTION
nodes

Every node, indexed by its id.

TYPE: tuple[Node, ...]

root

The root node.

TYPE: int

node

node(identity: int) -> Node

The node with an id.

PARAMETER DESCRIPTION
identity

The id.

TYPE: int

RETURNS DESCRIPTION
Node

The node.

Source code in src/quivers/dsl/patterns/decision.py
def node(self, identity: int) -> Node:
    """The node with an id.

    Parameters
    ----------
    identity : int
        The id.

    Returns
    -------
    Node
        The node.
    """
    return self.nodes[identity]

references

references() -> dict[int, int]

How many edges point at each node.

RETURNS DESCRIPTION
dict[int, int]

Incoming edge counts, with the root counted once.

Source code in src/quivers/dsl/patterns/decision.py
def references(self) -> dict[int, int]:
    """How many edges point at each node.

    Returns
    -------
    dict[int, int]
        Incoming edge counts, with the root counted once.
    """
    counts: dict[int, int] = {self.root: 1}
    for node in self.nodes:
        for target in _targets(node):
            counts[target] = counts.get(target, 0) + 1
    return counts

step

step(key: str, position: int) -> str

One step of an occurrence: a field of an alternative.

PARAMETER DESCRIPTION
key

The alternative's key.

TYPE: str

position

The field's position.

TYPE: int

RETURNS DESCRIPTION
str

The step, key#position.

Source code in src/quivers/dsl/patterns/decision.py
def step(key: str, position: int) -> str:
    """One step of an occurrence: a field of an alternative.

    Parameters
    ----------
    key : str
        The alternative's key.
    position : int
        The field's position.

    Returns
    -------
    str
        The step, ``key#position``.
    """
    return f"{key}#{position}"

parse_step

parse_step(text: str) -> tuple[str, int]

Split an occurrence step into its alternative and field.

PARAMETER DESCRIPTION
text

A step made by step.

TYPE: str

RETURNS DESCRIPTION
tuple[str, int]

The alternative's key and the field's position.

Source code in src/quivers/dsl/patterns/decision.py
def parse_step(text: str) -> tuple[str, int]:
    """Split an occurrence step into its alternative and field.

    Parameters
    ----------
    text : str
        A step made by `step`.

    Returns
    -------
    tuple[str, int]
        The alternative's key and the field's position.
    """
    key, position = text.rsplit("#", 1)
    return key, int(position)

compile_match

compile_match(patterns: tuple[tuple[ResolvedPattern, bool], ...], scrutinee: TypeExpr, structure_of: StructureUnder, assumptions: tuple[IndexEquation, ...] = ()) -> DecisionTree

Compile clauses to a decision tree.

PARAMETER DESCRIPTION
patterns

Each clause's resolved pattern and whether it is guarded, in order.

TYPE: tuple[tuple[ResolvedPattern, bool], ...]

scrutinee

The type of the value matched.

TYPE: TypeExpr

structure_of

Describes the matching structure of a type under index equations.

TYPE: StructureUnder

assumptions

The index equations the enclosing matches established.

TYPE: tuple[IndexEquation, ...] DEFAULT: ()

RETURNS DESCRIPTION
DecisionTree

The tree. Every possible value reaches a leaf, given that coverage has accepted the clauses.

Source code in src/quivers/dsl/patterns/decision.py
def compile_match(
    patterns: tuple[tuple[ResolvedPattern, bool], ...],
    scrutinee: TypeExpr,
    structure_of: StructureUnder,
    assumptions: tuple[IndexEquation, ...] = (),
) -> DecisionTree:
    """Compile clauses to a decision tree.

    Parameters
    ----------
    patterns : tuple[tuple[ResolvedPattern, bool], ...]
        Each clause's resolved pattern and whether it is guarded, in order.
    scrutinee : TypeExpr
        The type of the value matched.
    structure_of : StructureUnder
        Describes the matching structure of a type under index equations.
    assumptions : tuple[IndexEquation, ...]
        The index equations the enclosing matches established.

    Returns
    -------
    DecisionTree
        The tree. Every possible value reaches a leaf, given that coverage
        has accepted the clauses.
    """
    compiler = _Compiler(structure_of=structure_of)
    compiler.types[()] = scrutinee
    rows = tuple(
        Row(patterns=(pattern,), arm=arm, guarded=guarded)
        for arm, (pattern, guarded) in enumerate(patterns)
    )
    root = compiler.compile(((),), rows, assumptions)
    return DecisionTree(nodes=tuple(compiler.nodes), root=root)

leaf_counts

leaf_counts(tree: DecisionTree, shared: frozenset[int]) -> dict[int, int]

How many times each clause body would be lowered.

PARAMETER DESCRIPTION
tree

The tree.

TYPE: DecisionTree

shared

Nodes lowered once however many edges reach them.

TYPE: frozenset[int]

RETURNS DESCRIPTION
dict[int, int]

For each clause, the number of leaves selecting it on the lowered tree, counting a node reached by several edges once per edge unless it is shared.

Source code in src/quivers/dsl/patterns/decision.py
def leaf_counts(tree: DecisionTree, shared: frozenset[int]) -> dict[int, int]:
    """How many times each clause body would be lowered.

    Parameters
    ----------
    tree : DecisionTree
        The tree.
    shared : frozenset[int]
        Nodes lowered once however many edges reach them.

    Returns
    -------
    dict[int, int]
        For each clause, the number of leaves selecting it on the lowered
        tree, counting a node reached by several edges once per edge
        unless it is shared.
    """
    counts: dict[int, int] = {}

    def lowered(identity: int, seen: set[int]) -> None:
        node = tree.node(identity)
        if isinstance(node, Leaf):
            counts[node.arm] = counts.get(node.arm, 0) + 1
        for target in _targets(node):
            if target in shared:
                if target not in seen:
                    seen.add(target)
                    lowered(target, seen)
                continue
            lowered(target, seen)

    seen: set[int] = set()
    if tree.root in shared:
        seen.add(tree.root)
    lowered(tree.root, seen)
    return counts

lowered_size

lowered_size(tree: DecisionTree, shared: frozenset[int]) -> int

The number of nodes the lowered tree contains.

PARAMETER DESCRIPTION
tree

The tree.

TYPE: DecisionTree

shared

Nodes lowered once however many edges reach them.

TYPE: frozenset[int]

RETURNS DESCRIPTION
int

Nodes counted once per path to them, except shared nodes, which are counted once.

Source code in src/quivers/dsl/patterns/decision.py
def lowered_size(tree: DecisionTree, shared: frozenset[int]) -> int:
    """The number of nodes the lowered tree contains.

    Parameters
    ----------
    tree : DecisionTree
        The tree.
    shared : frozenset[int]
        Nodes lowered once however many edges reach them.

    Returns
    -------
    int
        Nodes counted once per path to them, except shared nodes, which
        are counted once.
    """
    seen: set[int] = set()

    def size(identity: int) -> int:
        node = tree.node(identity)
        total = 1
        for target in _targets(node):
            if target in shared:
                if target in seen:
                    continue
                seen.add(target)
            total += size(target)
        return total

    return size(tree.root)

structures

The matching structure of a QIEC value type.

A pattern is checked against a type, and what it may say about a value of that type is fixed by the type's structure: the alternatives a value is built from, which of them the type's static indices rule out, the types of each alternative's fields, and how a test on the value is lowered to the core. A MatchStructure answers those questions for one type.

Structures come from providers. The built-in providers cover declared families (generically, from their constructors), Bool, Unit, tuples, and the literal domains Int and String. A feature that adds value types registers its own provider with register_structure_provider; patterns over its types then resolve, are covered, and compile through the same machinery with no change here.

TRUE module-attribute

TRUE = Alternative(key='true', name='true', arity=0, form='name')

The alternative true of Bool.

FALSE module-attribute

FALSE = Alternative(key='false', name='false', arity=0, form='name')

The alternative false of Bool.

UNIT_VALUE module-attribute

UNIT_VALUE = Alternative(key='unit', name='unit', arity=0, form='name')

The only alternative of Unit.

Lowering

Lowering = Literal['case', 'boolean', 'product', 'literal', 'opaque', 'custom']

How a test on a value of the type is lowered to the core.

case is a core case over a declared family; boolean an if; product needs no test and reads fields by projection; literal is a chain of equality tests; opaque admits no test at all; custom defers to the structure's own switch.

BranchBody

BranchBody = Callable[[tuple[Local, ...]], tuple[Computation, TypeExpr]]

Lowers one arm of a custom switch, given the locals its fields are bound to.

StructureProvider

StructureProvider = Callable[[TypeExpr, KernelRegistry, dict[ConstructorId, tuple[tuple[ConstructorId, ...], ...]]], MatchStructure | None]

Describe a type's matching structure, or return None to decline it.

The provider receives the type, the registry it is checked against, and the binding arities of the module's constructors.

Alternative didactic-model

Alternative(*, key: str, name: str, arity: int, form: Literal['constructor', 'tuple', 'record', 'name'] = 'constructor', labels: tuple[str, ...] = (), telescope: Telescope = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), binders: tuple[tuple[str, ...], ...] = ())

Bases: ValueModel

One way a value of a type can be built.

PARAMETER DESCRIPTION
key

A stable key, unique among the type's alternatives.

TYPE: str

name

The name a pattern uses for the alternative, and the name a witness prints.

TYPE: str

arity

The number of fields.

TYPE: int

form

How a witness prints the alternative: a constructor applied to its fields, a tuple, a record, or a bare name.

TYPE: Literal['constructor', 'tuple', 'record', 'name'] DEFAULT: 'constructor'

labels

The field labels, for an alternative whose fields are labelled.

TYPE: tuple[str, ...] DEFAULT: ()

telescope

The static binders the alternative brings into scope, which a pattern may name in brackets.

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

binders

For each field, the keys of the alternatives that build the variables the field binds, in binding order; empty for a field that binds nothing.

TYPE: tuple[tuple[str, ...], ...] DEFAULT: ()

MatchStructure

Bases: Protocol

What patterns may say about values of one type.

ATTRIBUTE DESCRIPTION
type

The type described.

TYPE: TypeExpr

lowering

How a test on a value of the type is lowered.

TYPE: Lowering

type property

type: TypeExpr

The type this structure describes.

lowering property

lowering: Lowering

How a test on a value of the type is lowered.

alternatives

alternatives() -> tuple[Alternative, ...]

Every alternative, in declaration order.

RETURNS DESCRIPTION
tuple[Alternative, ...]

The alternatives; empty for a literal or opaque type.

Source code in src/quivers/dsl/patterns/structures.py
def alternatives(self) -> tuple[Alternative, ...]:
    """Every alternative, in declaration order.

    Returns
    -------
    tuple[Alternative, ...]
        The alternatives; empty for a literal or opaque type.
    """
    ...

possible

possible(alternative: Alternative) -> bool

Whether a value of this type can be built by an alternative.

PARAMETER DESCRIPTION
alternative

One of this structure's alternatives.

TYPE: Alternative

RETURNS DESCRIPTION
bool

False only when the type's static indices rule it out.

Source code in src/quivers/dsl/patterns/structures.py
def possible(self, alternative: Alternative) -> bool:
    """Whether a value of this type can be built by an alternative.

    Parameters
    ----------
    alternative : Alternative
        One of this structure's alternatives.

    Returns
    -------
    bool
        False only when the type's static indices rule it out.
    """
    ...

skolems

skolems(alternative: Alternative, scope: StaticScopeId) -> tuple[StaticArgument, ...]

Rigid variables for an alternative's telescope in one scope.

PARAMETER DESCRIPTION
alternative

One of this structure's alternatives.

TYPE: Alternative

scope

The scope the variables are minted in.

TYPE: StaticScopeId

RETURNS DESCRIPTION
tuple[StaticArgument, ...]

One variable per telescope binder.

Source code in src/quivers/dsl/patterns/structures.py
def skolems(
    self, alternative: Alternative, scope: StaticScopeId
) -> tuple[StaticArgument, ...]:
    """Rigid variables for an alternative's telescope in one scope.

    Parameters
    ----------
    alternative : Alternative
        One of this structure's alternatives.
    scope : StaticScopeId
        The scope the variables are minted in.

    Returns
    -------
    tuple[StaticArgument, ...]
        One variable per telescope binder.
    """
    ...

field_types

field_types(alternative: Alternative, statics: tuple[StaticArgument, ...]) -> tuple[TypeExpr, ...]

The types of an alternative's fields at given statics.

PARAMETER DESCRIPTION
alternative

One of this structure's alternatives.

TYPE: Alternative

statics

Arguments for the alternative's telescope.

TYPE: tuple[StaticArgument, ...]

RETURNS DESCRIPTION
tuple[TypeExpr, ...]

One type per field.

Source code in src/quivers/dsl/patterns/structures.py
def field_types(
    self, alternative: Alternative, statics: tuple[StaticArgument, ...]
) -> tuple[TypeExpr, ...]:
    """The types of an alternative's fields at given statics.

    Parameters
    ----------
    alternative : Alternative
        One of this structure's alternatives.
    statics : tuple[StaticArgument, ...]
        Arguments for the alternative's telescope.

    Returns
    -------
    tuple[TypeExpr, ...]
        One type per field.
    """
    ...

project

project(value: Value, alternative: Alternative, position: int) -> Value

Read one field of a product value.

PARAMETER DESCRIPTION
value

A value of this type.

TYPE: Value

alternative

The structure's only alternative.

TYPE: Alternative

position

The field's position.

TYPE: int

RETURNS DESCRIPTION
Value

The field, as a pure value.

Source code in src/quivers/dsl/patterns/structures.py
def project(self, value: Value, alternative: Alternative, position: int) -> Value:
    """Read one field of a product value.

    Parameters
    ----------
    value : Value
        A value of this type.
    alternative : Alternative
        The structure's only alternative.
    position : int
        The field's position.

    Returns
    -------
    Value
        The field, as a pure value.
    """
    ...

switch

switch(scrutinee: Value, branches: tuple[tuple[Alternative, BranchBody], ...]) -> tuple[Computation, TypeExpr]

Lower a test on a value for a custom structure.

PARAMETER DESCRIPTION
scrutinee

The value tested.

TYPE: Value

branches

For every possible alternative, the function lowering its arm.

TYPE: tuple[tuple[Alternative, BranchBody], ...]

RETURNS DESCRIPTION
tuple[Computation, TypeExpr]

The test and the type every arm produces.

Source code in src/quivers/dsl/patterns/structures.py
def switch(
    self,
    scrutinee: Value,
    branches: tuple[tuple[Alternative, BranchBody], ...],
) -> tuple[Computation, TypeExpr]:
    """Lower a test on a value for a ``custom`` structure.

    Parameters
    ----------
    scrutinee : Value
        The value tested.
    branches : tuple[tuple[Alternative, BranchBody], ...]
        For every possible alternative, the function lowering its arm.

    Returns
    -------
    tuple[Computation, TypeExpr]
        The test and the type every arm produces.
    """
    ...

FamilyStructure didactic-model

FamilyStructure(*, type: TypeApplication = field(opaque=True, extras=OPAQUE_BY_VALUE), family: FamilyDecl = field(opaque=True, extras=OPAQUE_BY_VALUE), constructors: tuple[ConstructorDecl, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), bindings: dict[ConstructorId, tuple[tuple[ConstructorId, ...], ...]] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE), assumptions: tuple[IndexEquation, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

The structure of a declared family application.

PARAMETER DESCRIPTION
type

The family application.

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

family

The family it applies.

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

constructors

The family's constructors, in declaration order.

TYPE: tuple[ConstructorDecl, ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

bindings

For each constructor that has binder fields, the variable constructors each field binds.

TYPE: dict[ConstructorId, tuple[tuple[ConstructorId, ...], ...]] DEFAULT: field(default_factory=dict, opaque=True, extras=OPAQUE_BY_VALUE)

assumptions

Equations between static terms that the enclosing matches have established, which decide what the application's indices admit.

TYPE: tuple[IndexEquation, ...] DEFAULT: field(default=(), opaque=True, extras=OPAQUE_BY_VALUE)

lowering property

lowering: Lowering

A family is tested by a core case.

constructor

constructor(alternative: Alternative) -> ConstructorDecl

The constructor an alternative stands for.

PARAMETER DESCRIPTION
alternative

One of this structure's alternatives.

TYPE: Alternative

RETURNS DESCRIPTION
ConstructorDecl

The declaration.

RAISES DESCRIPTION
KeyError

If the alternative is not one of this family's.

Source code in src/quivers/dsl/patterns/structures.py
def constructor(self, alternative: Alternative) -> ConstructorDecl:
    """The constructor an alternative stands for.

    Parameters
    ----------
    alternative : Alternative
        One of this structure's alternatives.

    Returns
    -------
    ConstructorDecl
        The declaration.

    Raises
    ------
    KeyError
        If the alternative is not one of this family's.
    """
    for constructor in self.constructors:
        if str(constructor.id) == alternative.key:
            return constructor
    raise KeyError(alternative.key)

alternatives

alternatives() -> tuple[Alternative, ...]

One alternative per constructor, in declaration order.

RETURNS DESCRIPTION
tuple[Alternative, ...]

The alternatives.

Source code in src/quivers/dsl/patterns/structures.py
def alternatives(self) -> tuple[Alternative, ...]:
    """One alternative per constructor, in declaration order.

    Returns
    -------
    tuple[Alternative, ...]
        The alternatives.
    """
    return tuple(
        Alternative(
            key=str(constructor.id),
            name=constructor.name,
            arity=len(constructor.fields),
            form="constructor" if constructor.fields else "name",
            telescope=constructor.telescope,
            binders=tuple(
                tuple(str(variable) for variable in field)
                for field in self.bindings.get(constructor.id, ())
            ),
        )
        for constructor in self.constructors
    )

possible

possible(alternative: Alternative) -> bool

Whether the application's indices admit a constructor.

PARAMETER DESCRIPTION
alternative

One of this structure's alternatives.

TYPE: Alternative

RETURNS DESCRIPTION
bool

False only when the constructor's result indices cannot equal the application's under the structure's assumptions, the rule the core's coverage check applies.

Source code in src/quivers/dsl/patterns/structures.py
def possible(self, alternative: Alternative) -> bool:
    """Whether the application's indices admit a constructor.

    Parameters
    ----------
    alternative : Alternative
        One of this structure's alternatives.

    Returns
    -------
    bool
        False only when the constructor's result indices cannot equal
        the application's under the structure's assumptions, the rule
        the core's coverage check applies.
    """
    return (
        self.refinement(
            alternative,
            constructor_skolems(
                self.constructor(alternative),
                StaticScopeId.derive(
                    "pattern-possibility",
                    self.family.id,
                    alternative.key,
                    self.type,
                ),
            ),
        ).reachability
        is not Reachability.IMPOSSIBLE
    )

refinement

refinement(alternative: Alternative, statics: tuple[StaticArgument, ...]) -> BranchRefinement

What matching an alternative at given statics establishes.

PARAMETER DESCRIPTION
alternative

One of this structure's alternatives.

TYPE: Alternative

statics

Arguments for the constructor's own telescope.

TYPE: tuple[StaticArgument, ...]

RETURNS DESCRIPTION
BranchRefinement

The branch's givens and whether it is reachable under the structure's assumptions.

Source code in src/quivers/dsl/patterns/structures.py
def refinement(
    self, alternative: Alternative, statics: tuple[StaticArgument, ...]
) -> BranchRefinement:
    """What matching an alternative at given statics establishes.

    Parameters
    ----------
    alternative : Alternative
        One of this structure's alternatives.
    statics : tuple[StaticArgument, ...]
        Arguments for the constructor's own telescope.

    Returns
    -------
    BranchRefinement
        The branch's givens and whether it is reachable under the
        structure's assumptions.
    """
    return refine_branch(
        self.family,
        self.constructor(alternative),
        self.type,
        statics,
        self.assumptions,
    )

equations

equations(alternative: Alternative, statics: tuple[StaticArgument, ...]) -> tuple[IndexEquation, ...]

The equations matching an alternative establishes.

PARAMETER DESCRIPTION
alternative

One of this structure's alternatives.

TYPE: Alternative

statics

Arguments for the constructor's own telescope.

TYPE: tuple[StaticArgument, ...]

RETURNS DESCRIPTION
tuple[IndexEquation, ...]

Each of the application's indices equals the constructor's result index at the statics.

Source code in src/quivers/dsl/patterns/structures.py
def equations(
    self, alternative: Alternative, statics: tuple[StaticArgument, ...]
) -> tuple[IndexEquation, ...]:
    """The equations matching an alternative establishes.

    Parameters
    ----------
    alternative : Alternative
        One of this structure's alternatives.
    statics : tuple[StaticArgument, ...]
        Arguments for the constructor's own telescope.

    Returns
    -------
    tuple[IndexEquation, ...]
        Each of the application's indices equals the constructor's
        result index at the statics.
    """
    return given_equations(self.refinement(alternative, statics).givens)

skolems

skolems(alternative: Alternative, scope: StaticScopeId) -> tuple[StaticArgument, ...]

The constructor's rigid variables in a branch scope.

PARAMETER DESCRIPTION
alternative

One of this structure's alternatives.

TYPE: Alternative

scope

The branch scope.

TYPE: StaticScopeId

RETURNS DESCRIPTION
tuple[StaticArgument, ...]

The canonical skolems the core expects of a branch.

Source code in src/quivers/dsl/patterns/structures.py
def skolems(
    self, alternative: Alternative, scope: StaticScopeId
) -> tuple[StaticArgument, ...]:
    """The constructor's rigid variables in a branch scope.

    Parameters
    ----------
    alternative : Alternative
        One of this structure's alternatives.
    scope : StaticScopeId
        The branch scope.

    Returns
    -------
    tuple[StaticArgument, ...]
        The canonical skolems the core expects of a branch.
    """
    return constructor_skolems(self.constructor(alternative), scope)

field_types

field_types(alternative: Alternative, statics: tuple[StaticArgument, ...]) -> tuple[TypeExpr, ...]

The constructor's field types at the application and statics.

PARAMETER DESCRIPTION
alternative

One of this structure's alternatives.

TYPE: Alternative

statics

Arguments for the constructor's own telescope.

TYPE: tuple[StaticArgument, ...]

RETURNS DESCRIPTION
tuple[TypeExpr, ...]

One type per field.

Source code in src/quivers/dsl/patterns/structures.py
def field_types(
    self, alternative: Alternative, statics: tuple[StaticArgument, ...]
) -> tuple[TypeExpr, ...]:
    """The constructor's field types at the application and statics.

    Parameters
    ----------
    alternative : Alternative
        One of this structure's alternatives.
    statics : tuple[StaticArgument, ...]
        Arguments for the constructor's own telescope.

    Returns
    -------
    tuple[TypeExpr, ...]
        One type per field.
    """
    constructor = self.constructor(alternative)
    count = len(self.family.parameters)
    parameters = instantiate_telescope(
        self.family.parameters, self.type.arguments[:count]
    )
    local = instantiate_telescope(constructor.telescope, statics)
    substitution = StaticSubstitution(
        types=(*parameters.types, *local.types),
        indices=(*parameters.indices, *local.indices),
        effects=(*parameters.effects, *local.effects),
    )
    return tuple(
        substitute_type(field.type, substitution) for field in constructor.fields
    )

project

project(value: Value, alternative: Alternative, position: int) -> Value

Families are not products.

PARAMETER DESCRIPTION
value

Unused.

TYPE: Value

alternative

Unused.

TYPE: Alternative

position

Unused.

TYPE: int

RETURNS DESCRIPTION
Value

Never returns.

RAISES DESCRIPTION
TypeError

Always: a family value's fields are bound by a case.

Source code in src/quivers/dsl/patterns/structures.py
def project(self, value: Value, alternative: Alternative, position: int) -> Value:
    """Families are not products.

    Parameters
    ----------
    value : Value
        Unused.
    alternative : Alternative
        Unused.
    position : int
        Unused.

    Returns
    -------
    Value
        Never returns.

    Raises
    ------
    TypeError
        Always: a family value's fields are bound by a ``case``.
    """
    raise TypeError("a family value's fields are bound by a case, not projected")

switch

switch(scrutinee: Value, branches: tuple[tuple[Alternative, BranchBody], ...]) -> tuple[Computation, TypeExpr]

Families are lowered by the elaborator's own case.

PARAMETER DESCRIPTION
scrutinee

Unused.

TYPE: Value

branches

Unused.

TYPE: tuple[tuple[Alternative, BranchBody], ...]

RETURNS DESCRIPTION
tuple[Computation, TypeExpr]

Never returns.

RAISES DESCRIPTION
TypeError

Always.

Source code in src/quivers/dsl/patterns/structures.py
def switch(
    self,
    scrutinee: Value,
    branches: tuple[tuple[Alternative, BranchBody], ...],
) -> tuple[Computation, TypeExpr]:
    """Families are lowered by the elaborator's own ``case``.

    Parameters
    ----------
    scrutinee : Value
        Unused.
    branches : tuple[tuple[Alternative, BranchBody], ...]
        Unused.

    Returns
    -------
    tuple[Computation, TypeExpr]
        Never returns.

    Raises
    ------
    TypeError
        Always.
    """
    raise TypeError("a family is lowered to a core case by the elaborator")

FiniteStructure didactic-model

FiniteStructure(*, type: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE), lowering: Lowering, choices: tuple[Alternative, ...])

Bases: ValueModel

A finite structure with no core family behind it.

Bool has the alternatives true and false, tested by if. A tuple type has one alternative whose fields are its components, and Unit one alternative with no fields; neither needs a test.

PARAMETER DESCRIPTION
type

The type described.

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

lowering

boolean or product.

TYPE: Lowering

choices

The alternatives.

TYPE: tuple[Alternative, ...]

alternatives

alternatives() -> tuple[Alternative, ...]

The alternatives.

RETURNS DESCRIPTION
tuple[Alternative, ...]

The structure's alternatives.

Source code in src/quivers/dsl/patterns/structures.py
def alternatives(self) -> tuple[Alternative, ...]:
    """The alternatives.

    Returns
    -------
    tuple[Alternative, ...]
        The structure's alternatives.
    """
    return self.choices

possible

possible(alternative: Alternative) -> bool

Every alternative is possible.

PARAMETER DESCRIPTION
alternative

Unused.

TYPE: Alternative

RETURNS DESCRIPTION
bool

True.

Source code in src/quivers/dsl/patterns/structures.py
def possible(self, alternative: Alternative) -> bool:
    """Every alternative is possible.

    Parameters
    ----------
    alternative : Alternative
        Unused.

    Returns
    -------
    bool
        True.
    """
    return True

skolems

skolems(alternative: Alternative, scope: StaticScopeId) -> tuple[StaticArgument, ...]

No alternative binds statics.

PARAMETER DESCRIPTION
alternative

Unused.

TYPE: Alternative

scope

Unused.

TYPE: StaticScopeId

RETURNS DESCRIPTION
tuple[StaticArgument, ...]

The empty tuple.

Source code in src/quivers/dsl/patterns/structures.py
def skolems(
    self, alternative: Alternative, scope: StaticScopeId
) -> tuple[StaticArgument, ...]:
    """No alternative binds statics.

    Parameters
    ----------
    alternative : Alternative
        Unused.
    scope : StaticScopeId
        Unused.

    Returns
    -------
    tuple[StaticArgument, ...]
        The empty tuple.
    """
    return ()

field_types

field_types(alternative: Alternative, statics: tuple[StaticArgument, ...]) -> tuple[TypeExpr, ...]

A tuple's components, or no fields.

PARAMETER DESCRIPTION
alternative

One of this structure's alternatives.

TYPE: Alternative

statics

Unused.

TYPE: tuple[StaticArgument, ...]

RETURNS DESCRIPTION
tuple[TypeExpr, ...]

The component types of a tuple, else the empty tuple.

Source code in src/quivers/dsl/patterns/structures.py
def field_types(
    self, alternative: Alternative, statics: tuple[StaticArgument, ...]
) -> tuple[TypeExpr, ...]:
    """A tuple's components, or no fields.

    Parameters
    ----------
    alternative : Alternative
        One of this structure's alternatives.
    statics : tuple[StaticArgument, ...]
        Unused.

    Returns
    -------
    tuple[TypeExpr, ...]
        The component types of a tuple, else the empty tuple.
    """
    if alternative.arity == 0 or not isinstance(self.type, TypeApplication):
        return ()
    return tuple(cast(TypeExpr, argument) for argument in self.type.arguments)

project

project(value: Value, alternative: Alternative, position: int) -> Value

Read a tuple component.

PARAMETER DESCRIPTION
value

A tuple value.

TYPE: Value

alternative

The tuple alternative.

TYPE: Alternative

position

The component.

TYPE: int

RETURNS DESCRIPTION
Value

The projection.

Source code in src/quivers/dsl/patterns/structures.py
def project(self, value: Value, alternative: Alternative, position: int) -> Value:
    """Read a tuple component.

    Parameters
    ----------
    value : Value
        A tuple value.
    alternative : Alternative
        The tuple alternative.
    position : int
        The component.

    Returns
    -------
    Value
        The projection.
    """
    return Projection(
        value=value,
        position=position,
        result_type=self.field_types(alternative, ())[position],
    )

switch

switch(scrutinee: Value, branches: tuple[tuple[Alternative, BranchBody], ...]) -> tuple[Computation, TypeExpr]

Finite structures are lowered by the elaborator.

PARAMETER DESCRIPTION
scrutinee

Unused.

TYPE: Value

branches

Unused.

TYPE: tuple[tuple[Alternative, BranchBody], ...]

RETURNS DESCRIPTION
tuple[Computation, TypeExpr]

Never returns.

RAISES DESCRIPTION
TypeError

Always.

Source code in src/quivers/dsl/patterns/structures.py
def switch(
    self,
    scrutinee: Value,
    branches: tuple[tuple[Alternative, BranchBody], ...],
) -> tuple[Computation, TypeExpr]:
    """Finite structures are lowered by the elaborator.

    Parameters
    ----------
    scrutinee : Value
        Unused.
    branches : tuple[tuple[Alternative, BranchBody], ...]
        Unused.

    Returns
    -------
    tuple[Computation, TypeExpr]
        Never returns.

    Raises
    ------
    TypeError
        Always.
    """
    raise TypeError("a finite structure is lowered by the elaborator")

LiteralStructure didactic-model

LiteralStructure(*, type: TypeExpr = field(opaque=True, extras=OPAQUE_BY_VALUE), lowering: Lowering)

Bases: ValueModel

An infinite domain matched by literals, Int or String.

A literal domain also stands for a type with no alternatives a pattern can name (Real, a tensor, a rigid type variable), which is the opaque lowering: only variables and wildcards match it.

PARAMETER DESCRIPTION
type

The type described.

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

lowering

literal or opaque.

TYPE: Lowering

alternatives

alternatives() -> tuple[Alternative, ...]

No finite list of alternatives.

RETURNS DESCRIPTION
tuple[Alternative, ...]

The empty tuple.

Source code in src/quivers/dsl/patterns/structures.py
def alternatives(self) -> tuple[Alternative, ...]:
    """No finite list of alternatives.

    Returns
    -------
    tuple[Alternative, ...]
        The empty tuple.
    """
    return ()

possible

possible(alternative: Alternative) -> bool

No alternative is possible.

PARAMETER DESCRIPTION
alternative

Unused.

TYPE: Alternative

RETURNS DESCRIPTION
bool

False.

Source code in src/quivers/dsl/patterns/structures.py
def possible(self, alternative: Alternative) -> bool:
    """No alternative is possible.

    Parameters
    ----------
    alternative : Alternative
        Unused.

    Returns
    -------
    bool
        False.
    """
    return False

skolems

skolems(alternative: Alternative, scope: StaticScopeId) -> tuple[StaticArgument, ...]

No statics.

PARAMETER DESCRIPTION
alternative

Unused.

TYPE: Alternative

scope

Unused.

TYPE: StaticScopeId

RETURNS DESCRIPTION
tuple[StaticArgument, ...]

The empty tuple.

Source code in src/quivers/dsl/patterns/structures.py
def skolems(
    self, alternative: Alternative, scope: StaticScopeId
) -> tuple[StaticArgument, ...]:
    """No statics.

    Parameters
    ----------
    alternative : Alternative
        Unused.
    scope : StaticScopeId
        Unused.

    Returns
    -------
    tuple[StaticArgument, ...]
        The empty tuple.
    """
    return ()

field_types

field_types(alternative: Alternative, statics: tuple[StaticArgument, ...]) -> tuple[TypeExpr, ...]

No fields.

PARAMETER DESCRIPTION
alternative

Unused.

TYPE: Alternative

statics

Unused.

TYPE: tuple[StaticArgument, ...]

RETURNS DESCRIPTION
tuple[TypeExpr, ...]

The empty tuple.

Source code in src/quivers/dsl/patterns/structures.py
def field_types(
    self, alternative: Alternative, statics: tuple[StaticArgument, ...]
) -> tuple[TypeExpr, ...]:
    """No fields.

    Parameters
    ----------
    alternative : Alternative
        Unused.
    statics : tuple[StaticArgument, ...]
        Unused.

    Returns
    -------
    tuple[TypeExpr, ...]
        The empty tuple.
    """
    return ()

project

project(value: Value, alternative: Alternative, position: int) -> Value

Literal values have no fields.

PARAMETER DESCRIPTION
value

Unused.

TYPE: Value

alternative

Unused.

TYPE: Alternative

position

Unused.

TYPE: int

RETURNS DESCRIPTION
Value

Never returns.

RAISES DESCRIPTION
TypeError

Always.

Source code in src/quivers/dsl/patterns/structures.py
def project(self, value: Value, alternative: Alternative, position: int) -> Value:
    """Literal values have no fields.

    Parameters
    ----------
    value : Value
        Unused.
    alternative : Alternative
        Unused.
    position : int
        Unused.

    Returns
    -------
    Value
        Never returns.

    Raises
    ------
    TypeError
        Always.
    """
    raise TypeError("a literal value has no fields")

switch

switch(scrutinee: Value, branches: tuple[tuple[Alternative, BranchBody], ...]) -> tuple[Computation, TypeExpr]

Literal tests are lowered by the elaborator.

PARAMETER DESCRIPTION
scrutinee

Unused.

TYPE: Value

branches

Unused.

TYPE: tuple[tuple[Alternative, BranchBody], ...]

RETURNS DESCRIPTION
tuple[Computation, TypeExpr]

Never returns.

RAISES DESCRIPTION
TypeError

Always.

Source code in src/quivers/dsl/patterns/structures.py
def switch(
    self,
    scrutinee: Value,
    branches: tuple[tuple[Alternative, BranchBody], ...],
) -> tuple[Computation, TypeExpr]:
    """Literal tests are lowered by the elaborator.

    Parameters
    ----------
    scrutinee : Value
        Unused.
    branches : tuple[tuple[Alternative, BranchBody], ...]
        Unused.

    Returns
    -------
    tuple[Computation, TypeExpr]
        Never returns.

    Raises
    ------
    TypeError
        Always.
    """
    raise TypeError("a literal test is lowered by the elaborator")

register_structure_provider

register_structure_provider(provider: StructureProvider) -> None

Add a provider consulted before the built-in ones.

PARAMETER DESCRIPTION
provider

A function describing the types it knows and declining the rest.

TYPE: StructureProvider

Source code in src/quivers/dsl/patterns/structures.py
def register_structure_provider(provider: StructureProvider) -> None:
    """Add a provider consulted before the built-in ones.

    Parameters
    ----------
    provider : StructureProvider
        A function describing the types it knows and declining the rest.
    """
    _PROVIDERS.append(provider)

tuple_alternative

tuple_alternative(arity: int) -> Alternative

The single alternative of a tuple type.

PARAMETER DESCRIPTION
arity

The number of components.

TYPE: int

RETURNS DESCRIPTION
Alternative

The alternative, keyed by its arity.

Source code in src/quivers/dsl/patterns/structures.py
def tuple_alternative(arity: int) -> Alternative:
    """The single alternative of a tuple type.

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

    Returns
    -------
    Alternative
        The alternative, keyed by its arity.
    """
    return Alternative(key=f"tuple{arity}", name="tuple", arity=arity, form="tuple")

branch_equations

branch_equations(structure: MatchStructure, alternative: Alternative, statics: tuple[StaticArgument, ...]) -> tuple[IndexEquation, ...]

The index equations matching an alternative establishes, if any.

PARAMETER DESCRIPTION
structure

The structure of the type matched.

TYPE: MatchStructure

alternative

One of its alternatives.

TYPE: Alternative

statics

Arguments for the alternative's telescope.

TYPE: tuple[StaticArgument, ...]

RETURNS DESCRIPTION
tuple[IndexEquation, ...]

A family's index equations; nothing for any other structure, whose alternatives refine no indices.

Source code in src/quivers/dsl/patterns/structures.py
def branch_equations(
    structure: MatchStructure,
    alternative: Alternative,
    statics: tuple[StaticArgument, ...],
) -> tuple[IndexEquation, ...]:
    """The index equations matching an alternative establishes, if any.

    Parameters
    ----------
    structure : MatchStructure
        The structure of the type matched.
    alternative : Alternative
        One of its alternatives.
    statics : tuple[StaticArgument, ...]
        Arguments for the alternative's telescope.

    Returns
    -------
    tuple[IndexEquation, ...]
        A family's index equations; nothing for any other structure,
        whose alternatives refine no indices.
    """
    if isinstance(structure, FamilyStructure):
        return structure.equations(alternative, statics)
    return ()

structure_of

structure_of(type_: TypeExpr, registry: KernelRegistry, bindings: dict[ConstructorId, tuple[tuple[ConstructorId, ...], ...]], assumptions: tuple[IndexEquation, ...] = ()) -> MatchStructure

Describe a type's matching structure.

PARAMETER DESCRIPTION
type_

The type a pattern is checked against.

TYPE: TypeExpr

registry

The registry declaring the module's families.

TYPE: KernelRegistry

bindings

The binding arities of constructors whose fields bind variables.

TYPE: dict[ConstructorId, tuple[tuple[ConstructorId, ...], ...]]

assumptions

Equations the enclosing matches established.

TYPE: tuple[IndexEquation, ...] DEFAULT: ()

RETURNS DESCRIPTION
MatchStructure

The first registered provider's answer, else the built-in one: a declared family, Bool, Unit, a tuple, Int or String as a literal domain, or an opaque type.

Source code in src/quivers/dsl/patterns/structures.py
def structure_of(
    type_: TypeExpr,
    registry: KernelRegistry,
    bindings: dict[ConstructorId, tuple[tuple[ConstructorId, ...], ...]],
    assumptions: tuple[IndexEquation, ...] = (),
) -> MatchStructure:
    """Describe a type's matching structure.

    Parameters
    ----------
    type_ : TypeExpr
        The type a pattern is checked against.
    registry : KernelRegistry
        The registry declaring the module's families.
    bindings : dict[ConstructorId, tuple[tuple[ConstructorId, ...], ...]]
        The binding arities of constructors whose fields bind variables.
    assumptions : tuple[IndexEquation, ...]
        Equations the enclosing matches established.

    Returns
    -------
    MatchStructure
        The first registered provider's answer, else the built-in one:
        a declared family, ``Bool``, ``Unit``, a tuple, ``Int`` or
        ``String`` as a literal domain, or an opaque type.
    """
    for provider in _PROVIDERS:
        provided = provider(type_, registry, bindings)
        if provided is not None:
            return provided
    if type_ == BOOL:
        return FiniteStructure(type=type_, lowering="boolean", choices=(TRUE, FALSE))
    if type_ == UNIT:
        return FiniteStructure(type=type_, lowering="product", choices=(UNIT_VALUE,))
    if type_ in (INT, STRING):
        return LiteralStructure(type=type_, lowering="literal")
    if isinstance(type_, TypeApplication):
        if _is_product(type_):
            return FiniteStructure(
                type=type_,
                lowering="product",
                choices=(tuple_alternative(len(type_.arguments)),),
            )
        family = _family_of(type_, registry)
        if family is not None:
            return FamilyStructure(
                type=type_,
                family=family,
                constructors=tuple(
                    registry.constructor(constructor)
                    for constructor in family.constructors
                ),
                bindings=bindings,
                assumptions=assumptions,
            )
    return LiteralStructure(type=type_, lowering="opaque")

statics

Static variables of QIEC types, and abstracting them into binders.

StaticVariable

A static variable: a rigid skolem or a telescope binder's variable.

free_statics

free_statics(term: StaticArgument) -> tuple[StaticVariable, ...]

The static variables a term mentions, in order of first occurrence.

PARAMETER DESCRIPTION
term

The term.

TYPE: StaticArgument

RETURNS DESCRIPTION
tuple[StaticVariable, ...]

Each variable once.

Source code in src/quivers/dsl/patterns/statics.py
def free_statics(term: StaticArgument) -> tuple[StaticVariable, ...]:
    """The static variables a term mentions, in order of first occurrence.

    Parameters
    ----------
    term : StaticArgument
        The term.

    Returns
    -------
    tuple[StaticVariable, ...]
        Each variable once.
    """
    found: list[StaticVariable] = []
    _collect(term, found)
    return tuple(dict.fromkeys(found))

binder_for

binder_for(variable: StaticVariable, name: str) -> TelescopeBinder

A binder ranging over what a variable ranges over.

PARAMETER DESCRIPTION
variable

The variable.

TYPE: StaticVariable

name

The binder's name.

TYPE: str

RETURNS DESCRIPTION
TelescopeBinder

A type binder of the variable's kind, an index binder of its sort, or an effect binder.

Source code in src/quivers/dsl/patterns/statics.py
def binder_for(variable: StaticVariable, name: str) -> TelescopeBinder:
    """A binder ranging over what a variable ranges over.

    Parameters
    ----------
    variable : StaticVariable
        The variable.
    name : str
        The binder's name.

    Returns
    -------
    TelescopeBinder
        A type binder of the variable's kind, an index binder of its sort,
        or an effect binder.
    """
    if isinstance(variable, TypeVariable):
        return TypeBinder(name=name, kind=variable.kind)
    if isinstance(variable, IndexVariable):
        return IndexBinder(name=name, sort=variable.sort)
    return EffectBinder(name=name)

variable_for

variable_for(binder: TelescopeBinder) -> StaticVariable

The variable a binder introduces, by name.

PARAMETER DESCRIPTION
binder

The binder.

TYPE: TelescopeBinder

RETURNS DESCRIPTION
StaticVariable

A variable with no identity, which substitution reaches by name.

Source code in src/quivers/dsl/patterns/statics.py
def variable_for(binder: TelescopeBinder) -> StaticVariable:
    """The variable a binder introduces, by name.

    Parameters
    ----------
    binder : TelescopeBinder
        The binder.

    Returns
    -------
    StaticVariable
        A variable with no identity, which substitution reaches by name.
    """
    if isinstance(binder, TypeBinder):
        return TypeVariable(name=binder.name, kind=binder.kind)
    if isinstance(binder, IndexBinder):
        return IndexVariable(name=binder.name, sort=binder.sort)
    return EffectVariable(name=binder.name)

abstract

abstract(type_: TypeExpr, variables: tuple[StaticVariable, ...], names: tuple[str, ...]) -> TypeExpr

Replace variables in a type by variables of new names.

PARAMETER DESCRIPTION
type_

The type.

TYPE: TypeExpr

variables

The variables to replace.

TYPE: tuple[StaticVariable, ...]

names

The name each becomes, a binder's name.

TYPE: tuple[str, ...]

RETURNS DESCRIPTION
TypeExpr

The type over the binders binder_for(variable, name), with rigid variables replaced by identity and the others by name.

Source code in src/quivers/dsl/patterns/statics.py
def abstract(
    type_: TypeExpr,
    variables: tuple[StaticVariable, ...],
    names: tuple[str, ...],
) -> TypeExpr:
    """Replace variables in a type by variables of new names.

    Parameters
    ----------
    type_ : TypeExpr
        The type.
    variables : tuple[StaticVariable, ...]
        The variables to replace.
    names : tuple[str, ...]
        The name each becomes, a binder's name.

    Returns
    -------
    TypeExpr
        The type over the binders ``binder_for(variable, name)``, with rigid
        variables replaced by identity and the others by name.
    """
    types: list[tuple[str, TypeExpr]] = []
    indices: list[tuple[str, IndexTerm]] = []
    effects: list[tuple[str, EffectRef | EffectVariable]] = []
    rigid: list[tuple[StaticVariableId, StaticArgument]] = []
    for variable, name in zip(variables, names, strict=True):
        replacement: StaticVariable
        if isinstance(variable, TypeVariable):
            replacement = TypeVariable(name=name, kind=variable.kind)
            if variable.identity is None:
                types.append((variable.name, replacement))
        elif isinstance(variable, IndexVariable):
            replacement = IndexVariable(name=name, sort=variable.sort)
            if variable.identity is None:
                indices.append((variable.name, replacement))
        else:
            replacement = EffectVariable(name=name)
            if variable.identity is None:
                effects.append((variable.name, replacement))
        if variable.identity is not None:
            rigid.append((variable.identity, replacement))
    substitution = StaticSubstitution(
        types=tuple(types),
        indices=tuple(indices),
        effects=tuple(effects),
        rigid=tuple(rigid),
    )
    return substitute_type(type_, substitution)

unification

First-order unification over QIEC static terms.

Constructor applications infer the static arguments they omit by unification over the constructor's telescope (Pottier 2014, restricted to static telescopes). The unknowns are metavariables: type, index, and effect variables whose names begin with ?, which no authored name can spell. A solution maps each metavariable's name to a static term.

Index arithmetic is solved only where it is a shift: a sum of one metavariable and a constant against a term the constant can be taken from. Everything else is structural.

META module-attribute

META = '?'

The prefix that marks a metavariable's name.

Solution

Solution = dict[str, StaticArgument]

Metavariable names and the static terms they are solved to.

metavariables

metavariables(telescope: Telescope, prefix: str) -> tuple[StaticArgument, ...]

One fresh metavariable per binder of a telescope.

PARAMETER DESCRIPTION
telescope

The binders.

TYPE: Telescope

prefix

Distinguishes these metavariables from any others in one problem.

TYPE: str

RETURNS DESCRIPTION
tuple[StaticArgument, ...]

A variable of each binder's class and classifier, named ?<prefix><position>.

Source code in src/quivers/dsl/patterns/unification.py
def metavariables(telescope: Telescope, prefix: str) -> tuple[StaticArgument, ...]:
    """One fresh metavariable per binder of a telescope.

    Parameters
    ----------
    telescope : Telescope
        The binders.
    prefix : str
        Distinguishes these metavariables from any others in one problem.

    Returns
    -------
    tuple[StaticArgument, ...]
        A variable of each binder's class and classifier, named
        ``?<prefix><position>``.
    """
    variables: list[StaticArgument] = []
    for position, binder in enumerate(telescope):
        name = f"{META}{prefix}{position}"
        if isinstance(binder, TypeBinder):
            variables.append(TypeVariable(name=name, kind=binder.kind))
        elif isinstance(binder, IndexBinder):
            variables.append(IndexVariable(name=name, sort=binder.sort))
        elif isinstance(binder, EffectBinder):
            variables.append(EffectVariable(name=name))
    return tuple(variables)

apply

apply(term: StaticArgument, solution: Mapping[str, StaticArgument]) -> StaticArgument

Substitute a solution into a term.

PARAMETER DESCRIPTION
term

The term.

TYPE: StaticArgument

solution

The solved metavariables.

TYPE: Mapping[str, StaticArgument]

RETURNS DESCRIPTION
StaticArgument

The term with every solved metavariable replaced, repeatedly, so a solution whose values mention other solved metavariables is fully applied.

Source code in src/quivers/dsl/patterns/unification.py
def apply(
    term: StaticArgument, solution: Mapping[str, StaticArgument]
) -> StaticArgument:
    """Substitute a solution into a term.

    Parameters
    ----------
    term : StaticArgument
        The term.
    solution : Mapping[str, StaticArgument]
        The solved metavariables.

    Returns
    -------
    StaticArgument
        The term with every solved metavariable replaced, repeatedly, so
        a solution whose values mention other solved metavariables is
        fully applied.
    """
    types: list[tuple[str, object]] = []
    indices: list[tuple[str, object]] = []
    effects: list[tuple[str, object]] = []
    for name, value in solution.items():
        if isinstance(
            value,
            IndexVariable | IndexLiteral | IndexConstructor | IndexSum | ShapeIndex,
        ):
            indices.append((name, value))
        elif isinstance(value, EffectRef | EffectVariable):
            effects.append((name, value))
        else:
            types.append((name, value))
    substitution = StaticSubstitution(
        types=tuple(types),  # type: ignore[arg-type]
        indices=tuple(indices),  # type: ignore[arg-type]
        effects=tuple(effects),  # type: ignore[arg-type]
    )
    current = term
    for _ in range(len(solution) + 1):
        following = substitute_static(current, substitution)
        if following == current:
            return current
        current = following
    return current

unsolved

unsolved(term: StaticArgument) -> tuple[str, ...]

The metavariables a term still mentions.

PARAMETER DESCRIPTION
term

The term.

TYPE: StaticArgument

RETURNS DESCRIPTION
tuple[str, ...]

Their names, in order of first occurrence.

Source code in src/quivers/dsl/patterns/unification.py
def unsolved(term: StaticArgument) -> tuple[str, ...]:
    """The metavariables a term still mentions.

    Parameters
    ----------
    term : StaticArgument
        The term.

    Returns
    -------
    tuple[str, ...]
        Their names, in order of first occurrence.
    """
    found: list[str] = []
    _collect(term, found)
    return tuple(dict.fromkeys(found))

unify

unify(left: StaticArgument, right: StaticArgument, solution: Solution) -> bool

Extend a solution so two terms become equal.

PARAMETER DESCRIPTION
left

One term.

TYPE: StaticArgument

right

The other.

TYPE: StaticArgument

solution

The solution so far, extended in place on success. On failure it may hold bindings made before the clash.

TYPE: Solution

RETURNS DESCRIPTION
bool

Whether the terms unify.

Source code in src/quivers/dsl/patterns/unification.py
def unify(left: StaticArgument, right: StaticArgument, solution: Solution) -> bool:
    """Extend a solution so two terms become equal.

    Parameters
    ----------
    left : StaticArgument
        One term.
    right : StaticArgument
        The other.
    solution : Solution
        The solution so far, extended in place on success. On failure it
        may hold bindings made before the clash.

    Returns
    -------
    bool
        Whether the terms unify.
    """
    left = apply(left, solution)
    right = apply(right, solution)
    if left == right:
        return True
    for meta, other in ((_meta_name(left), right), (_meta_name(right), left)):
        if meta is not None:
            if meta in unsolved(other):
                return False
            solution[meta] = other
            return True
    if isinstance(left, IndexSum) or isinstance(right, IndexSum):
        return _unify_shift(left, right, solution)
    if type(left) is not type(right):
        return False
    if isinstance(left, TypeApplication) and isinstance(right, TypeApplication):
        if left.constructor.id != right.constructor.id:
            return False
    elif isinstance(left, EffectRef) and isinstance(right, EffectRef):
        if left.id != right.id:
            return False
    elif isinstance(left, IndexConstructor) and isinstance(right, IndexConstructor):
        if left.name != right.name or left.sort != right.sort:
            return False
    elif isinstance(left, FunctionType) and isinstance(right, FunctionType):
        if left.effects != right.effects:
            return False
    elif not isinstance(left, ShapeIndex):
        return False
    left_children = _children(left)
    right_children = _children(right)
    if len(left_children) != len(right_children):
        return False
    return all(
        unify(a, b, solution)
        for a, b in zip(left_children, right_children, strict=True)
    )

elaboration

Bidirectional elaboration of QIEC values and pattern matches.

Mixed into the QIEC elaborator, this module elaborates:

  • constructor applications, where a constructor is an ordinary name. In checking mode the expected type selects the family and fixes its static arguments; in synthesis mode a name declared by one family selects it, and the static arguments are inferred by unification over the constructor's telescope. A name two families declare is refused with every candidate unless qualified (F.c) or checked against a type;
  • annotations (e : T), which check e against T;
  • case and destructuring let: patterns are resolved against the scrutinee's type, checked for coverage and redundancy, compiled to a decision tree, and lowered to the core's one-level case and if.

Nothing here adds a core term. Branch bodies the decision tree would copy are lowered once each, behind a generated selector family: the tree returns the selected branch and its bindings as a value, and one flat case over that value runs the body.