Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Exhaustiveness Checking

The typing rule for match in Pattern matching, T-Match, left its final premise unexplained: that the patterns exhaust the scrutinee’s type. To see what it does, take Arith and value from that chapter and add a constructor for negation, leaving value as it was:

type Arith = Num(Int) | Add(Arith, Arith) | Mul(Arith, Arith) | Neg(Arith);

fn value(e: Arith) -> Int = match e {
    Num(n) => n,
    Add(l, r) => value(l) + value(r),
    Mul(l, r) => value(l) * value(r),
};

fn main() {
    println(value(Neg(Num(1))));
}

The untyped evaluator runs this program until a Neg reaches value, then stops with NonExhaustiveMatch. A program that never builds a Neg on some input would pass on that input. The type checker rejects the program before it runs and points at the match.

A missing constructor is the simplest kind of gap. zip_with adds two lists element by element, stopping at the end of the shorter one:

fn zip_with(xs: [Int], ys: [Int]) -> [Int] = match (xs, ys) {
    ([], _) => [],
    (x :: a, y :: b) => (x + y) :: zip_with(a, b),
};

The first component’s patterns mention both list constructors, and the second component’s patterns include a wildcard that accepts any list. Yet the checker rejects this match too. The pair of a non-empty list and an empty one fits neither arm.

These examples raise some questions:

  • What does it mean for arms to cover a type? zip_with shows that each component can look covered on its own while a combination of them is missed.
  • How can a program check coverage of an infinite type? [Int] has infinitely many values, and Arith does too.
  • Which types can be covered without a catch-all? A Bool has two cases to list, whereas an Int has more than any program would write.
  • What do guards contribute? A guard can run arbitrary pure code to decide whether its arm applies.

From tags to nested patterns

Checks of this kind appeared alongside the sums themselves. The CLU Reference Manual (1979) has this rule for tagcase: “If all tags of T are present, there is no others arm; otherwise an others arm must be present.” A tagcase looks only at one tag, so the rule can be checked by comparing two lists of names. Hope stated the requirement for its equations as well: “The set of equations defining a function should exhaust the possibilities given in the data-statement introducing the argument types.”

Nesting makes the question harder, as zip_with shows, since a list of names no longer suffices. Luc Maranget’s “Warnings for Pattern Matching” (2007) reduced both exhaustiveness and the detection of useless arms to one predicate over a matrix of patterns. The algorithm in this chapter follows his definitions, and rustc’s source says its own check is “inspired from” the paper.

Coverage

Arms are exhaustive for a type when every value of type fits at least one of them:

Trying each value is out of the question for most types, but a finite set of patterns can only distinguish finitely many cases. The check works on the patterns, and it needs the scrutinee’s type to say which constructors exist. For Option<Int>, the type says that a value is a None or a Some, so a list of arms is complete when it handles both and, under Some, handles every Int. That is why exhaustiveness belongs in the type checker: the set of alternatives comes from the scrutinee’s type, and a pattern alone does not say what it left out.

Signatures

The signature of a type is its set of head constructors, each with its argument types.

TypeSignature
Booltrue, false
()()
(A, B)one constructor of arguments A, B
[T][], and :: of arguments T, [T]
Option<T>None, Some of argument T
a declared typeits constructors, at the type’s arguments
a structone constructor, with all fields in declaration order
Int, Stringno finite signature
a function or ref typeno finite signature

A list has two constructors, however long it is, so its signature is finite. An Int has too many literals to list, and a function has no patterns of its own, so for those types only a wildcard or variable can complete a set of arms.

A set of constructors is complete for a type when it contains the whole signature. Literals of an unbounded type are constructors with no arguments that can never form a complete set.

Before the check runs, patterns reduce to three forms. A variable becomes a wildcard, since it matches any value. A list pattern becomes the conses it abbreviates, so [x, y] becomes x :: y :: [] and [x, ...t] becomes x :: _. A struct pattern lists every declared field, with omitted fields as wildcards. What is left is , a constructor applied to patterns, or an alternative .

Usefulness

To check a match, place its patterns in a matrix with one row per arm. At the start has a single column, holding each arm’s pattern. As the algorithm unpacks constructors, a row grows into a vector of patterns, one per column, and a vector of values fits a row when each value fits the pattern in its column. A pattern vector is useful with respect to a matrix when some value vector matches and matches no row of .

Exhaustiveness is one question about usefulness. Arms are exhaustive exactly when a wildcard placed after them could not catch anything they miss:

works on the first column and recurses on smaller matrices. Two operations build those matrices.

The specialized matrix keeps the rows that can match a value whose first component is built by constructor of arity , with ’s arguments as new columns:

First pattern of the rowRow in
, with no row
the rows of and of

The default matrix keeps the rows that can match a first component built by a constructor that no row mentions, and it drops that column:

First pattern of the rowRow in
no row
the rows of and of

is then defined by the first pattern of , with for arguments and for the rest of the vector:

In the first line, is the vector with no columns, which matches the empty vector of values. That vector is caught if any row remains, so it is useful only when none does.

The first column’s heads are the constructors at the front of its patterns, including those inside an or-pattern at the front of a row, so a row beginning true | false contributes both.

If the rows mention every constructor of the first column’s type, a value must begin with one of them, and the check tries each. If some constructor is missing from the rows, a value built with it can be matched only by rows that begin with a wildcard, so finds what those rows leave uncovered.

The recursion ends because each step removes a constructor from a pattern or removes a column. The wildcard case splits only on constructors the rows already mention, so a recursive type like [Int] is unfolded no deeper than the patterns themselves go.

A trace

Take a pair of booleans, with one arm for (true, true) and one for (false, _). A tuple has one constructor, so the first step applies for that constructor and replaces the single column with two columns:

The first column’s heads are true and false, which is the whole signature of Bool, so tries each. For true:

The remaining column mentions true but never false, so the heads are incomplete and applies. No row begins with a wildcard, so has no rows:

The wildcard is useful, so the arms are not exhaustive. The path through the recursion names the missing value: true in the first column, and a constructor missing from the second column, which is false. The value (true, false) fits neither arm.

A trace across lists

zip_with’s arms start, after the tuple step and with variables as wildcards, as

The first column has both list constructors, so tries each.

For [], the row becomes , and the second row drops. That column has no constructors, so the heads are incomplete and leaves one row with no columns. A row remains, so is false, and an empty first list is covered.

For ::, which takes two arguments, drops the first row and expands the second into three columns: . Neither of the first two columns mentions a constructor, so two steps of apply and drop them in turn, leaving

This column mentions :: but not [], so the heads are incomplete. has no rows, and on no rows with no columns is true. The wildcard is useful, and the path names a non-empty first list with an empty second list.

Adding the arm (_, []) => [] puts a row in the matrix. In the :: case, the last column’s heads are now [] and ::, a complete set. Specializing that column by [] and by :: each leaves a row that catches everything remaining, so is false on both branches and the check passes.

Bridger’s check

The premise of T-Match is over the unguarded arms, at the scrutinee’s type. The reference checker runs it after the arms have been checked, so that inference variables in the scrutinee’s type are solved by then.

A guarded arm contributes no row, since its guard may be false. This function is rejected, although one guard or the other holds for every integer:

fn m(o: Option<Int>) -> Int = match o {
    Some(x) if x > 0 => x,
    Some(x) if x <= 0 => 0,
    None => 0,
};

Deciding whether two guards together cover every value would mean reasoning about arbitrary functions of integers, and no algorithm can do that in general. A final Some(x) => 0 arm settles it, with the guards above it.

The generic case needs no extra machinery. Option<Bool> has the signature None and Some at Bool, so the argument column has the signature of Bool:

fn f(o: Option<Bool>) -> Int =
    match o { Some(true) => 1, Some(false) => 2, None => 0 };

These arms are exhaustive. Inside a generic function over Option<T>, though, the type parameter T has no known constructors, so it has no signature to complete and only a wildcard or variable can cover the argument of Some.

With the premise in place, Soundness, informally gains an entry. A checked program cannot reach NonExhaustiveMatch: every value of the scrutinee’s type fits an unguarded arm, so a failed guard only sends the value on to a later arm. The variant stays in RuntimeError for the untyped path, as TypeError does.

Usefulness can also answer the opposite question, whether an arm can ever run. Arm is reachable exactly when holds, with the guarded arms again left out of . Bridger’s checker does not make that test: this function is accepted, and its last two arms never run.

fn f(o: Option<Int>) -> Int = match o {
    Some(x) => x,
    None => 0,
    Some(1) => 99,
    _ => 5,
};

Building it

The check belongs to the Match arm of check_expr, and it reports TyError::NonExhaustiveMatch with the span of the match. It splits into three parts, each following a definition above: a pass that reduces a pattern to wildcards, constructors, and alternatives; a function from a type to its signature, using the declarations and substituting the type’s arguments, as T-Con does; and itself, with and as helpers. keeps a list of column types alongside the rows, one per column, updated as replaces a column by its constructor’s arguments. A literal of an unbounded type needs a constructor representation too, with no argument types.

The design space

Error or warning

Rust, Swift, and Elm reject a non-exhaustive match, and Bridger does the same, so a checked program cannot reach the gap. OCaml compiles one with warning 8, which is on by default but not fatal. GHC reports it only when asked, through -Wincomplete-patterns, and Scala warns on a match over a sealed type. A warning leaves room for programs whose author knows that some case cannot occur, but a program that reaches the gap anyway fails at run time.

Languages without the check

Python’s match statement does nothing when no case applies, and exhaustiveness is left to external type checkers. TypeScript has no exhaustiveness rule for its switch, but a programmer can get one by assigning the scrutinee to a variable of type never in the default branch, since after every alternative has been handled no value remains. The TypeScript handbook shows the idiom, and Python’s typing.assert_never gives static checkers the same signal.

What a wildcard hides

A catch-all is exhaustive by definition. This simplify has one, and it passes after Neg is added, with no sign that Neg was overlooked:

fn simplify(e: Arith) -> Arith = match e {
    Add(Num(0), r) => simplify(r),
    Add(l, r) => Add(simplify(l), simplify(r)),
    Mul(l, r) => Mul(simplify(l), simplify(r)),
    other => other,
};

simplify(Neg(Add(Num(0), Num(5)))) returns its argument unchanged. A wildcard makes the check pass for every constructor added later, including those where the arm’s behaviour is wrong. Writing each constructor out loses that convenience but keeps the check meaningful. OCaml’s warning 4 reports such fragile matches, though it is off by default, and Rust’s Clippy has an optional lint against wildcards over enums.

Open and closed types

The check assumes that the signature is complete and known. A library that may add a variant later can’t promise that to its users. A Rust library can mark an enum #[non_exhaustive], which requires every client outside the library to write a wildcard. Swift’s @unknown default matches only cases added in the future, and omitting one over such an enum is a warning. Java’s switch over a sealed hierarchy is checked at compile time, but JEP 441 explains the remaining gap: “Because of separate compilation, it is possible for a novel implementation of the interface I to show up at runtime, so the compiler will in this case insert a synthetic default clause that throws.”

The tension extends beyond matching. Adding a constructor to Arith touches every function over it, whereas adding a function touches nothing else. In a class hierarchy the costs are reversed. Wadler named this the Expression Problem: “The goal is to define a datatype by cases, where one can add new cases to the datatype and new functions over the datatype, without recompiling existing code, and while retaining static type safety (e.g., no casts).” Part IX takes up the other side.

Reporting what is missing

Bridger’s error points at the match. Compilers such as rustc and OCaml go further and print an example of a missing value, which the recursion can build: a complete-signature step records the constructor it followed, and a default step records a constructor missing from the column.

Guards and cost

GHC analyses guards where Bridger drops them. “Lower Your Guards” (2020) reduces patterns and guards to a small core language for that purpose, and it handles common cases while stating that “coverage checking for guards is undecidable in general.”

Without guards the problem is decidable, but it can be expensive. Maranget’s paper reports that deciding usefulness is NP-complete, citing Sekar, Ramesh, and Ramakrishnan, and rustc’s documentation notes that a SAT problem can be encoded as an exhaustiveness problem. The recursion on U can take exponential time on such inputs.

Further reading

The algorithm: Maranget’s “Warnings for Pattern Matching” (2007, published version) defines usefulness, proves its correctness, and extends it to lazy languages. This chapter borrows its notation.

In a production compiler: The documentation comment at the top of rustc’s usefulness.rs explains in prose how Rust’s check extends the matrix approach and how it reports missing values.

Guards and strictness: “Lower Your Guards” (2020) desugars Haskell’s patterns and guards into guard trees built from three constructs, and it accounts for laziness.

Concept checks

For Option<Bool> with arms Some(true) and _, give U(P, _), and then give it with _ removed.

With _, the first column’s heads are just Some, which is incomplete, so keeps the _ row, and on a row with no columns is false: exhaustive. Without _, is the one row Some(true), the heads are incomplete, is empty, and on no rows is true. The path says that a constructor other than Some is missing, which is None.

Are the arms (true, _), (_, false), (false, true) exhaustive over (Bool, Bool)? Trace it, and say which arm is the last one needed.

They are. The first column’s heads are complete. For true, the rows _ and false remain: from (true, _) and (_, false). The heads in that column are just false, so keeps the _ row, and with no columns left is false. For false, the rows are false and true, which is complete, and specializing each leaves a row with no columns, so is false. Every arm is needed: only the first covers (true, true), only the second covers (false, false), and only the third covers (false, true).

The check says a match over Int needs a wildcard even if the arms cover every value of a smaller range. What would a language need to do better, and what is the cost?

It would need to know the set of integers more precisely than as a type. It could add integer range patterns and treat a list of non-overlapping ranges as a signature, as Rust does for its bounded integer types, or it could add refinement types that restrict an integer’s values. Each adds a theory of integers to the checker. Bridger’s check stays structural, relying on constructors alone.

The wildcard case of splits only when the rows mention every constructor of the column's type. What would happen if it always split over the whole signature?

On a recursive type, each :: would generate a new [T] column to split, and the recursion would never end. Splitting only when every constructor appears in the rows means that the depth reached is bounded by the patterns. The otherwise line asks about the other constructors collectively, since no row can tell them apart.

An enum is published with three variants, and clients match it exhaustively. A new version adds a fourth. Compare what happens under Bridger's rule and under OCaml's, and what a library author might want instead.

Under Bridger’s rule, every client fails to compile at each match until it handles the new variant, which finds each site to update and breaks every client of the library. Under OCaml’s warning, the clients compile, and a client that receives the variant fails at run time. A library author who plans for this can mark the type as open, as #[non_exhaustive] does in Rust, so that clients must write a wildcard from the start and adding a variant is not a breaking change.