Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1e95196

Browse files
Explain the important concepts of exhaustiveness checking
1 parent 904bb5a commit 1e95196

File tree

1 file changed

+131
-1
lines changed

1 file changed

+131
-1
lines changed

‎src/pat-exhaustive-checking.md

Lines changed: 131 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ are exhaustive.
77
## Pattern usefulness
88

99
The central question that usefulness checking answers is:
10-
"in this match expression, is that branch reachable?".
10+
"in this match expression, is that branch redundant?".
1111
More precisely, it boils down to computing whether,
1212
given a list of patterns we have already seen,
1313
a given new pattern might match any new value.
@@ -84,5 +84,135 @@ Exhaustiveness checking is implemented in [`check_match`].
8484
The core of the algorithm is in [`usefulness`].
8585
That file contains a detailed description of the algorithm.
8686

87+
## Important concepts
88+
89+
### Constructors and fields
90+
91+
In the value `Pair(Some(0), true)`, `Pair` is called the constructor of the value, and `Some(0)` and
92+
`true` are its fields. Every matcheable value can be decomposed in this way. Examples of
93+
constructors are: `Some`, `None`, `(,)` (the 2-tuple constructor), `Foo {..}` (the constructor for
94+
a struct `Foo`), and `2` (the constructor for the number `2`).
95+
96+
Each constructor takes a fixed number of fields; this is called its arity. `Pair` and `(,)` have
97+
arity 2, `Some` has arity 1, `None` and `42` have arity 0. Each type has a known set of
98+
constructors. Some types have many constructors (like `u64`) or even an infinitely many (like `&str`
99+
and `&[T]`).
100+
101+
Patterns are similar: `Pair(Some(_), _)` has constructor `Pair` and two fields. The difference is
102+
that we get some extra pattern-only constructors, namely: the wildcard `_`, variable bindings,
103+
integer ranges like `0..=10`, and variable-length slices like `[_, .., _]`. We treat or-patterns
104+
separately.
105+
106+
Now to check if a value `v` matches a pattern `p`, we check if `v`'s constructor matches `p`'s
107+
constructor, then recursively compare their fields if necessary. A few representative examples:
108+
109+
- `matches!(v, _) := true`
110+
- `matches!((v0, v1), (p0, p1)) := matches!(v0, p0) && matches!(v1, p1)`
111+
- `matches!(Foo { a: v0, b: v1 }, Foo { a: p0, b: p1 }) := matches!(v0, p0) && matches!(v1, p1)`
112+
- `matches!(Ok(v0), Ok(p0)) := matches!(v0, p0)`
113+
- `matches!(Ok(v0), Err(p0)) := false` (incompatible variants)
114+
- `matches!(v, 1..=100) := matches!(v, 1) || ... || matches!(v, 100)`
115+
- `matches!([v0], [p0, .., p1]) := false` (incompatible lengths)
116+
- `matches!([v0, v1, v2], [p0, .., p1]) := matches!(v0, p0) && matches!(v2, p1)`
117+
118+
This concept is absolutely central to pattern analysis. The [`deconstruct_pat`] module provides
119+
functions to extract, list and manipulate constructors. This is a useful enough concept that
120+
variations of it can be found in other places of the compiler, like in the MIR-lowering of a match
121+
expression and in some clippy lints.
122+
123+
### Constructor grouping and splitting
124+
125+
The pattern-only constructors (`_`, ranges and variable-length slices) each stand for a set of
126+
normal constructors, e.g. `_: Option<T>` stands for the set {`None`, `Some`} and `[_, .., _]` stands
127+
for the infinite set {`[,]`, `[,,]`, `[,,,]`, ...} of the slice constructors of arity >= 2.
128+
129+
In order to manage these constructors, we keep them as grouped as possible. For example:
130+
131+
```rust
132+
match (0, false) {
133+
(0 ..=100, true) => {}
134+
(50..=150, false) => {}
135+
(0 ..=200, _) => {}
136+
}
137+
```
138+
139+
In this example, all of `0`, `1`, .., `49` match the same arms, and thus can be treated as a group.
140+
In fact, in this match, the only ranges we need to consider are: `0..50`, `50..=100`,
141+
`101..=150`,`151..=200` and `201..`. Similarly:
142+
143+
```rust
144+
enum Direction { North, South, East, West }
145+
# let wind = (Direction::North, 0u8);
146+
match wind {
147+
(Direction::North, 50..) => {}
148+
(_, _) => {}
149+
}
150+
```
151+
152+
Here we can treat all the non-`North` constructors as a group, giving us only two cases to handle:
153+
`North`, and everything else.
154+
155+
This is called "constructor splitting" and is crucial to having exhaustiveness run in reasonable
156+
time.
157+
158+
### Usefulness vs reachability in the presence of empty types
159+
160+
This is likely the subtlest aspect of exhaustiveness. To be fully precise, a match doesn't operate
161+
on a value, it operates on a place. In certain unsafe circumstances, it is possible for a place to
162+
not contain valid data for its type. This has subtle consequences for empty types. Take the
163+
following:
164+
165+
```rust
166+
enum Void {}
167+
let x: u8 = 0;
168+
let ptr: *const Void = &x as *const u8 as *const Void;
169+
unsafe {
170+
match *ptr {
171+
_ => println!("Reachable!"),
172+
}
173+
}
174+
```
175+
176+
In this example, `ptr` is a valid pointer pointing to a place with invalid data. The `_` pattern
177+
does not look at the contents of the place `*ptr`, so this code is ok and the arm is taken. In other
178+
words, despite the place we are inspecting being of type `Void`, there is a reachable arm. If the
179+
arm had a binding however:
180+
181+
```rust
182+
# #[derive(Copy, Clone)]
183+
# enum Void {}
184+
# let x: u8 = 0;
185+
# let ptr: *const Void = &x as *const u8 as *const Void;
186+
# unsafe {
187+
match *ptr {
188+
_a => println!("Unreachable!"),
189+
}
190+
# }
191+
```
192+
193+
Here the binding loads the value of type `Void` from the `*ptr` place. In this example, this causes
194+
UB since the data is not valid. In the general case, this asserts validity of the data at `*ptr`.
195+
Either way, this arm will never be taken.
196+
197+
Finally, let's consider the empty match `match *ptr {}`. If we consider this exhaustive, then
198+
having invalid data at `*ptr` is invalid. In other words, the empty match is semantically
199+
equivalent to the `_a => ...` match. In the interest of explicitness, we prefer the case with an
200+
arm, hence we won't tell the user to remove the `_a` arm. In other words, the `_a` arm is
201+
unreachable yet not redundant. This is why we lint on redundant arms rather than unreachable
202+
arms, despite the fact that the lint says "unreachable".
203+
204+
These considerations only affects certain places, namely those that can contain non-valid data
205+
without UB. These are: pointer dereferences, reference dereferences, and union field accesses. We
206+
track during exhaustiveness checking whether a given place is known to contain valid data.
207+
208+
Having said all that, the current implementation of exhaustiveness checking does not follow the
209+
above considerations. On stable, empty types are for the most part treated as non-empty. The
210+
[`exhaustive_patterns`] feature errs on the other end: it allows omitting arms that could be
211+
reachable in unsafe situations. The [`never_patterns`] experimental feature aims to fix this and
212+
permit the correct behavior of empty types in patterns.
213+
87214
[`check_match`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_mir_build/thir/pattern/check_match/index.html
88215
[`usefulness`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_mir_build/thir/pattern/usefulness/index.html
216+
[`deconstruct_pat`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_mir_build/thir/pattern/deconstruct_pat/index.html
217+
[`never_patterns`]: https://github.com/rust-lang/rust/issues/118155
218+
[`exhaustive_patterns`]: https://github.com/rust-lang/rust/issues/51085

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /