Conceptcore
Exhaustive matching
Also called exhaustiveness checking, exhaustiveness check, exhaustive switch, exhaustive pattern matching, non-exhaustive patterns, complete case analysis, totality check.
A match is exhaustive when each possible value matches one of its arms. Some compilers check this, so a missing case, such as a new variant of an enum, becomes a compile-time error.
- Applies to
- core-languages
Idea
A match is exhaustive when each value that can reach it matches at least one arm. A match that is not exhaustive has a gap: some value finds no arm. Rust makes the check a rule of the language: "The arms’ patterns must cover all possibilities"1. "Matches in Rust are exhaustive: We must exhaust every last possibility in order for the code to be valid"1.
The check is most useful for a type with a fixed list of cases, such as an enum. This match names each variant, so it compiles:
enum Shape {
Circle(f64),
Square(f64),
Triangle(f64, f64),
}
fn area(shape: &Shape) -> f64 {
match shape {
Shape::Circle(r) => 3.0 * r * r,
Shape::Square(s) => s * s,
Shape::Triangle(b, h) => b * h / 2.0,
}
}
fn main() {
let shapes = [Shape::Circle(1.0), Shape::Square(2.0), Shape::Triangle(3.0, 4.0)];
for shape in &shapes {
println!("{}", area(shape));
}
}
3
4
6
If someone adds a variant Hexagon to Shape, this match no longer compiles, and the error names the missing pattern, because the compiler "even knows which pattern we forgot"1. So the compiler finds each place in the program that must handle the new case.
How it works
- The cases of a type. To check a match, the compiler must know each case of the type. An enum, a
bool, a sealed type and a tuple of these have a finite list of cases. An integer or a string has too many cases to list, so a match on it needs a catch-all arm. The Rust Book shows a match on au8that "compiles, even though we haven’t listed all the possible values a u8 can have, because the last pattern will match all values not specifically listed"1. - Two anomalies. Maranget names the two checks that a compiler does on a match. "This style of reasoning calls for two basic checks: Are all cases considered? And, is any case subsumed by some others?"2 The first finds a non-exhaustive match. The second finds a useless arm, which no value can reach. His paper gives "a simple algorithm to detect them"2, which the Objective Caml compiler uses2.
- The error names the gap. The Rust compiler reports the patterns that no arm covers. For a match on an
Option<i32>without aNonearm, the error is "non-exhaustive patterns:Nonenot covered"1. - Guards do not count. The check looks at patterns only. A guard is an arbitrary expression, so the compiler treats a guarded arm as an arm that can fail. The Rust Book states that "the compiler doesn’t try to check for exhaustiveness when match guard expressions are involved"15. Match guards shows the error that this gives.
- Statements and expressions. A match that gives a value must give a value for each input. JEP 441 states: "A switch expression requires that all possible values of the selector expression be handled in the switch block; in other words, it must be exhaustive"3. Kotlin makes the same split: a
whenexpression must be exhaustive, but "If you use when as a statement, you don't need to cover all possible cases"5.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Idiom | |
| Java | Native | |
| C | Idiom | |
| C# | Native | |
| JavaScript | Absent | |
| TypeScript | Idiom | |
| Go | Absent | |
| Rust | Native | |
| Kotlin | Native | A when expression must be exhaustive, and with a sealed class or an enum the compiler checks that each subclass or entry has a branch, so no else branch is needed. A when statement need not be exhaustive. No example file exists because kotlinc is not installed. |
| SQL | Absent | Nothing checks that the WHEN clauses of a CASE expression cover each value. With no ELSE clause, a value that matches no WHEN gives NULL. No example file exists. |
| Bash | Absent | |
| PowerShell | Absent | Switch has no static check. If no condition matches and there is no default, no action runs. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no match statement. |
| CSS | Does not apply | CSS has no match statement. |
| Regular expressions | Does not apply | A regular expression has no match arms to cover. |
| Language | What checks the match | A gap gives |
|---|---|---|
| Rust | the compiler, for each match1 |
a compile-time error1 |
| Java | the compiler, for each switch expression and each pattern switch3 | a compile-time error |
| Kotlin | the compiler, for each when expression56 |
a compile-time error |
| C# | the compiler, for each switch expression4 | a warning, and an exception at run time4 |
| TypeScript | the type checker, with an assignment to never8 |
a compile-time error from that assignment |
| Python | a static type checker, with assert_never10 |
no error from the interpreter; no case runs9 |
| C, C++ | GCC with -Wswitch, for a switch on an enum11 |
a warning |
| Go | nothing | no case runs12 |
| JavaScript, Bash | nothing | no case runs13 |
- Rust. Each
matchmust be exhaustive. The Rust Book shows the error for a missingNone, and adds: "Rust knows that we didn’t cover every possible case"1. - Java. A switch expression must be exhaustive3. JEP 441 extends the rule to switch statements with patterns, and one of its goals is "requiring that pattern switch statements cover all possible input values"3. Sealed classes give the compiler the list of subclasses: JEP 409 has the goal of "providing a foundation for the exhaustive analysis of patterns"7.
- Kotlin. "Covering all possible cases is called being exhaustive"5, and "If you use when as an expression, you must cover all possible cases"5. With a sealed class, "The when expression, used with a sealed class, allows the Kotlin compiler to check exhaustively that all possible cases are covered"6.
- C#. "In most cases, the compiler generates a warning if a switch expression doesn't handle all possible input values"4. At run time, "If none of a switch expression's patterns matches an input value, the runtime throws an exception"4.
- TypeScript. The language does not check a switch. But "The never type is assignable to every type; however, no type is assignable to never (except never itself)"8. So in the
defaultclause of a switch on a union, an assignment to anevervariable compiles only when each member of the union has a case. The handbook calls this "exhaustive checking in a switch statement"8. - Python. "If no case matches, none of the branches is executed"9.
typing.assert_neverasks "a static type checker to confirm that a line of code is unreachable"10. The check is done by the type checker, not by the interpreter. - C and C++. The languages have no check. GCC has
-Wswitch, which warns "whenever a switch statement has an index of enumerated type and lacks a case for one or more of the named codes of that enumeration"11. "This warning is enabled by -Wall"11. - Go and Bash. Nothing checks the cases. In Go, "If no case matches and there is a "default" case, its statements are executed"12; with no
default, the switch does nothing. In Bash, "The return status is zero if no pattern matches"13.
from enum import Enum
from typing import assert_never
class Light(Enum):
RED = "red"
YELLOW = "yellow"
GREEN = "green"
def action(light: Light) -> str:
match light:
case Light.RED:
return "stop"
case Light.YELLOW:
return "slow down"
case Light.GREEN:
return "go"
case _ as unreachable:
assert_never(unreachable)
for light in Light:
print(f"{light.value}: {action(light)}")
red: stop
yellow: slow down
green: go
- Verdict: stdlib. The interpreter does not check that a
matchis exhaustive. If no case matches, no case runs.typing.assert_neverasks a static type checker to confirm that the last case is unreachable, and at run time it throws an exception if the case runs.
#include <iostream>
#include <string_view>
enum class Light { Red, Yellow, Green };
static std::string_view action(Light light) {
// No default: -Wswitch (in -Wall) warns if an enumerator has no case.
switch (light) {
case Light::Red:
return "stop";
case Light::Yellow:
return "slow down";
case Light::Green:
return "go";
}
return "unknown";
}
int main() {
const char *names[] = {"red", "yellow", "green"};
const Light lights[] = {Light::Red, Light::Yellow, Light::Green};
for (int i = 0; i < 3; i++) {
std::cout << names[i] << ": " << action(lights[i]) << "\n";
}
}
red: stop
yellow: slow down
green: go
- Verdict: idiom. As in C, the language does not require a switch to be exhaustive, and GCC warns with
-Wswitchwhen an enumerator has no case and there is nodefault. Thereturnafter the switch handles a value that is not an enumerator.
public class Main {
enum Light { RED, YELLOW, GREEN }
static String action(Light light) {
// A switch expression must be exhaustive. No default is needed here.
return switch (light) {
case RED -> "stop";
case YELLOW -> "slow down";
case GREEN -> "go";
};
}
public static void main(String[] args) {
for (Light light : Light.values()) {
System.out.println(light.name().toLowerCase() + ": " + action(light));
}
}
}
red: stop
yellow: slow down
green: go
- Verdict: native. A switch expression must be exhaustive, and a switch on an enum is exhaustive when it names each constant. The switch has no
default, so a new constant gives a compile-time error. If a new constant reaches a switch that was not compiled again, the default that the compiler added throws an exception.
#include <stdio.h>
enum light { RED, YELLOW, GREEN };
static const char *action(enum light light) {
/* No default: -Wswitch (in -Wall) warns if an enumerator has no case. */
switch (light) {
case RED:
return "stop";
case YELLOW:
return "slow down";
case GREEN:
return "go";
}
return "unknown";
}
int main(void) {
const char *names[] = {"red", "yellow", "green"};
for (int i = RED; i <= GREEN; i++) {
printf("%s: %s\n", names[i], action((enum light)i));
}
return 0;
}
red: stop
yellow: slow down
green: go
- Verdict: idiom. The C language does not require a switch to be exhaustive. GCC warns with
-Wswitch, which-Wallturns on, when a switch on an enum has no case for a named enumerator. Adefaultlabel turns the warning off, so the switch has nodefault. Thereturnafter the switch handles a value that is not a named enumerator.
using System;
static string Action(Light light) => light switch
{
Light.Red => "stop",
Light.Yellow => "slow down",
Light.Green => "go",
_ => throw new ArgumentOutOfRangeException(nameof(light)),
};
foreach (Light light in Enum.GetValues<Light>())
{
Console.WriteLine($"{light.ToString().ToLowerInvariant()}: {Action(light)}");
}
enum Light { Red, Yellow, Green }
red: stop
yellow: slow down
green: go
- Verdict: native. The compiler gives a warning, not an error, for a switch expression that does not cover each input, and the runtime throws an exception when no arm matches. A C# enum can hold an integer that is not a named member, such as
(Light)10, so the switch also needs the discard arm_to be exhaustive.
const Light = Object.freeze({ RED: "red", YELLOW: "yellow", GREEN: "green" });
function action(light) {
switch (light) {
case Light.RED:
return "stop";
case Light.YELLOW:
return "slow down";
case Light.GREEN:
return "go";
default:
throw new Error(`unknown light: ${light}`);
}
}
for (const light of Object.values(Light)) {
console.log(`${light}: ${action(light)}`);
}
red: stop
yellow: slow down
green: go
- Verdict: absent. JavaScript has no static types, so nothing checks that a switch covers each value. A
defaultclause that throws finds a missing case at run time, and only when that value comes.
type Light = "red" | "yellow" | "green";
function action(light: Light): string {
switch (light) {
case "red":
return "stop";
case "yellow":
return "slow down";
case "green":
return "go";
default: {
// If a case is missing, light is not never here, and tsc reports an error.
const unreachable: never = light;
throw new Error(`unknown light: ${unreachable}`);
}
}
}
for (const light of ["red", "yellow", "green"] as const) {
console.log(`${light}: ${action(light)}`);
}
red: stop
yellow: slow down
green: go
- Verdict: idiom. TypeScript does not require a switch to be exhaustive. Narrowing makes the type of
lightin thedefaultclauseneverwhen each member of the union has a case. The assignment to anevervariable fails to compile when a member is missing, so it works as an exhaustiveness check.
package main
import "fmt"
type Light int
const (
Red Light = iota
Yellow
Green
)
func action(l Light) string {
switch l {
case Red:
return "stop"
case Yellow:
return "slow down"
case Green:
return "go"
default:
panic(fmt.Sprintf("unknown light %d", l))
}
}
func main() {
names := []string{"red", "yellow", "green"}
for l := Red; l <= Green; l++ {
fmt.Printf("%s: %s\n", names[l], action(l))
}
}
red: stop
yellow: slow down
green: go
- Verdict: absent. Go has no enum types and no exhaustiveness check. If no case matches and there is no
default, the switch does nothing. Adefaultthat panics finds a missing case at run time.
#[derive(Debug, Clone, Copy)]
enum Light {
Red,
Yellow,
Green,
}
fn action(light: Light) -> &'static str {
// No wildcard arm: a new variant makes this match fail to compile.
match light {
Light::Red => "stop",
Light::Yellow => "slow down",
Light::Green => "go",
}
}
fn main() {
for light in [Light::Red, Light::Yellow, Light::Green] {
println!("{}: {}", format!("{light:?}").to_lowercase(), action(light));
}
}
red: stop
yellow: slow down
green: go
- Verdict: native. A
matchmust cover each value of its type, or the program does not compile. The match lists the three variants and has no wildcard arm, so the compiler reports each match that a new variant makes incomplete.
action() {
case $1 in
red) echo "stop" ;;
yellow) echo "slow down" ;;
green) echo "go" ;;
*)
echo "unknown light: $1" >&2
return 1
;;
esac
}
for light in red yellow green; do
echo "$light: $(action "$light")"
done
red: stop
yellow: slow down
green: go
- Verdict: absent. A
casecommand matches strings, and nothing checks that it covers each value. If no pattern matches, no command runs, and the return status is zero. A last*)clause that fails finds a missing case at run time.
Variations and related ideas
- Sealed types and closed hierarchies. An enum gives a list of values. A sealed type gives a list of subclasses, so a match on the type can be exhaustive without a wildcard. Java and Kotlin both use sealed types for this76. Pattern matching shows matches on such types.
- Useless arms. The second check of Maranget finds an arm that no value can reach2. Java makes some of these an error: a label that is dominated by an earlier label does not compile3.
- Types that can grow. A library can mark an enum as open to new variants. In Rust, "The non_exhaustive attribute indicates that a type or variant may have more fields or variants added in the future"14. Outside the crate that defines it, "When pattern matching on a non-exhaustive enum, matching on a variant does not contribute towards the exhaustiveness of the arms"14, so each match needs a wildcard arm.
- Values outside the named cases. In C, C++ and C#, an enum variable can hold an integer that is not a named member. The C# reference shows a discard arm "to handle any integer value that doesn't have the corresponding member of the Direction enumeration (for example, (Direction)10)"4.
Pitfalls
A wildcard arm that hides a new case
A wildcard arm makes each match exhaustive, so the compiler can no longer find a missing case. Here Blue was added to the enum after the match was written. The program compiles, and blue gets the color of the wildcard arm:
This code runs but gives a wrong answer on purpose.
enum Color {
Red,
Green,
Blue,
}
fn hex(c: &Color) -> &'static str {
match c {
Color::Red => "#ff0000",
Color::Green => "#00ff00",
_ => "#000000",
}
}
fn main() {
for c in [Color::Red, Color::Green, Color::Blue] {
print!("{} ", hex(&c));
}
println!();
}
#ff0000 #00ff00 #000000
JEP 441 states the problem: "If we have an explicit match-all clause then we will only discover the new constant value if it shows up at run time"3, and "A match-all clause risks sweeping exhaustiveness errors under the rug"3. Name each variant, and use a wildcard only for a type with too many values to list. In C, the same problem affects -Wswitch: "The presence of a default label prevents this warning"11. -Wswitch-enum warns "about an omitted enumeration code even if there is a default label"11.
A match that is not exhaustive
Without the wildcard, the match must name each variant. A match that misses one does not compile:
This code does not compile, on purpose.
enum Color {
Red,
Green,
Blue,
}
fn hex(c: &Color) -> &'static str {
match c {
Color::Red => "#ff0000",
Color::Green => "#00ff00",
}
}
fn main() {
println!("{}", hex(&Color::Blue));
}
The fix is the arm Color::Blue => "#0000ff". This error is the point of the check: it comes at compile time, in place of a wrong color at run time.
A gap that nothing reports
In a language without the check, a missing case does nothing. This Python function returns None for a value that it does not handle, and no error appears:
This code runs but gives a wrong answer on purpose.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
def hex_code(c):
match c:
case Color.RED:
return "#ff0000"
case Color.GREEN:
return "#00ff00"
print([hex_code(c) for c in Color])
['#ff0000', '#00ff00', None]
Add a last case that fails loudly, such as case _ as unreachable: assert_never(unreachable). A static type checker then reports the gap, and the interpreter raises an exception if the case runs10.
Exhaustive at compile time, not at run time
A check at compile time sees the cases that exist at compile time. In Java, a new enum constant can reach a switch in a class that was not compiled again. So "if an exhaustive enum switch does not have a match-all clause then the compiler will synthesize a default clause that throws an exception"3. In C#, the runtime throws an exception when no arm matches4.
Cost
- The check runs in the compiler. An exhaustiveness check costs nothing at run time. In the compiler, the check can be slow: Maranget notes that the related useful clause problem "is NP-complete", and that his algorithm "can exhibit exponential time behavior" in the size of the match2. He adds safeguards, because the input to a compiler "consists of programs written by human beings attempting to solve specific problems, not to break the compiler"2.
- A synthesized default. Java adds a default clause that throws to an exhaustive enum switch without a match-all clause3, so a switch has one more branch. C# throws an exception when no arm matches4.
- Edits in many places. Adding a case to a type makes each match on the type fail to compile until it handles the case. This is the purpose of the check, but it is work for each new case.
History
- 2007. Luc Maranget, in "Warnings for pattern matching", examined "the ML pattern-matching anomalies of useless clauses and non-exhaustive matches"2. He gave an algorithm for both, integrated it "in the Objective Caml compiler", and showed that "the same algorithm is also usable in a non-strict language such as Haskell"2.
- Java 17. JEP 409 made sealed classes standard, with the goal of exhaustive analysis of patterns7.
- Python 3.11. Python added
typing.assert_never10. - Java 21. JEP 441 required pattern switch statements to be exhaustive3.
References
- The match Control Flow Construct, The Rust Programming Language, Matches Are Exhaustive
- Luc Maranget, Warnings for pattern matching, Journal of Functional Programming 17(3), 2007, pp. 387-421, Abstract; 1 Introduction
- JEP 441: Pattern Matching for switch, Goals; Exhaustiveness of switch expressions and statements; the header (Release 21)
- switch expression, C# language reference, Nonexhaustive switch expressions; the example with the Direction enumeration
- Conditions and loops, Kotlin documentation, When expressions and statements
- Sealed classes and interfaces, Kotlin documentation, Use sealed classes with when expression
- JEP 409: Sealed Classes, Goals; the header (Release 17)
- Narrowing, TypeScript Handbook, The never type; Exhaustiveness checking
- More Control Flow Tools, The Python Tutorial, 4.7 match Statements
- typing, The Python Standard Library, assert_never
- Options to Request or Suppress Warnings, GCC documentation, -Wswitch; -Wswitch-enum
- The Go Programming Language Specification, Expression switches
- Conditional Constructs, Bash Reference Manual, case
- The Rust Reference, Type system attributes, The non_exhaustive attribute
- Pattern Syntax, The Rust Programming Language, Adding Conditionals with Match Guards
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag ZQPDKQ Edit this page History Report an error Markdown