1 //! Note: tests specific to this file can be found in:
3 //! - `ui/pattern/usefulness`
5 //! - `ui/consts/const_in_pattern`
6 //! - `ui/rfc-2008-non-exhaustive`
7 //! - `ui/half-open-range-patterns`
8 //! - probably many others
10 //! I (Nadrieril) prefer to put new tests in `ui/pattern/usefulness` unless there's a specific
11 //! reason not to, for example if they depend on a particular feature like `or_patterns`.
15 //! This file includes the logic for exhaustiveness and reachability checking for pattern-matching.
16 //! Specifically, given a list of patterns for a type, we can tell whether:
17 //! (a) each pattern is reachable (reachability)
18 //! (b) the patterns cover every possible value for the type (exhaustiveness)
20 //! The algorithm implemented here is a modified version of the one described in [this
21 //! paper](http://moscova.inria.fr/~maranget/papers/warn/index.html). We have however generalized
22 //! it to accommodate the variety of patterns that Rust supports. We thus explain our version here,
23 //! without being as rigorous.
28 //! The core of the algorithm is the notion of "usefulness". A pattern `q` is said to be *useful*
29 //! relative to another pattern `p` of the same type if there is a value that is matched by `q` and
30 //! not matched by `p`. This generalizes to many `p`s: `q` is useful w.r.t. a list of patterns
31 //! `p_1 .. p_n` if there is a value that is matched by `q` and by none of the `p_i`. We write
32 //! `usefulness(p_1 .. p_n, q)` for a function that returns a list of such values. The aim of this
33 //! file is to compute it efficiently.
35 //! This is enough to compute reachability: a pattern in a `match` expression is reachable iff it
36 //! is useful w.r.t. the patterns above it:
40 //! None => ..., // reachable: `None` is matched by this but not the branch above
41 //! Some(0) => ..., // unreachable: all the values this matches are already matched by
42 //! // `Some(_)` above
46 //! This is also enough to compute exhaustiveness: a match is exhaustive iff the wildcard `_`
47 //! pattern is _not_ useful w.r.t. the patterns in the match. The values returned by `usefulness`
48 //! are used to tell the user which values are missing.
53 //! // not exhaustive: `_` is useful because it matches `Some(1)`
57 //! The entrypoint of this file is the [`compute_match_usefulness`] function, which computes
58 //! reachability for each match branch and exhaustiveness for the whole match.
61 //! # Constructors and fields
63 //! Note: we will often abbreviate "constructor" as "ctor".
65 //! The idea that powers everything that is done in this file is the following: a (matcheable)
66 //! value is made from a constructor applied to a number of subvalues. Examples of constructors are
67 //! `Some`, `None`, `(,)` (the 2-tuple constructor), `Foo {..}` (the constructor for a struct
68 //! `Foo`), and `2` (the constructor for the number `2`). This is natural when we think of
69 //! pattern-matching, and this is the basis for what follows.
71 //! Some of the ctors listed above might feel weird: `None` and `2` don't take any arguments.
72 //! That's ok: those are ctors that take a list of 0 arguments; they are the simplest case of
73 //! ctors. We treat `2` as a ctor because `u64` and other number types behave exactly like a huge
74 //! `enum`, with one variant for each number. This allows us to see any matcheable value as made up
75 //! from a tree of ctors, each having a set number of children. For example: `Foo { bar: None,
76 //! baz: Ok(0) }` is made from 4 different ctors, namely `Foo{..}`, `None`, `Ok` and `0`.
78 //! This idea can be extended to patterns: they are also made from constructors applied to fields.
79 //! A pattern for a given type is allowed to use all the ctors for values of that type (which we
80 //! call "value constructors"), but there are also pattern-only ctors. The most important one is
81 //! the wildcard (`_`), and the others are integer ranges (`0..=10`), variable-length slices (`[x,
82 //! ..]`), and or-patterns (`Ok(0) | Err(_)`). Examples of valid patterns are `42`, `Some(_)`, `Foo
83 //! { bar: Some(0) | None, baz: _ }`. Note that a binder in a pattern (e.g. `Some(x)`) matches the
84 //! same values as a wildcard (e.g. `Some(_)`), so we treat both as wildcards.
86 //! From this deconstruction we can compute whether a given value matches a given pattern; we
87 //! simply look at ctors one at a time. Given a pattern `p` and a value `v`, we want to compute
88 //! `matches!(v, p)`. It's mostly straightforward: we compare the head ctors and when they match
89 //! we compare their fields recursively. A few representative examples:
91 //! - `matches!(v, _) := true`
92 //! - `matches!((v0, v1), (p0, p1)) := matches!(v0, p0) && matches!(v1, p1)`
93 //! - `matches!(Foo { bar: v0, baz: v1 }, Foo { bar: p0, baz: p1 }) := matches!(v0, p0) && matches!(v1, p1)`
94 //! - `matches!(Ok(v0), Ok(p0)) := matches!(v0, p0)`
95 //! - `matches!(Ok(v0), Err(p0)) := false` (incompatible variants)
96 //! - `matches!(v, 1..=100) := matches!(v, 1) || ... || matches!(v, 100)`
97 //! - `matches!([v0], [p0, .., p1]) := false` (incompatible lengths)
98 //! - `matches!([v0, v1, v2], [p0, .., p1]) := matches!(v0, p0) && matches!(v2, p1)`
99 //! - `matches!(v, p0 | p1) := matches!(v, p0) || matches!(v, p1)`
101 //! Constructors, fields and relevant operations are defined in the [`super::deconstruct_pat`] module.
103 //! Note: this constructors/fields distinction may not straightforwardly apply to every Rust type.
104 //! For example a value of type `Rc<u64>` can't be deconstructed that way, and `&str` has an
105 //! infinitude of constructors. There are also subtleties with visibility of fields and
106 //! uninhabitedness and various other things. The constructors idea can be extended to handle most
107 //! of these subtleties though; caveats are documented where relevant throughout the code.
109 //! Whether constructors cover each other is computed by [`Constructor::is_covered_by`].
114 //! Recall that we wish to compute `usefulness(p_1 .. p_n, q)`: given a list of patterns `p_1 ..
115 //! p_n` and a pattern `q`, all of the same type, we want to find a list of values (called
116 //! "witnesses") that are matched by `q` and by none of the `p_i`. We obviously don't just
117 //! enumerate all possible values. From the discussion above we see that we can proceed
118 //! ctor-by-ctor: for each value ctor of the given type, we ask "is there a value that starts with
119 //! this constructor and matches `q` and none of the `p_i`?". As we saw above, there's a lot we can
120 //! say from knowing only the first constructor of our candidate value.
122 //! Let's take the following example:
125 //! Enum::Variant1(_) => {} // `p1`
126 //! Enum::Variant2(None, 0) => {} // `p2`
127 //! Enum::Variant2(Some(_), 0) => {} // `q`
131 //! We can easily see that if our candidate value `v` starts with `Variant1` it will not match `q`.
132 //! If `v = Variant2(v0, v1)` however, whether or not it matches `p2` and `q` will depend on `v0`
133 //! and `v1`. In fact, such a `v` will be a witness of usefulness of `q` exactly when the tuple
134 //! `(v0, v1)` is a witness of usefulness of `q'` in the following reduced match:
138 //! (None, 0) => {} // `p2'`
139 //! (Some(_), 0) => {} // `q'`
143 //! This motivates a new step in computing usefulness, that we call _specialization_.
144 //! Specialization consist of filtering a list of patterns for those that match a constructor, and
145 //! then looking into the constructor's fields. This enables usefulness to be computed recursively.
147 //! Instead of acting on a single pattern in each row, we will consider a list of patterns for each
148 //! row, and we call such a list a _pattern-stack_. The idea is that we will specialize the
149 //! leftmost pattern, which amounts to popping the constructor and pushing its fields, which feels
150 //! like a stack. We note a pattern-stack simply with `[p_1 ... p_n]`.
151 //! Here's a sequence of specializations of a list of pattern-stacks, to illustrate what's
154 //! [Enum::Variant1(_)]
155 //! [Enum::Variant2(None, 0)]
156 //! [Enum::Variant2(Some(_), 0)]
157 //! //==>> specialize with `Variant2`
160 //! //==>> specialize with `Some`
162 //! //==>> specialize with `true` (say the type was `bool`)
164 //! //==>> specialize with `0`
168 //! The function `specialize(c, p)` takes a value constructor `c` and a pattern `p`, and returns 0
169 //! or more pattern-stacks. If `c` does not match the head constructor of `p`, it returns nothing;
170 //! otherwise if returns the fields of the constructor. This only returns more than one
171 //! pattern-stack if `p` has a pattern-only constructor.
173 //! - Specializing for the wrong constructor returns nothing
175 //! `specialize(None, Some(p0)) := []`
177 //! - Specializing for the correct constructor returns a single row with the fields
179 //! `specialize(Variant1, Variant1(p0, p1, p2)) := [[p0, p1, p2]]`
181 //! `specialize(Foo{..}, Foo { bar: p0, baz: p1 }) := [[p0, p1]]`
183 //! - For or-patterns, we specialize each branch and concatenate the results
185 //! `specialize(c, p0 | p1) := specialize(c, p0) ++ specialize(c, p1)`
187 //! - We treat the other pattern constructors as if they were a large or-pattern of all the
190 //! `specialize(c, _) := specialize(c, Variant1(_) | Variant2(_, _) | ...)`
192 //! `specialize(c, 1..=100) := specialize(c, 1 | ... | 100)`
194 //! `specialize(c, [p0, .., p1]) := specialize(c, [p0, p1] | [p0, _, p1] | [p0, _, _, p1] | ...)`
196 //! - If `c` is a pattern-only constructor, `specialize` is defined on a case-by-case basis. See
197 //! the discussion about constructor splitting in [`super::deconstruct_pat`].
200 //! We then extend this function to work with pattern-stacks as input, by acting on the first
201 //! column and keeping the other columns untouched.
203 //! Specialization for the whole matrix is done in [`Matrix::specialize_constructor`]. Note that
204 //! or-patterns in the first column are expanded before being stored in the matrix. Specialization
205 //! for a single patstack is done from a combination of [`Constructor::is_covered_by`] and
206 //! [`PatStack::pop_head_constructor`]. The internals of how it's done mostly live in the
207 //! [`Fields`] struct.
210 //! # Computing usefulness
212 //! We now have all we need to compute usefulness. The inputs to usefulness are a list of
213 //! pattern-stacks `p_1 ... p_n` (one per row), and a new pattern_stack `q`. The paper and this
214 //! file calls the list of patstacks a _matrix_. They must all have the same number of columns and
215 //! the patterns in a given column must all have the same type. `usefulness` returns a (possibly
216 //! empty) list of witnesses of usefulness. These witnesses will also be pattern-stacks.
218 //! - base case: `n_columns == 0`.
219 //! Since a pattern-stack functions like a tuple of patterns, an empty one functions like the
220 //! unit type. Thus `q` is useful iff there are no rows above it, i.e. if `n == 0`.
222 //! - inductive case: `n_columns > 0`.
223 //! We need a way to list the constructors we want to try. We will be more clever in the next
224 //! section but for now assume we list all value constructors for the type of the first column.
226 //! - for each such ctor `c`:
228 //! - for each `q'` returned by `specialize(c, q)`:
230 //! - we compute `usefulness(specialize(c, p_1) ... specialize(c, p_n), q')`
232 //! - for each witness found, we revert specialization by pushing the constructor `c` on top.
234 //! - We return the concatenation of all the witnesses found, if any.
238 //! [Some(true)] // p_1
241 //! //==>> try `None`: `specialize(None, q)` returns nothing
242 //! //==>> try `Some`: `specialize(Some, q)` returns a single row
245 //! //==>> try `true`: `specialize(true, q')` returns a single row
248 //! //==>> base case; `n != 0` so `q''` is not useful.
249 //! //==>> go back up a step
252 //! //==>> try `false`: `specialize(false, q')` returns a single row
254 //! //==>> base case; `n == 0` so `q''` is useful. We return the single witness `[]`
257 //! //==>> undo the specialization with `false`
260 //! //==>> undo the specialization with `Some`
263 //! //==>> we have tried all the constructors. The output is the single witness `[Some(false)]`.
266 //! This computation is done in [`is_useful`]. In practice we don't care about the list of
267 //! witnesses when computing reachability; we only need to know whether any exist. We do keep the
268 //! witnesses when computing exhaustiveness to report them to the user.
271 //! # Making usefulness tractable: constructor splitting
273 //! We're missing one last detail: which constructors do we list? Naively listing all value
274 //! constructors cannot work for types like `u64` or `&str`, so we need to be more clever. The
275 //! first obvious insight is that we only want to list constructors that are covered by the head
276 //! constructor of `q`. If it's a value constructor, we only try that one. If it's a pattern-only
277 //! constructor, we use the final clever idea for this algorithm: _constructor splitting_, where we
278 //! group together constructors that behave the same.
280 //! The details are not necessary to understand this file, so we explain them in
281 //! [`super::deconstruct_pat`]. Splitting is done by the [`Constructor::split`] function.
283 use self::Usefulness::*;
284 use self::WitnessPreference::*;
286 use super::deconstruct_pat::{Constructor, Fields, SplitWildcard};
287 use super::{PatternFoldable, PatternFolder};
289 use rustc_data_structures::captures::Captures;
290 use rustc_data_structures::fx::FxHashMap;
292 use rustc_arena::TypedArena;
293 use rustc_hir::def_id::DefId;
294 use rustc_hir::HirId;
295 use rustc_middle::thir::{Pat, PatKind};
296 use rustc_middle::ty::{self, Ty, TyCtxt};
297 use rustc_span::Span;
299 use smallvec::{smallvec, SmallVec};
301 use std::iter::{FromIterator, IntoIterator};
302 use std::lazy::OnceCell;
304 crate struct MatchCheckCtxt<'a, 'tcx> {
305 crate tcx: TyCtxt<'tcx>,
306 /// The module in which the match occurs. This is necessary for
307 /// checking inhabited-ness of types because whether a type is (visibly)
308 /// inhabited can depend on whether it was defined in the current module or
309 /// not. E.g., `struct Foo { _private: ! }` cannot be seen to be empty
310 /// outside its module and should not be matchable with an empty match statement.
312 crate param_env: ty::ParamEnv<'tcx>,
313 crate pattern_arena: &'a TypedArena<Pat<'tcx>>,
316 impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> {
317 pub(super) fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool {
318 if self.tcx.features().exhaustive_patterns {
319 self.tcx.is_ty_uninhabited_from(self.module, ty, self.param_env)
325 /// Returns whether the given type is an enum from another crate declared `#[non_exhaustive]`.
326 pub(super) fn is_foreign_non_exhaustive_enum(&self, ty: Ty<'tcx>) -> bool {
328 ty::Adt(def, ..) => {
329 def.is_enum() && def.is_variant_list_non_exhaustive() && !def.did.is_local()
336 #[derive(Copy, Clone)]
337 pub(super) struct PatCtxt<'a, 'p, 'tcx> {
338 pub(super) cx: &'a MatchCheckCtxt<'p, 'tcx>,
339 /// Type of the current column under investigation.
340 pub(super) ty: Ty<'tcx>,
341 /// Span of the current pattern under investigation.
342 pub(super) span: Span,
343 /// Whether the current pattern is the whole pattern as found in a match arm, or if it's a
345 pub(super) is_top_level: bool,
348 impl<'a, 'p, 'tcx> fmt::Debug for PatCtxt<'a, 'p, 'tcx> {
349 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350 f.debug_struct("PatCtxt").field("ty", &self.ty).finish()
354 crate fn expand_pattern<'tcx>(pat: Pat<'tcx>) -> Pat<'tcx> {
355 LiteralExpander.fold_pattern(&pat)
358 struct LiteralExpander;
360 impl<'tcx> PatternFolder<'tcx> for LiteralExpander {
361 fn fold_pattern(&mut self, pat: &Pat<'tcx>) -> Pat<'tcx> {
362 debug!("fold_pattern {:?} {:?} {:?}", pat, pat.ty.kind(), pat.kind);
363 match (pat.ty.kind(), pat.kind.as_ref()) {
364 (_, PatKind::Binding { subpattern: Some(s), .. }) => s.fold_with(self),
365 (_, PatKind::AscribeUserType { subpattern: s, .. }) => s.fold_with(self),
366 (ty::Ref(_, t, _), PatKind::Constant { .. }) if t.is_str() => {
367 // Treat string literal patterns as deref patterns to a `str` constant, i.e.
368 // `&CONST`. This expands them like other const patterns. This could have been done
369 // in `const_to_pat`, but that causes issues with the rest of the matching code.
370 let mut new_pat = pat.super_fold_with(self);
371 // Make a fake const pattern of type `str` (instead of `&str`). That the carried
372 // constant value still knows it is of type `&str`.
375 kind: Box::new(PatKind::Deref { subpattern: new_pat }),
380 _ => pat.super_fold_with(self),
385 pub(super) fn is_wildcard(pat: &Pat<'_>) -> bool {
386 matches!(*pat.kind, PatKind::Binding { subpattern: None, .. } | PatKind::Wild)
389 fn is_or_pat(pat: &Pat<'_>) -> bool {
390 matches!(*pat.kind, PatKind::Or { .. })
393 /// Recursively expand this pattern into its subpatterns. Only useful for or-patterns.
394 fn expand_or_pat<'p, 'tcx>(pat: &'p Pat<'tcx>) -> Vec<&'p Pat<'tcx>> {
395 fn expand<'p, 'tcx>(pat: &'p Pat<'tcx>, vec: &mut Vec<&'p Pat<'tcx>>) {
396 if let PatKind::Or { pats } = pat.kind.as_ref() {
405 let mut pats = Vec::new();
406 expand(pat, &mut pats);
410 /// A row of a matrix. Rows of len 1 are very common, which is why `SmallVec[_; 2]`
413 struct PatStack<'p, 'tcx> {
414 pats: SmallVec<[&'p Pat<'tcx>; 2]>,
415 /// Cache for the constructor of the head
416 head_ctor: OnceCell<Constructor<'tcx>>,
419 impl<'p, 'tcx> PatStack<'p, 'tcx> {
420 fn from_pattern(pat: &'p Pat<'tcx>) -> Self {
421 Self::from_vec(smallvec![pat])
424 fn from_vec(vec: SmallVec<[&'p Pat<'tcx>; 2]>) -> Self {
425 PatStack { pats: vec, head_ctor: OnceCell::new() }
428 fn is_empty(&self) -> bool {
432 fn len(&self) -> usize {
436 fn head(&self) -> &'p Pat<'tcx> {
441 fn head_ctor<'a>(&'a self, cx: &MatchCheckCtxt<'p, 'tcx>) -> &'a Constructor<'tcx> {
442 self.head_ctor.get_or_init(|| Constructor::from_pat(cx, self.head()))
445 fn iter(&self) -> impl Iterator<Item = &Pat<'tcx>> {
446 self.pats.iter().copied()
449 // Recursively expand the first pattern into its subpatterns. Only useful if the pattern is an
450 // or-pattern. Panics if `self` is empty.
451 fn expand_or_pat<'a>(&'a self) -> impl Iterator<Item = PatStack<'p, 'tcx>> + Captures<'a> {
452 expand_or_pat(self.head()).into_iter().map(move |pat| {
453 let mut new_patstack = PatStack::from_pattern(pat);
454 new_patstack.pats.extend_from_slice(&self.pats[1..]);
459 /// This computes `S(self.head_ctor(), self)`. See top of the file for explanations.
461 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
462 /// fields filled with wild patterns.
464 /// This is roughly the inverse of `Constructor::apply`.
465 fn pop_head_constructor(&self, ctor_wild_subpatterns: &Fields<'p, 'tcx>) -> PatStack<'p, 'tcx> {
466 // We pop the head pattern and push the new fields extracted from the arguments of
469 ctor_wild_subpatterns.replace_with_pattern_arguments(self.head()).into_patterns();
470 new_fields.extend_from_slice(&self.pats[1..]);
471 PatStack::from_vec(new_fields)
475 impl<'p, 'tcx> Default for PatStack<'p, 'tcx> {
476 fn default() -> Self {
477 Self::from_vec(smallvec![])
481 impl<'p, 'tcx> PartialEq for PatStack<'p, 'tcx> {
482 fn eq(&self, other: &Self) -> bool {
483 self.pats == other.pats
487 impl<'p, 'tcx> FromIterator<&'p Pat<'tcx>> for PatStack<'p, 'tcx> {
488 fn from_iter<T>(iter: T) -> Self
490 T: IntoIterator<Item = &'p Pat<'tcx>>,
492 Self::from_vec(iter.into_iter().collect())
496 /// Pretty-printing for matrix row.
497 impl<'p, 'tcx> fmt::Debug for PatStack<'p, 'tcx> {
498 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
500 for pat in self.iter() {
501 write!(f, " {} +", pat)?;
508 #[derive(Clone, PartialEq)]
509 pub(super) struct Matrix<'p, 'tcx> {
510 patterns: Vec<PatStack<'p, 'tcx>>,
513 impl<'p, 'tcx> Matrix<'p, 'tcx> {
515 Matrix { patterns: vec![] }
518 /// Number of columns of this matrix. `None` is the matrix is empty.
519 pub(super) fn column_count(&self) -> Option<usize> {
520 self.patterns.get(0).map(|r| r.len())
523 /// Pushes a new row to the matrix. If the row starts with an or-pattern, this recursively
525 fn push(&mut self, row: PatStack<'p, 'tcx>) {
526 if !row.is_empty() && is_or_pat(row.head()) {
527 for row in row.expand_or_pat() {
528 self.patterns.push(row);
531 self.patterns.push(row);
535 /// Iterate over the first component of each row
536 fn heads<'a>(&'a self) -> impl Iterator<Item = &'a Pat<'tcx>> + Captures<'p> {
537 self.patterns.iter().map(|r| r.head())
540 /// Iterate over the first constructor of each row.
541 pub(super) fn head_ctors<'a>(
543 cx: &'a MatchCheckCtxt<'p, 'tcx>,
544 ) -> impl Iterator<Item = &'a Constructor<'tcx>> + Captures<'p> + Clone {
545 self.patterns.iter().map(move |r| r.head_ctor(cx))
548 /// Iterate over the first constructor and the corresponding span of each row.
549 pub(super) fn head_ctors_and_spans<'a>(
551 cx: &'a MatchCheckCtxt<'p, 'tcx>,
552 ) -> impl Iterator<Item = (&'a Constructor<'tcx>, Span)> + Captures<'p> {
553 self.patterns.iter().map(move |r| (r.head_ctor(cx), r.head().span))
556 /// This computes `S(constructor, self)`. See top of the file for explanations.
557 fn specialize_constructor(
559 pcx: PatCtxt<'_, 'p, 'tcx>,
560 ctor: &Constructor<'tcx>,
561 ctor_wild_subpatterns: &Fields<'p, 'tcx>,
562 ) -> Matrix<'p, 'tcx> {
565 .filter(|r| ctor.is_covered_by(pcx, r.head_ctor(pcx.cx)))
566 .map(|r| r.pop_head_constructor(ctor_wild_subpatterns))
571 /// Pretty-printer for matrices of patterns, example:
575 /// + true + [First] +
576 /// + true + [Second(true)] +
578 /// + _ + [_, _, tail @ ..] +
580 impl<'p, 'tcx> fmt::Debug for Matrix<'p, 'tcx> {
581 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
584 let Matrix { patterns: m, .. } = self;
585 let pretty_printed_matrix: Vec<Vec<String>> =
586 m.iter().map(|row| row.iter().map(|pat| format!("{}", pat)).collect()).collect();
588 let column_count = m.iter().map(|row| row.len()).next().unwrap_or(0);
589 assert!(m.iter().all(|row| row.len() == column_count));
590 let column_widths: Vec<usize> = (0..column_count)
591 .map(|col| pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0))
594 for row in pretty_printed_matrix {
596 for (column, pat_str) in row.into_iter().enumerate() {
598 write!(f, "{:1$}", pat_str, column_widths[column])?;
607 impl<'p, 'tcx> FromIterator<PatStack<'p, 'tcx>> for Matrix<'p, 'tcx> {
608 fn from_iter<T>(iter: T) -> Self
610 T: IntoIterator<Item = PatStack<'p, 'tcx>>,
612 let mut matrix = Matrix::empty();
614 // Using `push` ensures we correctly expand or-patterns.
621 /// Given a pattern or a pattern-stack, this struct captures a set of its subpatterns. We use that
622 /// to track reachable sub-patterns arising from or-patterns. In the absence of or-patterns this
623 /// will always be either `Empty` (the whole pattern is unreachable) or `Full` (the whole pattern
624 /// is reachable). When there are or-patterns, some subpatterns may be reachable while others
625 /// aren't. In this case the whole pattern still counts as reachable, but we will lint the
626 /// unreachable subpatterns.
628 /// This supports a limited set of operations, so not all possible sets of subpatterns can be
629 /// represented. That's ok, we only want the ones that make sense for our usage.
631 /// What we're doing is illustrated by this:
633 /// match (true, 0) {
636 /// (true | false, 0 | 1) => {}
639 /// When we try the alternatives of the `true | false` or-pattern, the last `0` is reachable in the
640 /// `false` alternative but not the `true`. So overall it is reachable. By contrast, the last `1`
641 /// is not reachable in either alternative, so we want to signal this to the user.
642 /// Therefore we take the union of sets of reachable patterns coming from different alternatives in
643 /// order to figure out which subpatterns are overall reachable.
645 /// Invariant: we try to construct the smallest representation we can. In particular if
646 /// `self.is_empty()` we ensure that `self` is `Empty`, and same with `Full`. This is not important
647 /// for correctness currently.
648 #[derive(Debug, Clone)]
649 enum SubPatSet<'p, 'tcx> {
650 /// The empty set. This means the pattern is unreachable.
652 /// The set containing the full pattern.
654 /// If the pattern is a pattern with a constructor or a pattern-stack, we store a set for each
655 /// of its subpatterns. Missing entries in the map are implicitly full, because that's the
657 Seq { subpats: FxHashMap<usize, SubPatSet<'p, 'tcx>> },
658 /// If the pattern is an or-pattern, we store a set for each of its alternatives. Missing
659 /// entries in the map are implicitly empty. Note: we always flatten nested or-patterns.
661 subpats: FxHashMap<usize, SubPatSet<'p, 'tcx>>,
662 /// Counts the total number of alternatives in the pattern
664 /// We keep the pattern around to retrieve spans.
669 impl<'p, 'tcx> SubPatSet<'p, 'tcx> {
677 fn is_empty(&self) -> bool {
679 SubPatSet::Empty => true,
680 SubPatSet::Full => false,
681 // If any subpattern in a sequence is unreachable, the whole pattern is unreachable.
682 SubPatSet::Seq { subpats } => subpats.values().any(|set| set.is_empty()),
683 // An or-pattern is reachable if any of its alternatives is.
684 SubPatSet::Alt { subpats, .. } => subpats.values().all(|set| set.is_empty()),
688 fn is_full(&self) -> bool {
690 SubPatSet::Empty => false,
691 SubPatSet::Full => true,
692 // The whole pattern is reachable only when all its alternatives are.
693 SubPatSet::Seq { subpats } => subpats.values().all(|sub_set| sub_set.is_full()),
694 // The whole or-pattern is reachable only when all its alternatives are.
695 SubPatSet::Alt { subpats, alt_count, .. } => {
696 subpats.len() == *alt_count && subpats.values().all(|set| set.is_full())
701 /// Union `self` with `other`, mutating `self`.
702 fn union(&mut self, other: Self) {
704 // Union with full stays full; union with empty changes nothing.
705 if self.is_full() || other.is_empty() {
707 } else if self.is_empty() {
710 } else if other.is_full() {
715 match (&mut *self, other) {
716 (Seq { subpats: s_set }, Seq { subpats: mut o_set }) => {
717 s_set.retain(|i, s_sub_set| {
718 // Missing entries count as full.
719 let o_sub_set = o_set.remove(&i).unwrap_or(Full);
720 s_sub_set.union(o_sub_set);
721 // We drop full entries.
724 // Everything left in `o_set` is missing from `s_set`, i.e. counts as full. Since
725 // unioning with full returns full, we can drop those entries.
727 (Alt { subpats: s_set, .. }, Alt { subpats: mut o_set, .. }) => {
728 s_set.retain(|i, s_sub_set| {
729 // Missing entries count as empty.
730 let o_sub_set = o_set.remove(&i).unwrap_or(Empty);
731 s_sub_set.union(o_sub_set);
732 // We drop empty entries.
733 !s_sub_set.is_empty()
735 // Everything left in `o_set` is missing from `s_set`, i.e. counts as empty. Since
736 // unioning with empty changes nothing, we can take those entries as is.
747 /// Returns a list of the spans of the unreachable subpatterns. If `self` is empty (i.e. the
748 /// whole pattern is unreachable) we return `None`.
749 fn list_unreachable_spans(&self) -> Option<Vec<Span>> {
750 /// Panics if `set.is_empty()`.
751 fn fill_spans(set: &SubPatSet<'_, '_>, spans: &mut Vec<Span>) {
753 SubPatSet::Empty => bug!(),
754 SubPatSet::Full => {}
755 SubPatSet::Seq { subpats } => {
756 for (_, sub_set) in subpats {
757 fill_spans(sub_set, spans);
760 SubPatSet::Alt { subpats, pat, alt_count, .. } => {
761 let expanded = expand_or_pat(pat);
762 for i in 0..*alt_count {
763 let sub_set = subpats.get(&i).unwrap_or(&SubPatSet::Empty);
764 if sub_set.is_empty() {
765 // Found an unreachable subpattern.
766 spans.push(expanded[i].span);
768 fill_spans(sub_set, spans);
779 // No subpatterns are unreachable.
780 return Some(Vec::new());
782 let mut spans = Vec::new();
783 fill_spans(self, &mut spans);
787 /// When `self` refers to a patstack that was obtained from specialization, after running
788 /// `unspecialize` it will refer to the original patstack before specialization.
789 fn unspecialize(self, arity: usize) -> Self {
795 // We gather the first `arity` subpatterns together and shift the remaining ones.
796 let mut new_subpats = FxHashMap::default();
797 let mut new_subpats_first_col = FxHashMap::default();
798 for (i, sub_set) in subpats {
800 // The first `arity` indices are now part of the pattern in the first
802 new_subpats_first_col.insert(i, sub_set);
804 // Indices after `arity` are simply shifted
805 new_subpats.insert(i - arity + 1, sub_set);
808 // If `new_subpats_first_col` has no entries it counts as full, so we can omit it.
809 if !new_subpats_first_col.is_empty() {
810 new_subpats.insert(0, Seq { subpats: new_subpats_first_col });
812 Seq { subpats: new_subpats }
814 Alt { .. } => bug!(), // `self` is a patstack
818 /// When `self` refers to a patstack that was obtained from splitting an or-pattern, after
819 /// running `unspecialize` it will refer to the original patstack before splitting.
823 /// match Some(true) {
825 /// None | Some(true | false) => {}
828 /// Here `None` would return the full set and `Some(true | false)` would return the set
829 /// containing `false`. After `unsplit_or_pat`, we want the set to contain `None` and `false`.
830 /// This is what this function does.
831 fn unsplit_or_pat(mut self, alt_id: usize, alt_count: usize, pat: &'p Pat<'tcx>) -> Self {
837 // Subpatterns coming from inside the or-pattern alternative itself, e.g. in `None | Some(0
839 let set_first_col = match &mut self {
841 Seq { subpats } => subpats.remove(&0).unwrap_or(Full),
842 Empty => unreachable!(),
843 Alt { .. } => bug!(), // `self` is a patstack
845 let mut subpats_first_col = FxHashMap::default();
846 subpats_first_col.insert(alt_id, set_first_col);
847 let set_first_col = Alt { subpats: subpats_first_col, pat, alt_count };
849 let mut subpats = match self {
850 Full => FxHashMap::default(),
851 Seq { subpats } => subpats,
852 Empty => unreachable!(),
853 Alt { .. } => bug!(), // `self` is a patstack
855 subpats.insert(0, set_first_col);
860 /// This carries the results of computing usefulness, as described at the top of the file. When
861 /// checking usefulness of a match branch, we use the `NoWitnesses` variant, which also keeps track
862 /// of potential unreachable sub-patterns (in the presence of or-patterns). When checking
863 /// exhaustiveness of a whole match, we use the `WithWitnesses` variant, which carries a list of
864 /// witnesses of non-exhaustiveness when there are any.
865 /// Which variant to use is dictated by `WitnessPreference`.
866 #[derive(Clone, Debug)]
867 enum Usefulness<'p, 'tcx> {
868 /// Carries a set of subpatterns that have been found to be reachable. If empty, this indicates
869 /// the whole pattern is unreachable. If not, this indicates that the pattern is reachable but
870 /// that some sub-patterns may be unreachable (due to or-patterns). In the absence of
871 /// or-patterns this will always be either `Empty` (the whole pattern is unreachable) or `Full`
872 /// (the whole pattern is reachable).
873 NoWitnesses(SubPatSet<'p, 'tcx>),
874 /// Carries a list of witnesses of non-exhaustiveness. If empty, indicates that the whole
875 /// pattern is unreachable.
876 WithWitnesses(Vec<Witness<'tcx>>),
879 impl<'p, 'tcx> Usefulness<'p, 'tcx> {
880 fn new_useful(preference: WitnessPreference) -> Self {
882 ConstructWitness => WithWitnesses(vec![Witness(vec![])]),
883 LeaveOutWitness => NoWitnesses(SubPatSet::full()),
886 fn new_not_useful(preference: WitnessPreference) -> Self {
888 ConstructWitness => WithWitnesses(vec![]),
889 LeaveOutWitness => NoWitnesses(SubPatSet::empty()),
893 /// Combine usefulnesses from two branches. This is an associative operation.
894 fn extend(&mut self, other: Self) {
895 match (&mut *self, other) {
896 (WithWitnesses(_), WithWitnesses(o)) if o.is_empty() => {}
897 (WithWitnesses(s), WithWitnesses(o)) if s.is_empty() => *self = WithWitnesses(o),
898 (WithWitnesses(s), WithWitnesses(o)) => s.extend(o),
899 (NoWitnesses(s), NoWitnesses(o)) => s.union(o),
904 /// When trying several branches and each returns a `Usefulness`, we need to combine the
905 /// results together.
906 fn merge(pref: WitnessPreference, usefulnesses: impl Iterator<Item = Self>) -> Self {
907 let mut ret = Self::new_not_useful(pref);
908 for u in usefulnesses {
910 if let NoWitnesses(subpats) = &ret {
911 if subpats.is_full() {
912 // Once we reach the full set, more unions won't change the result.
920 /// After calculating the usefulness for a branch of an or-pattern, call this to make this
921 /// usefulness mergeable with those from the other branches.
922 fn unsplit_or_pat(self, alt_id: usize, alt_count: usize, pat: &'p Pat<'tcx>) -> Self {
924 NoWitnesses(subpats) => NoWitnesses(subpats.unsplit_or_pat(alt_id, alt_count, pat)),
925 WithWitnesses(_) => bug!(),
929 /// After calculating usefulness after a specialization, call this to recontruct a usefulness
930 /// that makes sense for the matrix pre-specialization. This new usefulness can then be merged
931 /// with the results of specializing with the other constructors.
932 fn apply_constructor(
934 pcx: PatCtxt<'_, 'p, 'tcx>,
935 matrix: &Matrix<'p, 'tcx>, // used to compute missing ctors
936 ctor: &Constructor<'tcx>,
937 ctor_wild_subpatterns: &Fields<'p, 'tcx>,
940 WithWitnesses(witnesses) if witnesses.is_empty() => WithWitnesses(witnesses),
941 WithWitnesses(witnesses) => {
942 let new_witnesses = if matches!(ctor, Constructor::Missing) {
943 let mut split_wildcard = SplitWildcard::new(pcx);
944 split_wildcard.split(pcx, matrix.head_ctors(pcx.cx));
945 // Construct for each missing constructor a "wild" version of this
946 // constructor, that matches everything that can be built with
947 // it. For example, if `ctor` is a `Constructor::Variant` for
948 // `Option::Some`, we get the pattern `Some(_)`.
949 let new_patterns: Vec<_> = split_wildcard
951 .map(|missing_ctor| {
952 Fields::wildcards(pcx, missing_ctor).apply(pcx, missing_ctor)
957 .flat_map(|witness| {
958 new_patterns.iter().map(move |pat| {
959 let mut witness = witness.clone();
960 witness.0.push(pat.clone());
968 .map(|witness| witness.apply_constructor(pcx, &ctor, ctor_wild_subpatterns))
971 WithWitnesses(new_witnesses)
973 NoWitnesses(subpats) => NoWitnesses(subpats.unspecialize(ctor_wild_subpatterns.len())),
978 #[derive(Copy, Clone, Debug)]
979 enum WitnessPreference {
984 /// A witness of non-exhaustiveness for error reporting, represented
985 /// as a list of patterns (in reverse order of construction) with
986 /// wildcards inside to represent elements that can take any inhabitant
987 /// of the type as a value.
989 /// A witness against a list of patterns should have the same types
990 /// and length as the pattern matched against. Because Rust `match`
991 /// is always against a single pattern, at the end the witness will
992 /// have length 1, but in the middle of the algorithm, it can contain
993 /// multiple patterns.
995 /// For example, if we are constructing a witness for the match against
998 /// struct Pair(Option<(u32, u32)>, bool);
1000 /// match (p: Pair) {
1001 /// Pair(None, _) => {}
1002 /// Pair(_, false) => {}
1006 /// We'll perform the following steps:
1007 /// 1. Start with an empty witness
1008 /// `Witness(vec![])`
1009 /// 2. Push a witness `true` against the `false`
1010 /// `Witness(vec![true])`
1011 /// 3. Push a witness `Some(_)` against the `None`
1012 /// `Witness(vec![true, Some(_)])`
1013 /// 4. Apply the `Pair` constructor to the witnesses
1014 /// `Witness(vec![Pair(Some(_), true)])`
1016 /// The final `Pair(Some(_), true)` is then the resulting witness.
1017 #[derive(Clone, Debug)]
1018 crate struct Witness<'tcx>(Vec<Pat<'tcx>>);
1020 impl<'tcx> Witness<'tcx> {
1021 /// Asserts that the witness contains a single pattern, and returns it.
1022 fn single_pattern(self) -> Pat<'tcx> {
1023 assert_eq!(self.0.len(), 1);
1024 self.0.into_iter().next().unwrap()
1027 /// Constructs a partial witness for a pattern given a list of
1028 /// patterns expanded by the specialization step.
1030 /// When a pattern P is discovered to be useful, this function is used bottom-up
1031 /// to reconstruct a complete witness, e.g., a pattern P' that covers a subset
1032 /// of values, V, where each value in that set is not covered by any previously
1033 /// used patterns and is covered by the pattern P'. Examples:
1035 /// left_ty: tuple of 3 elements
1036 /// pats: [10, 20, _] => (10, 20, _)
1038 /// left_ty: struct X { a: (bool, &'static str), b: usize}
1039 /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 }
1040 fn apply_constructor<'p>(
1042 pcx: PatCtxt<'_, 'p, 'tcx>,
1043 ctor: &Constructor<'tcx>,
1044 ctor_wild_subpatterns: &Fields<'p, 'tcx>,
1047 let len = self.0.len();
1048 let arity = ctor_wild_subpatterns.len();
1049 let pats = self.0.drain((len - arity)..).rev();
1050 ctor_wild_subpatterns.replace_fields(pcx.cx, pats).apply(pcx, ctor)
1059 /// Algorithm from <http://moscova.inria.fr/~maranget/papers/warn/index.html>.
1060 /// The algorithm from the paper has been modified to correctly handle empty
1061 /// types. The changes are:
1062 /// (0) We don't exit early if the pattern matrix has zero rows. We just
1063 /// continue to recurse over columns.
1064 /// (1) all_constructors will only return constructors that are statically
1065 /// possible. E.g., it will only return `Ok` for `Result<T, !>`.
1067 /// This finds whether a (row) vector `v` of patterns is 'useful' in relation
1068 /// to a set of such vectors `m` - this is defined as there being a set of
1069 /// inputs that will match `v` but not any of the sets in `m`.
1071 /// All the patterns at each column of the `matrix ++ v` matrix must have the same type.
1073 /// This is used both for reachability checking (if a pattern isn't useful in
1074 /// relation to preceding patterns, it is not reachable) and exhaustiveness
1075 /// checking (if a wildcard pattern is useful in relation to a matrix, the
1076 /// matrix isn't exhaustive).
1078 /// `is_under_guard` is used to inform if the pattern has a guard. If it
1079 /// has one it must not be inserted into the matrix. This shouldn't be
1080 /// relied on for soundness.
1083 skip(cx, matrix, witness_preference, hir_id, is_under_guard, is_top_level)
1085 fn is_useful<'p, 'tcx>(
1086 cx: &MatchCheckCtxt<'p, 'tcx>,
1087 matrix: &Matrix<'p, 'tcx>,
1088 v: &PatStack<'p, 'tcx>,
1089 witness_preference: WitnessPreference,
1091 is_under_guard: bool,
1093 ) -> Usefulness<'p, 'tcx> {
1094 debug!("matrix,v={:?}{:?}", matrix, v);
1095 let Matrix { patterns: rows, .. } = matrix;
1097 // The base case. We are pattern-matching on () and the return value is
1098 // based on whether our matrix has a row or not.
1099 // NOTE: This could potentially be optimized by checking rows.is_empty()
1100 // first and then, if v is non-empty, the return value is based on whether
1101 // the type of the tuple we're checking is inhabited or not.
1103 let ret = if rows.is_empty() {
1104 Usefulness::new_useful(witness_preference)
1106 Usefulness::new_not_useful(witness_preference)
1112 assert!(rows.iter().all(|r| r.len() == v.len()));
1114 // FIXME(Nadrieril): Hack to work around type normalization issues (see #72476).
1115 let ty = matrix.heads().next().map_or(v.head().ty, |r| r.ty);
1116 let pcx = PatCtxt { cx, ty, span: v.head().span, is_top_level };
1118 // If the first pattern is an or-pattern, expand it.
1119 let ret = if is_or_pat(v.head()) {
1120 debug!("expanding or-pattern");
1121 let v_head = v.head();
1122 let vs: Vec<_> = v.expand_or_pat().collect();
1123 let alt_count = vs.len();
1124 // We try each or-pattern branch in turn.
1125 let mut matrix = matrix.clone();
1126 let usefulnesses = vs.into_iter().enumerate().map(|(i, v)| {
1128 is_useful(cx, &matrix, &v, witness_preference, hir_id, is_under_guard, false);
1129 // If pattern has a guard don't add it to the matrix.
1130 if !is_under_guard {
1131 // We push the already-seen patterns into the matrix in order to detect redundant
1132 // branches like `Some(_) | Some(0)`.
1135 usefulness.unsplit_or_pat(i, alt_count, v_head)
1137 Usefulness::merge(witness_preference, usefulnesses)
1139 let v_ctor = v.head_ctor(cx);
1140 if let Constructor::IntRange(ctor_range) = &v_ctor {
1141 // Lint on likely incorrect range patterns (#63987)
1142 ctor_range.lint_overlapping_range_endpoints(
1144 matrix.head_ctors_and_spans(cx),
1145 matrix.column_count().unwrap_or(0),
1149 // We split the head constructor of `v`.
1150 let split_ctors = v_ctor.split(pcx, matrix.head_ctors(cx));
1151 // For each constructor, we compute whether there's a value that starts with it that would
1152 // witness the usefulness of `v`.
1153 let start_matrix = &matrix;
1154 let usefulnesses = split_ctors.into_iter().map(|ctor| {
1155 debug!("specialize({:?})", ctor);
1156 // We cache the result of `Fields::wildcards` because it is used a lot.
1157 let ctor_wild_subpatterns = Fields::wildcards(pcx, &ctor);
1159 start_matrix.specialize_constructor(pcx, &ctor, &ctor_wild_subpatterns);
1160 let v = v.pop_head_constructor(&ctor_wild_subpatterns);
1162 is_useful(cx, &spec_matrix, &v, witness_preference, hir_id, is_under_guard, false);
1163 usefulness.apply_constructor(pcx, start_matrix, &ctor, &ctor_wild_subpatterns)
1165 Usefulness::merge(witness_preference, usefulnesses)
1171 /// The arm of a match expression.
1172 #[derive(Clone, Copy)]
1173 crate struct MatchArm<'p, 'tcx> {
1174 /// The pattern must have been lowered through `check_match::MatchVisitor::lower_pattern`.
1175 crate pat: &'p Pat<'tcx>,
1176 crate hir_id: HirId,
1177 crate has_guard: bool,
1180 /// Indicates whether or not a given arm is reachable.
1181 #[derive(Clone, Debug)]
1182 crate enum Reachability {
1183 /// The arm is reachable. This additionally carries a set of or-pattern branches that have been
1184 /// found to be unreachable despite the overall arm being reachable. Used only in the presence
1185 /// of or-patterns, otherwise it stays empty.
1186 Reachable(Vec<Span>),
1187 /// The arm is unreachable.
1191 /// The output of checking a match for exhaustiveness and arm reachability.
1192 crate struct UsefulnessReport<'p, 'tcx> {
1193 /// For each arm of the input, whether that arm is reachable after the arms above it.
1194 crate arm_usefulness: Vec<(MatchArm<'p, 'tcx>, Reachability)>,
1195 /// If the match is exhaustive, this is empty. If not, this contains witnesses for the lack of
1197 crate non_exhaustiveness_witnesses: Vec<Pat<'tcx>>,
1200 /// The entrypoint for the usefulness algorithm. Computes whether a match is exhaustive and which
1201 /// of its arms are reachable.
1203 /// Note: the input patterns must have been lowered through
1204 /// `check_match::MatchVisitor::lower_pattern`.
1205 crate fn compute_match_usefulness<'p, 'tcx>(
1206 cx: &MatchCheckCtxt<'p, 'tcx>,
1207 arms: &[MatchArm<'p, 'tcx>],
1208 scrut_hir_id: HirId,
1210 ) -> UsefulnessReport<'p, 'tcx> {
1211 let mut matrix = Matrix::empty();
1212 let arm_usefulness: Vec<_> = arms
1216 let v = PatStack::from_pattern(arm.pat);
1218 is_useful(cx, &matrix, &v, LeaveOutWitness, arm.hir_id, arm.has_guard, true);
1222 let reachability = match usefulness {
1223 NoWitnesses(subpats) if subpats.is_empty() => Reachability::Unreachable,
1224 NoWitnesses(subpats) => {
1225 Reachability::Reachable(subpats.list_unreachable_spans().unwrap())
1227 WithWitnesses(..) => bug!(),
1233 let wild_pattern = cx.pattern_arena.alloc(Pat::wildcard_from_ty(scrut_ty));
1234 let v = PatStack::from_pattern(wild_pattern);
1235 let usefulness = is_useful(cx, &matrix, &v, ConstructWitness, scrut_hir_id, false, true);
1236 let non_exhaustiveness_witnesses = match usefulness {
1237 WithWitnesses(pats) => pats.into_iter().map(|w| w.single_pattern()).collect(),
1238 NoWitnesses(_) => bug!(),
1240 UsefulnessReport { arm_usefulness, non_exhaustiveness_witnesses }