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::ArmType::*;
284 use self::Usefulness::*;
286 use super::check_match::{joined_uncovered_patterns, pattern_not_covered_label};
287 use super::deconstruct_pat::{Constructor, DeconstructedPat, Fields, SplitWildcard};
289 use rustc_data_structures::captures::Captures;
291 use rustc_arena::TypedArena;
292 use rustc_hir::def_id::DefId;
293 use rustc_hir::HirId;
294 use rustc_middle::ty::{self, Ty, TyCtxt};
295 use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS;
296 use rustc_span::{Span, DUMMY_SP};
298 use smallvec::{smallvec, SmallVec};
302 crate struct MatchCheckCtxt<'p, 'tcx> {
303 crate tcx: TyCtxt<'tcx>,
304 /// The module in which the match occurs. This is necessary for
305 /// checking inhabited-ness of types because whether a type is (visibly)
306 /// inhabited can depend on whether it was defined in the current module or
307 /// not. E.g., `struct Foo { _private: ! }` cannot be seen to be empty
308 /// outside its module and should not be matchable with an empty match statement.
310 crate param_env: ty::ParamEnv<'tcx>,
311 crate pattern_arena: &'p TypedArena<DeconstructedPat<'p, 'tcx>>,
314 impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> {
315 pub(super) fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool {
316 if self.tcx.features().exhaustive_patterns {
317 self.tcx.is_ty_uninhabited_from(self.module, ty, self.param_env)
323 /// Returns whether the given type is an enum from another crate declared `#[non_exhaustive]`.
324 pub(super) fn is_foreign_non_exhaustive_enum(&self, ty: Ty<'tcx>) -> bool {
326 ty::Adt(def, ..) => {
327 def.is_enum() && def.is_variant_list_non_exhaustive() && !def.did.is_local()
334 #[derive(Copy, Clone)]
335 pub(super) struct PatCtxt<'a, 'p, 'tcx> {
336 pub(super) cx: &'a MatchCheckCtxt<'p, 'tcx>,
337 /// Type of the current column under investigation.
338 pub(super) ty: Ty<'tcx>,
339 /// Span of the current pattern under investigation.
340 pub(super) span: Span,
341 /// Whether the current pattern is the whole pattern as found in a match arm, or if it's a
343 pub(super) is_top_level: bool,
344 /// Wether the current pattern is from a `non_exhaustive` enum.
345 pub(super) is_non_exhaustive: 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 /// A row of a matrix. Rows of len 1 are very common, which is why `SmallVec[_; 2]`
357 struct PatStack<'p, 'tcx> {
358 pats: SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]>,
361 impl<'p, 'tcx> PatStack<'p, 'tcx> {
362 fn from_pattern(pat: &'p DeconstructedPat<'p, 'tcx>) -> Self {
363 Self::from_vec(smallvec![pat])
366 fn from_vec(vec: SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]>) -> Self {
367 PatStack { pats: vec }
370 fn is_empty(&self) -> bool {
374 fn len(&self) -> usize {
378 fn head(&self) -> &'p DeconstructedPat<'p, 'tcx> {
382 fn iter(&self) -> impl Iterator<Item = &DeconstructedPat<'p, 'tcx>> {
383 self.pats.iter().copied()
386 // Recursively expand the first pattern into its subpatterns. Only useful if the pattern is an
387 // or-pattern. Panics if `self` is empty.
388 fn expand_or_pat<'a>(&'a self) -> impl Iterator<Item = PatStack<'p, 'tcx>> + Captures<'a> {
389 self.head().iter_fields().map(move |pat| {
390 let mut new_patstack = PatStack::from_pattern(pat);
391 new_patstack.pats.extend_from_slice(&self.pats[1..]);
396 /// This computes `S(self.head().ctor(), self)`. See top of the file for explanations.
398 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
399 /// fields filled with wild patterns.
401 /// This is roughly the inverse of `Constructor::apply`.
402 fn pop_head_constructor(
404 cx: &MatchCheckCtxt<'p, 'tcx>,
405 ctor: &Constructor<'tcx>,
406 ) -> PatStack<'p, 'tcx> {
407 // We pop the head pattern and push the new fields extracted from the arguments of
409 let mut new_fields: SmallVec<[_; 2]> = self.head().specialize(cx, ctor);
410 new_fields.extend_from_slice(&self.pats[1..]);
411 PatStack::from_vec(new_fields)
415 /// Pretty-printing for matrix row.
416 impl<'p, 'tcx> fmt::Debug for PatStack<'p, 'tcx> {
417 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
419 for pat in self.iter() {
420 write!(f, " {:?} +", pat)?;
428 pub(super) struct Matrix<'p, 'tcx> {
429 patterns: Vec<PatStack<'p, 'tcx>>,
432 impl<'p, 'tcx> Matrix<'p, 'tcx> {
434 Matrix { patterns: vec![] }
437 /// Number of columns of this matrix. `None` is the matrix is empty.
438 pub(super) fn column_count(&self) -> Option<usize> {
439 self.patterns.get(0).map(|r| r.len())
442 /// Pushes a new row to the matrix. If the row starts with an or-pattern, this recursively
444 fn push(&mut self, row: PatStack<'p, 'tcx>) {
445 if !row.is_empty() && row.head().is_or_pat() {
446 for row in row.expand_or_pat() {
447 self.patterns.push(row);
450 self.patterns.push(row);
454 /// Iterate over the first component of each row
457 ) -> impl Iterator<Item = &'p DeconstructedPat<'p, 'tcx>> + Clone + Captures<'a> {
458 self.patterns.iter().map(|r| r.head())
461 /// This computes `S(constructor, self)`. See top of the file for explanations.
462 fn specialize_constructor(
464 pcx: PatCtxt<'_, 'p, 'tcx>,
465 ctor: &Constructor<'tcx>,
466 ) -> Matrix<'p, 'tcx> {
467 let mut matrix = Matrix::empty();
468 for row in &self.patterns {
469 if ctor.is_covered_by(pcx, row.head().ctor()) {
470 let new_row = row.pop_head_constructor(pcx.cx, ctor);
471 matrix.push(new_row);
478 /// Pretty-printer for matrices of patterns, example:
482 /// + true + [First] +
483 /// + true + [Second(true)] +
485 /// + _ + [_, _, tail @ ..] +
487 impl<'p, 'tcx> fmt::Debug for Matrix<'p, 'tcx> {
488 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
491 let Matrix { patterns: m, .. } = self;
492 let pretty_printed_matrix: Vec<Vec<String>> =
493 m.iter().map(|row| row.iter().map(|pat| format!("{:?}", pat)).collect()).collect();
495 let column_count = m.iter().map(|row| row.len()).next().unwrap_or(0);
496 assert!(m.iter().all(|row| row.len() == column_count));
497 let column_widths: Vec<usize> = (0..column_count)
498 .map(|col| pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0))
501 for row in pretty_printed_matrix {
503 for (column, pat_str) in row.into_iter().enumerate() {
505 write!(f, "{:1$}", pat_str, column_widths[column])?;
514 /// This carries the results of computing usefulness, as described at the top of the file. When
515 /// checking usefulness of a match branch, we use the `NoWitnesses` variant, which also keeps track
516 /// of potential unreachable sub-patterns (in the presence of or-patterns). When checking
517 /// exhaustiveness of a whole match, we use the `WithWitnesses` variant, which carries a list of
518 /// witnesses of non-exhaustiveness when there are any.
519 /// Which variant to use is dictated by `ArmType`.
521 enum Usefulness<'p, 'tcx> {
522 /// If we don't care about witnesses, simply remember if the pattern was useful.
523 NoWitnesses { useful: bool },
524 /// Carries a list of witnesses of non-exhaustiveness. If empty, indicates that the whole
525 /// pattern is unreachable.
526 WithWitnesses(Vec<Witness<'p, 'tcx>>),
529 impl<'p, 'tcx> Usefulness<'p, 'tcx> {
530 fn new_useful(preference: ArmType) -> Self {
532 // A single (empty) witness of reachability.
533 FakeExtraWildcard => WithWitnesses(vec![Witness(vec![])]),
534 RealArm => NoWitnesses { useful: true },
538 fn new_not_useful(preference: ArmType) -> Self {
540 FakeExtraWildcard => WithWitnesses(vec![]),
541 RealArm => NoWitnesses { useful: false },
545 fn is_useful(&self) -> bool {
547 Usefulness::NoWitnesses { useful } => *useful,
548 Usefulness::WithWitnesses(witnesses) => !witnesses.is_empty(),
552 /// Combine usefulnesses from two branches. This is an associative operation.
553 fn extend(&mut self, other: Self) {
554 match (&mut *self, other) {
555 (WithWitnesses(_), WithWitnesses(o)) if o.is_empty() => {}
556 (WithWitnesses(s), WithWitnesses(o)) if s.is_empty() => *self = WithWitnesses(o),
557 (WithWitnesses(s), WithWitnesses(o)) => s.extend(o),
558 (NoWitnesses { useful: s_useful }, NoWitnesses { useful: o_useful }) => {
559 *s_useful = *s_useful || o_useful
565 /// After calculating usefulness after a specialization, call this to reconstruct a usefulness
566 /// that makes sense for the matrix pre-specialization. This new usefulness can then be merged
567 /// with the results of specializing with the other constructors.
568 fn apply_constructor(
570 pcx: PatCtxt<'_, 'p, 'tcx>,
571 matrix: &Matrix<'p, 'tcx>, // used to compute missing ctors
572 ctor: &Constructor<'tcx>,
575 NoWitnesses { .. } => self,
576 WithWitnesses(ref witnesses) if witnesses.is_empty() => self,
577 WithWitnesses(witnesses) => {
578 let new_witnesses = if let Constructor::Missing { .. } = ctor {
579 // We got the special `Missing` constructor, so each of the missing constructors
580 // gives a new pattern that is not caught by the match. We list those patterns.
581 let new_patterns = if pcx.is_non_exhaustive {
582 // Here we don't want the user to try to list all variants, we want them to add
583 // a wildcard, so we only suggest that.
584 vec![DeconstructedPat::wildcard(pcx.ty)]
586 let mut split_wildcard = SplitWildcard::new(pcx);
587 split_wildcard.split(pcx, matrix.heads().map(DeconstructedPat::ctor));
589 // This lets us know if we skipped any variants because they are marked
590 // `doc(hidden)` or they are unstable feature gate (only stdlib types).
591 let mut hide_variant_show_wild = false;
592 // Construct for each missing constructor a "wild" version of this
593 // constructor, that matches everything that can be built with
594 // it. For example, if `ctor` is a `Constructor::Variant` for
595 // `Option::Some`, we get the pattern `Some(_)`.
596 let mut new: Vec<DeconstructedPat<'_, '_>> = split_wildcard
598 .filter_map(|missing_ctor| {
599 // Check if this variant is marked `doc(hidden)`
600 if missing_ctor.is_doc_hidden_variant(pcx)
601 || missing_ctor.is_unstable_variant(pcx)
603 hide_variant_show_wild = true;
606 Some(DeconstructedPat::wild_from_ctor(pcx, missing_ctor.clone()))
610 if hide_variant_show_wild {
611 new.push(DeconstructedPat::wildcard(pcx.ty));
619 .flat_map(|witness| {
620 new_patterns.iter().map(move |pat| {
626 .map(DeconstructedPat::clone_and_forget_reachability)
635 .map(|witness| witness.apply_constructor(pcx, &ctor))
638 WithWitnesses(new_witnesses)
644 #[derive(Copy, Clone, Debug)]
650 /// A witness of non-exhaustiveness for error reporting, represented
651 /// as a list of patterns (in reverse order of construction) with
652 /// wildcards inside to represent elements that can take any inhabitant
653 /// of the type as a value.
655 /// A witness against a list of patterns should have the same types
656 /// and length as the pattern matched against. Because Rust `match`
657 /// is always against a single pattern, at the end the witness will
658 /// have length 1, but in the middle of the algorithm, it can contain
659 /// multiple patterns.
661 /// For example, if we are constructing a witness for the match against
664 /// struct Pair(Option<(u32, u32)>, bool);
666 /// match (p: Pair) {
667 /// Pair(None, _) => {}
668 /// Pair(_, false) => {}
672 /// We'll perform the following steps:
673 /// 1. Start with an empty witness
674 /// `Witness(vec![])`
675 /// 2. Push a witness `true` against the `false`
676 /// `Witness(vec![true])`
677 /// 3. Push a witness `Some(_)` against the `None`
678 /// `Witness(vec![true, Some(_)])`
679 /// 4. Apply the `Pair` constructor to the witnesses
680 /// `Witness(vec![Pair(Some(_), true)])`
682 /// The final `Pair(Some(_), true)` is then the resulting witness.
684 crate struct Witness<'p, 'tcx>(Vec<DeconstructedPat<'p, 'tcx>>);
686 impl<'p, 'tcx> Witness<'p, 'tcx> {
687 /// Asserts that the witness contains a single pattern, and returns it.
688 fn single_pattern(self) -> DeconstructedPat<'p, 'tcx> {
689 assert_eq!(self.0.len(), 1);
690 self.0.into_iter().next().unwrap()
693 /// Constructs a partial witness for a pattern given a list of
694 /// patterns expanded by the specialization step.
696 /// When a pattern P is discovered to be useful, this function is used bottom-up
697 /// to reconstruct a complete witness, e.g., a pattern P' that covers a subset
698 /// of values, V, where each value in that set is not covered by any previously
699 /// used patterns and is covered by the pattern P'. Examples:
701 /// left_ty: tuple of 3 elements
702 /// pats: [10, 20, _] => (10, 20, _)
704 /// left_ty: struct X { a: (bool, &'static str), b: usize}
705 /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 }
706 fn apply_constructor(mut self, pcx: PatCtxt<'_, 'p, 'tcx>, ctor: &Constructor<'tcx>) -> Self {
708 let len = self.0.len();
709 let arity = ctor.arity(pcx);
710 let pats = self.0.drain((len - arity)..).rev();
711 let fields = Fields::from_iter(pcx.cx, pats);
712 DeconstructedPat::new(ctor.clone(), fields, pcx.ty, DUMMY_SP)
721 /// Report that a match of a `non_exhaustive` enum marked with `non_exhaustive_omitted_patterns`
722 /// is not exhaustive enough.
724 /// NB: The partner lint for structs lives in `compiler/rustc_typeck/src/check/pat.rs`.
725 fn lint_non_exhaustive_omitted_patterns<'p, 'tcx>(
726 cx: &MatchCheckCtxt<'p, 'tcx>,
730 witnesses: Vec<DeconstructedPat<'p, 'tcx>>,
732 let joined_patterns = joined_uncovered_patterns(cx, &witnesses);
733 cx.tcx.struct_span_lint_hir(NON_EXHAUSTIVE_OMITTED_PATTERNS, hir_id, sp, |build| {
734 let mut lint = build.build("some variants are not matched explicitly");
735 lint.span_label(sp, pattern_not_covered_label(&witnesses, &joined_patterns));
737 "ensure that all variants are matched explicitly by adding the suggested match arms",
740 "the matched value is of type `{}` and the `non_exhaustive_omitted_patterns` attribute was found",
747 /// Algorithm from <http://moscova.inria.fr/~maranget/papers/warn/index.html>.
748 /// The algorithm from the paper has been modified to correctly handle empty
749 /// types. The changes are:
750 /// (0) We don't exit early if the pattern matrix has zero rows. We just
751 /// continue to recurse over columns.
752 /// (1) all_constructors will only return constructors that are statically
753 /// possible. E.g., it will only return `Ok` for `Result<T, !>`.
755 /// This finds whether a (row) vector `v` of patterns is 'useful' in relation
756 /// to a set of such vectors `m` - this is defined as there being a set of
757 /// inputs that will match `v` but not any of the sets in `m`.
759 /// All the patterns at each column of the `matrix ++ v` matrix must have the same type.
761 /// This is used both for reachability checking (if a pattern isn't useful in
762 /// relation to preceding patterns, it is not reachable) and exhaustiveness
763 /// checking (if a wildcard pattern is useful in relation to a matrix, the
764 /// matrix isn't exhaustive).
766 /// `is_under_guard` is used to inform if the pattern has a guard. If it
767 /// has one it must not be inserted into the matrix. This shouldn't be
768 /// relied on for soundness.
771 skip(cx, matrix, witness_preference, hir_id, is_under_guard, is_top_level)
773 fn is_useful<'p, 'tcx>(
774 cx: &MatchCheckCtxt<'p, 'tcx>,
775 matrix: &Matrix<'p, 'tcx>,
776 v: &PatStack<'p, 'tcx>,
777 witness_preference: ArmType,
779 is_under_guard: bool,
781 ) -> Usefulness<'p, 'tcx> {
782 debug!("matrix,v={:?}{:?}", matrix, v);
783 let Matrix { patterns: rows, .. } = matrix;
785 // The base case. We are pattern-matching on () and the return value is
786 // based on whether our matrix has a row or not.
787 // NOTE: This could potentially be optimized by checking rows.is_empty()
788 // first and then, if v is non-empty, the return value is based on whether
789 // the type of the tuple we're checking is inhabited or not.
791 let ret = if rows.is_empty() {
792 Usefulness::new_useful(witness_preference)
794 Usefulness::new_not_useful(witness_preference)
800 assert!(rows.iter().all(|r| r.len() == v.len()));
802 let ty = v.head().ty();
803 let is_non_exhaustive = cx.is_foreign_non_exhaustive_enum(ty);
804 let pcx = PatCtxt { cx, ty, span: v.head().span(), is_top_level, is_non_exhaustive };
806 // If the first pattern is an or-pattern, expand it.
807 let mut ret = Usefulness::new_not_useful(witness_preference);
808 if v.head().is_or_pat() {
809 debug!("expanding or-pattern");
810 // We try each or-pattern branch in turn.
811 let mut matrix = matrix.clone();
812 for v in v.expand_or_pat() {
814 is_useful(cx, &matrix, &v, witness_preference, hir_id, is_under_guard, false);
815 ret.extend(usefulness);
816 // If pattern has a guard don't add it to the matrix.
818 // We push the already-seen patterns into the matrix in order to detect redundant
819 // branches like `Some(_) | Some(0)`.
824 let v_ctor = v.head().ctor();
825 if let Constructor::IntRange(ctor_range) = &v_ctor {
826 // Lint on likely incorrect range patterns (#63987)
827 ctor_range.lint_overlapping_range_endpoints(
830 matrix.column_count().unwrap_or(0),
834 // We split the head constructor of `v`.
835 let split_ctors = v_ctor.split(pcx, matrix.heads().map(DeconstructedPat::ctor));
836 let is_non_exhaustive_and_wild = is_non_exhaustive && v_ctor.is_wildcard();
837 // For each constructor, we compute whether there's a value that starts with it that would
838 // witness the usefulness of `v`.
839 let start_matrix = &matrix;
840 for ctor in split_ctors {
841 debug!("specialize({:?})", ctor);
842 // We cache the result of `Fields::wildcards` because it is used a lot.
843 let spec_matrix = start_matrix.specialize_constructor(pcx, &ctor);
844 let v = v.pop_head_constructor(cx, &ctor);
846 is_useful(cx, &spec_matrix, &v, witness_preference, hir_id, is_under_guard, false);
847 let usefulness = usefulness.apply_constructor(pcx, start_matrix, &ctor);
849 // When all the conditions are met we have a match with a `non_exhaustive` enum
850 // that has the potential to trigger the `non_exhaustive_omitted_patterns` lint.
851 // To understand the workings checkout `Constructor::split` and `SplitWildcard::new/into_ctors`
852 if is_non_exhaustive_and_wild
853 // We check that the match has a wildcard pattern and that that wildcard is useful,
854 // meaning there are variants that are covered by the wildcard. Without the check
855 // for `witness_preference` the lint would trigger on `if let NonExhaustiveEnum::A = foo {}`
856 && usefulness.is_useful() && matches!(witness_preference, RealArm)
859 Constructor::Missing { nonexhaustive_enum_missing_real_variants: true }
863 let mut split_wildcard = SplitWildcard::new(pcx);
864 split_wildcard.split(pcx, matrix.heads().map(DeconstructedPat::ctor));
865 // Construct for each missing constructor a "wild" version of this
866 // constructor, that matches everything that can be built with
867 // it. For example, if `ctor` is a `Constructor::Variant` for
868 // `Option::Some`, we get the pattern `Some(_)`.
871 // Filter out the `NonExhaustive` because we want to list only real
872 // variants. Also remove any unstable feature gated variants.
873 // Because of how we computed `nonexhaustive_enum_missing_real_variants`,
874 // this will not return an empty `Vec`.
875 .filter(|c| !(c.is_non_exhaustive() || c.is_unstable_variant(pcx)))
877 .map(|missing_ctor| DeconstructedPat::wild_from_ctor(pcx, missing_ctor))
881 lint_non_exhaustive_omitted_patterns(pcx.cx, pcx.ty, pcx.span, hir_id, patterns);
884 ret.extend(usefulness);
889 v.head().set_reachable();
896 /// The arm of a match expression.
897 #[derive(Clone, Copy)]
898 crate struct MatchArm<'p, 'tcx> {
899 /// The pattern must have been lowered through `check_match::MatchVisitor::lower_pattern`.
900 crate pat: &'p DeconstructedPat<'p, 'tcx>,
902 crate has_guard: bool,
905 /// Indicates whether or not a given arm is reachable.
906 #[derive(Clone, Debug)]
907 crate enum Reachability {
908 /// The arm is reachable. This additionally carries a set of or-pattern branches that have been
909 /// found to be unreachable despite the overall arm being reachable. Used only in the presence
910 /// of or-patterns, otherwise it stays empty.
911 Reachable(Vec<Span>),
912 /// The arm is unreachable.
916 /// The output of checking a match for exhaustiveness and arm reachability.
917 crate struct UsefulnessReport<'p, 'tcx> {
918 /// For each arm of the input, whether that arm is reachable after the arms above it.
919 crate arm_usefulness: Vec<(MatchArm<'p, 'tcx>, Reachability)>,
920 /// If the match is exhaustive, this is empty. If not, this contains witnesses for the lack of
922 crate non_exhaustiveness_witnesses: Vec<DeconstructedPat<'p, 'tcx>>,
925 /// The entrypoint for the usefulness algorithm. Computes whether a match is exhaustive and which
926 /// of its arms are reachable.
928 /// Note: the input patterns must have been lowered through
929 /// `check_match::MatchVisitor::lower_pattern`.
930 crate fn compute_match_usefulness<'p, 'tcx>(
931 cx: &MatchCheckCtxt<'p, 'tcx>,
932 arms: &[MatchArm<'p, 'tcx>],
935 ) -> UsefulnessReport<'p, 'tcx> {
936 let mut matrix = Matrix::empty();
937 let arm_usefulness: Vec<_> = arms
941 let v = PatStack::from_pattern(arm.pat);
942 is_useful(cx, &matrix, &v, RealArm, arm.hir_id, arm.has_guard, true);
946 let reachability = if arm.pat.is_reachable() {
947 Reachability::Reachable(arm.pat.unreachable_spans())
949 Reachability::Unreachable
955 let wild_pattern = cx.pattern_arena.alloc(DeconstructedPat::wildcard(scrut_ty));
956 let v = PatStack::from_pattern(wild_pattern);
957 let usefulness = is_useful(cx, &matrix, &v, FakeExtraWildcard, scrut_hir_id, false, true);
958 let non_exhaustiveness_witnesses = match usefulness {
959 WithWitnesses(pats) => pats.into_iter().map(|w| w.single_pattern()).collect(),
960 NoWitnesses { .. } => bug!(),
962 UsefulnessReport { arm_usefulness, non_exhaustiveness_witnesses }