Skip to content

Coverage

These functions refine indices in the branches of a case analysis over a GADT (generalized algebraic data type) (Xi et al., 2003) and check that the case covers every constructor. Matching an empty vector, for instance, fixes its length at zero. Coverage checking uses such refinements to tell a missing case from a branch the indices make impossible.

coverage

GADT branch refinement and conservative coverage interfaces.

IndexEquation

IndexEquation = tuple[StaticArgument, StaticArgument]

Two static terms an enclosing branch has shown equal.

CoverageStatus

Bases: str, Enum

Whether a set of branch patterns covers a family.

Reachability

Bases: str, Enum

Whether a branch can be entered, as far as its equalities decide.

BranchPattern didactic-model

BranchPattern(*, constructor: ConstructorId | None = field(opaque=True, extras=OPAQUE_BY_VALUE), guarded: bool = False)

Bases: QiecModel

The shape of one case branch, as coverage sees it.

PARAMETER DESCRIPTION
constructor

The constructor the branch matches, or None for a wildcard.

TYPE: ConstructorId | None DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

guarded

Whether the branch carries a guard that may reject a matching value, which keeps it from counting toward completeness.

TYPE: bool DEFAULT: False

CoverageResult didactic-model

CoverageResult(*, status: CoverageStatus = field(opaque=True, extras=OPAQUE_BY_VALUE), missing: tuple[ConstructorId, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), duplicates: tuple[ConstructorId, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

The outcome of checking branch patterns against a family.

PARAMETER DESCRIPTION
status

Whether the patterns cover the family.

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

missing

Constructors no pattern matches.

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

duplicates

Constructors more than one pattern matches.

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

BranchRefinement didactic-model

BranchRefinement(*, skolems: tuple[str, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), givens: tuple[BranchGiven, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), reachability: Reachability = field(default=UNKNOWN, opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

Rigid skolems and local equalities available inside one branch.

PARAMETER DESCRIPTION
skolems

The names of the branch's rigid static variables.

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

givens

The equalities the branch's constructor makes available.

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

reachability

Whether the givens are jointly satisfiable, as far as the unifier decides.

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

given_equations

given_equations(givens: tuple[BranchGiven, ...]) -> tuple[IndexEquation, ...]

The equations a context's branch givens state.

PARAMETER DESCRIPTION
givens

Evidence introduced by enclosing case branches.

TYPE: tuple[BranchGiven, ...]

RETURNS DESCRIPTION
tuple[IndexEquation, ...]

Each given's two sides.

Source code in src/quivers/qiec/coverage.py
def given_equations(givens: tuple[BranchGiven, ...]) -> tuple[IndexEquation, ...]:
    """The equations a context's branch givens state.

    Parameters
    ----------
    givens : tuple[BranchGiven, ...]
        Evidence introduced by enclosing case branches.

    Returns
    -------
    tuple[IndexEquation, ...]
        Each given's two sides.
    """
    return tuple((given.equality.left, given.equality.right) for given in givens)

solve_equations

solve_equations(equations: tuple[IndexEquation, ...]) -> StaticSubstitution | None

The most general unifier of static equations, or None if they contradict.

Every static variable, rigid or named, is an unknown. The result is sound for both uses the checker makes of it: when it is None no instantiation satisfies the equations, so a branch that requires them is unreachable; and two terms it makes syntactically equal are equal under every instantiation that satisfies them.

PARAMETER DESCRIPTION
equations

The equations.

TYPE: tuple[IndexEquation, ...]

RETURNS DESCRIPTION
StaticSubstitution or None

The unifier, applied transitively by apply_unifier, or None.

Source code in src/quivers/qiec/coverage.py
def solve_equations(
    equations: tuple[IndexEquation, ...],
) -> StaticSubstitution | None:
    """The most general unifier of static equations, or ``None`` if they contradict.

    Every static variable, rigid or named, is an unknown. The result is
    sound for both uses the checker makes of it: when it is ``None`` no
    instantiation satisfies the equations, so a branch that requires
    them is unreachable; and two terms it makes syntactically equal are
    equal under every instantiation that satisfies them.

    Parameters
    ----------
    equations : tuple[IndexEquation, ...]
        The equations.

    Returns
    -------
    StaticSubstitution or None
        The unifier, applied transitively by `apply_unifier`, or ``None``.
    """
    solution: dict[tuple[str, object], StaticArgument] = {}
    try:
        for left, right in equations:
            _unify(left, right, solution)
    except _Contradiction:
        return None
    resolved = {key: _resolve(value, solution) for key, value in solution.items()}
    return _substitution(resolved)

apply_unifier

apply_unifier(term: StaticArgument, unifier: StaticSubstitution) -> StaticArgument

A term with a unifier applied.

PARAMETER DESCRIPTION
term

The term.

TYPE: StaticArgument

unifier

A result of solve_equations.

TYPE: StaticSubstitution

RETURNS DESCRIPTION
StaticArgument

The term with every solved variable replaced.

Source code in src/quivers/qiec/coverage.py
def apply_unifier(term: StaticArgument, unifier: StaticSubstitution) -> StaticArgument:
    """A term with a unifier applied.

    Parameters
    ----------
    term : StaticArgument
        The term.
    unifier : StaticSubstitution
        A result of `solve_equations`.

    Returns
    -------
    StaticArgument
        The term with every solved variable replaced.
    """
    return substitute_static(term, unifier)

equal_under

equal_under(left: StaticArgument, right: StaticArgument, equations: tuple[IndexEquation, ...]) -> bool

Whether two static terms are equal given some equations.

PARAMETER DESCRIPTION
left

The terms.

TYPE: StaticArgument

right

The terms.

TYPE: StaticArgument

equations

Equations known to hold, such as a branch's givens.

TYPE: tuple[IndexEquation, ...]

RETURNS DESCRIPTION
bool

True when the terms are syntactically equal, when the equations contradict (the position is unreachable), or when the equations' most general unifier makes them equal.

Source code in src/quivers/qiec/coverage.py
def equal_under(
    left: StaticArgument, right: StaticArgument, equations: tuple[IndexEquation, ...]
) -> bool:
    """Whether two static terms are equal given some equations.

    Parameters
    ----------
    left, right : StaticArgument
        The terms.
    equations : tuple[IndexEquation, ...]
        Equations known to hold, such as a branch's givens.

    Returns
    -------
    bool
        True when the terms are syntactically equal, when the equations
        contradict (the position is unreachable), or when the equations'
        most general unifier makes them equal.
    """
    if left == right:
        return True
    if not equations:
        return False
    unifier = solve_equations(equations)
    if unifier is None:
        return True
    return apply_unifier(left, unifier) == apply_unifier(right, unifier)

check_coverage

check_coverage(family: FamilyDecl, patterns: tuple[BranchPattern, ...], *, certified_impossible: frozenset[ConstructorId] = frozenset()) -> CoverageResult

Check constructor coverage without pretending opaque cases are total.

PARAMETER DESCRIPTION
family

The family being matched on.

TYPE: FamilyDecl

patterns

The branch patterns written, in source order.

TYPE: tuple[BranchPattern, ...]

certified_impossible

Constructors an equality solver has proven cannot occur, which may therefore be omitted without making the match incomplete.

TYPE: frozenset[ConstructorId] DEFAULT: frozenset()

RETURNS DESCRIPTION
CoverageResult

The status, the constructors still missing, and any matched twice. The status is UNKNOWN rather than COMPLETE whenever the family is open, a pattern is a wildcard or guarded, or a pattern names a constructor the family does not declare, since none of those can be decided here.

Source code in src/quivers/qiec/coverage.py
def check_coverage(
    family: FamilyDecl,
    patterns: tuple[BranchPattern, ...],
    *,
    certified_impossible: frozenset[ConstructorId] = frozenset(),
) -> CoverageResult:
    """Check constructor coverage without pretending opaque cases are total.

    Parameters
    ----------
    family : FamilyDecl
        The family being matched on.
    patterns : tuple[BranchPattern, ...]
        The branch patterns written, in source order.
    certified_impossible : frozenset[ConstructorId]
        Constructors an equality solver has proven cannot occur, which
        may therefore be omitted without making the match incomplete.

    Returns
    -------
    CoverageResult
        The status, the constructors still missing, and any matched
        twice. The status is `UNKNOWN` rather than `COMPLETE` whenever
        the family is open, a pattern is a wildcard or guarded, or a
        pattern names a constructor the family does not declare, since
        none of those can be decided here.
    """
    known = tuple(
        pattern.constructor for pattern in patterns if pattern.constructor is not None
    )
    seen: set[ConstructorId] = set()
    duplicates: list[ConstructorId] = []
    for constructor in known:
        if constructor in seen and constructor not in duplicates:
            duplicates.append(constructor)
        seen.add(constructor)

    missing = tuple(
        constructor
        for constructor in family.constructors
        if constructor not in seen and constructor not in certified_impossible
    )
    unresolved = (
        not family.closed
        or any(pattern.constructor is None or pattern.guarded for pattern in patterns)
        or any(constructor not in family.constructors for constructor in known)
    )
    if unresolved:
        status = CoverageStatus.UNKNOWN
    elif missing or duplicates:
        status = CoverageStatus.INCOMPLETE
    else:
        status = CoverageStatus.COMPLETE
    return CoverageResult(status=status, missing=missing, duplicates=tuple(duplicates))

refine_branch

refine_branch(family: FamilyDecl, constructor: ConstructorDecl, scrutinee: TypeApplication, constructor_arguments: tuple[StaticArgument, ...], assumptions: tuple[IndexEquation, ...] = ()) -> BranchRefinement

Introduce constructor skolems and index equalities for a branch.

The branch's equations (each scrutinee index equals the constructor's result index) are solved by first-order unification together with the equations of the enclosing branches. Indices the enclosing equations already make equal are reachable; equations with no solution, because distinct constructors would have to be equal at some depth, are impossible; all others remain UNKNOWN and still contribute branch effects and coverage.

PARAMETER DESCRIPTION
family

The family being matched on.

TYPE: FamilyDecl

constructor

The constructor this branch matches.

TYPE: ConstructorDecl

scrutinee

The applied family type being scrutinised, supplying the parameters and the indices to be refined.

TYPE: TypeApplication

constructor_arguments

Arguments instantiating the constructor's local telescope, normally the rigid skolems from constructor_skolems.

TYPE: tuple[StaticArgument, ...]

assumptions

Equations the enclosing branches established, which the branch's own equations are solved together with.

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

RETURNS DESCRIPTION
BranchRefinement

The skolems in scope, the equalities the match makes available, and whether the branch is reachable.

RAISES DESCRIPTION
TypeError

If the constructor belongs to another family, if the scrutinee does not inhabit the matched family, or if the scrutinee supplies the wrong number of arguments.

Source code in src/quivers/qiec/coverage.py
def refine_branch(
    family: FamilyDecl,
    constructor: ConstructorDecl,
    scrutinee: TypeApplication,
    constructor_arguments: tuple[StaticArgument, ...],
    assumptions: tuple[IndexEquation, ...] = (),
) -> BranchRefinement:
    """Introduce constructor skolems and index equalities for a branch.

    The branch's equations (each scrutinee index equals the constructor's
    result index) are solved by first-order unification together with the
    equations of the enclosing branches. Indices the enclosing equations
    already make equal are reachable; equations with no solution, because
    distinct constructors would have to be equal at some depth, are
    impossible; all others remain ``UNKNOWN`` and still contribute branch
    effects and coverage.

    Parameters
    ----------
    family : FamilyDecl
        The family being matched on.
    constructor : ConstructorDecl
        The constructor this branch matches.
    scrutinee : TypeApplication
        The applied family type being scrutinised, supplying the
        parameters and the indices to be refined.
    constructor_arguments : tuple[StaticArgument, ...]
        Arguments instantiating the constructor's local telescope,
        normally the rigid skolems from `constructor_skolems`.
    assumptions : tuple[IndexEquation, ...]
        Equations the enclosing branches established, which the branch's
        own equations are solved together with.

    Returns
    -------
    BranchRefinement
        The skolems in scope, the equalities the match makes available,
        and whether the branch is reachable.

    Raises
    ------
    TypeError
        If the constructor belongs to another family, if the scrutinee
        does not inhabit the matched family, or if the scrutinee supplies
        the wrong number of arguments.
    """
    if constructor.family != family.id:
        raise TypeError(f"constructor {constructor.name!r} belongs to another family")
    if scrutinee.constructor != family.type_constructor:
        raise TypeError("scrutinee does not inhabit the matched family")

    parameter_count = len(family.parameters)
    expected_count = parameter_count + len(family.indices)
    if len(scrutinee.arguments) != expected_count:
        raise TypeError(
            f"family {family.name!r} expects {expected_count} arguments, "
            f"got {len(scrutinee.arguments)}"
        )
    parameter_substitution = instantiate_telescope(
        family.parameters,
        scrutinee.arguments[:parameter_count],
    )
    local_substitution = instantiate_telescope(
        constructor.telescope,
        constructor_arguments,
    )
    substitution = StaticSubstitution(
        types=(*parameter_substitution.types, *local_substitution.types),
        indices=(*parameter_substitution.indices, *local_substitution.indices),
        effects=(*parameter_substitution.effects, *local_substitution.effects),
    )

    actual_indices = scrutinee.arguments[parameter_count:]
    if len(constructor.result_indices) != len(actual_indices):
        raise TypeError(
            f"constructor {constructor.name!r} returns the wrong number of indices"
        )

    givens: list[BranchGiven] = []
    equations: list[IndexEquation] = []
    for position, (binder, actual, result) in enumerate(
        zip(family.indices, actual_indices, constructor.result_indices, strict=True)
    ):
        result = substitute_static(result, substitution)
        equality = EqualityType(
            kind=_binder_classifier(binder), left=actual, right=result
        )
        equality_id = EqualityId.derive(constructor.id, position, equality)
        givens.append(BranchGiven(id=equality_id, equality=equality))
        equations.append((actual, result))

    unifier = solve_equations((*assumptions, *equations))
    known = solve_equations(assumptions)
    if unifier is None or known is None:
        reachability = Reachability.IMPOSSIBLE
    elif all(
        apply_unifier(actual, known) == apply_unifier(result, known)
        for actual, result in equations
    ):
        reachability = Reachability.REACHABLE
    else:
        reachability = Reachability.UNKNOWN
    return BranchRefinement(
        skolems=tuple(binder.name for binder in constructor.telescope),
        givens=tuple(givens),
        reachability=reachability,
    )

constructor_skolems

constructor_skolems(constructor: ConstructorDecl, scope: StaticScopeId) -> tuple[StaticArgument, ...]

Create rigid static variables for a constructor's local telescope.

PARAMETER DESCRIPTION
constructor

The constructor whose telescope to instantiate.

TYPE: ConstructorDecl

scope

Identity of the branch scope. It enters each variable's identity, so skolems from two branches are never confused and cannot be mistaken for one another when a type escapes.

TYPE: StaticScopeId

RETURNS DESCRIPTION
tuple[StaticArgument, ...]

One rigid variable per binder, in telescope order.

Source code in src/quivers/qiec/coverage.py
def constructor_skolems(
    constructor: ConstructorDecl,
    scope: StaticScopeId,
) -> tuple[StaticArgument, ...]:
    """Create rigid static variables for a constructor's local telescope.

    Parameters
    ----------
    constructor : ConstructorDecl
        The constructor whose telescope to instantiate.
    scope : StaticScopeId
        Identity of the branch scope. It enters each variable's identity,
        so skolems from two branches are never confused and cannot be
        mistaken for one another when a type escapes.

    Returns
    -------
    tuple[StaticArgument, ...]
        One rigid variable per binder, in telescope order.
    """
    arguments: list[StaticArgument] = []
    for position, binder in enumerate(constructor.telescope):
        identity = StaticVariableId.derive(
            scope,
            constructor.id,
            position,
            binder.tag,
        )
        if isinstance(binder, TypeBinder):
            arguments.append(
                TypeVariable(name=binder.name, kind=binder.kind, identity=identity)
            )
        elif isinstance(binder, IndexBinder):
            arguments.append(
                IndexVariable(name=binder.name, sort=binder.sort, identity=identity)
            )
        elif isinstance(binder, EffectBinder):
            arguments.append(EffectVariable(name=binder.name, identity=identity))
    return tuple(arguments)

check_indexed_coverage

check_indexed_coverage(family: FamilyDecl, constructors: tuple[ConstructorDecl, ...], scrutinee: TypeApplication, patterns: tuple[BranchPattern, ...], assumptions: tuple[IndexEquation, ...] = ()) -> CoverageResult

Coverage with omissions justified by closed-index contradiction.

Only constructors that the small equality solver certifies as impossible may be omitted. An unknown result remains a required case.

PARAMETER DESCRIPTION
family

The family being matched on.

TYPE: FamilyDecl

constructors

Declarations of the family's constructors, needed to refine each one against the scrutinee.

TYPE: tuple[ConstructorDecl, ...]

scrutinee

The applied family type being matched.

TYPE: TypeApplication

patterns

The branch patterns written.

TYPE: tuple[BranchPattern, ...]

assumptions

Equations the enclosing branches established.

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

RETURNS DESCRIPTION
CoverageResult

Coverage judged against the constructors that remain possible.

RAISES DESCRIPTION
TypeError

If a constructor belongs to another family, or the scrutinee does not inhabit the matched family.

Source code in src/quivers/qiec/coverage.py
def check_indexed_coverage(
    family: FamilyDecl,
    constructors: tuple[ConstructorDecl, ...],
    scrutinee: TypeApplication,
    patterns: tuple[BranchPattern, ...],
    assumptions: tuple[IndexEquation, ...] = (),
) -> CoverageResult:
    """Coverage with omissions justified by closed-index contradiction.

    Only constructors that the small equality solver certifies as impossible
    may be omitted.  An unknown result remains a required case.

    Parameters
    ----------
    family : FamilyDecl
        The family being matched on.
    constructors : tuple[ConstructorDecl, ...]
        Declarations of the family's constructors, needed to refine each
        one against the scrutinee.
    scrutinee : TypeApplication
        The applied family type being matched.
    patterns : tuple[BranchPattern, ...]
        The branch patterns written.
    assumptions : tuple[IndexEquation, ...]
        Equations the enclosing branches established.

    Returns
    -------
    CoverageResult
        Coverage judged against the constructors that remain possible.

    Raises
    ------
    TypeError
        If a constructor belongs to another family, or the scrutinee does
        not inhabit the matched family.
    """
    impossible: set[ConstructorId] = set()
    for constructor in constructors:
        scope = StaticScopeId.derive(
            "coverage",
            family.id,
            constructor.id,
            scrutinee,
        )
        refinement = refine_branch(
            family,
            constructor,
            scrutinee,
            constructor_skolems(constructor, scope),
            assumptions,
        )
        if refinement.reachability is Reachability.IMPOSSIBLE:
            impossible.add(constructor.id)
    return check_coverage(
        family,
        patterns,
        certified_impossible=frozenset(impossible),
    )

join_branch_rows

join_branch_rows(branches: tuple[tuple[Reachability, EffectRow], ...]) -> EffectRow

Union effects of every possibly reachable branch.

UNKNOWN is intentionally treated as reachable. Dropping it would make an incomplete equality solver unsound for effect inference.

PARAMETER DESCRIPTION
branches

Each branch's reachability and the row its body performs.

TYPE: tuple[tuple[Reachability, EffectRow], ...]

RETURNS DESCRIPTION
EffectRow

The union over every branch not certified impossible. Only a proven contradiction removes a branch's effects from the result.

RAISES DESCRIPTION
ValueError

If two reachable branches bind one instance to different interfaces, or their open tails cannot merge.

Source code in src/quivers/qiec/coverage.py
def join_branch_rows(
    branches: tuple[tuple[Reachability, EffectRow], ...],
) -> EffectRow:
    """Union effects of every possibly reachable branch.

    ``UNKNOWN`` is intentionally treated as reachable.  Dropping it would make
    an incomplete equality solver unsound for effect inference.

    Parameters
    ----------
    branches : tuple[tuple[Reachability, EffectRow], ...]
        Each branch's reachability and the row its body performs.

    Returns
    -------
    EffectRow
        The union over every branch not certified impossible. Only a
        proven contradiction removes a branch's effects from the result.

    Raises
    ------
    ValueError
        If two reachable branches bind one instance to different
        interfaces, or their open tails cannot merge.
    """
    result = EMPTY_ROW
    for reachability, row in branches:
        if reachability is not Reachability.IMPOSSIBLE:
            result = result.union(row)
    return result

Cited sources

Hongwei Xi, Chiyan Chen, and Gang Chen. Guarded Recursive Datatype Constructors. In Proceedings of the 30th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL), 224–235. 2003. doi:10.1145/604131.604150.