]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/thir/pattern/usefulness.rs
Auto merge of #96000 - jyn514:faster-doctests, r=Mark-Simulacrum
[rust.git] / compiler / rustc_mir_build / src / thir / pattern / usefulness.rs
1 //! Note: tests specific to this file can be found in:
2 //!
3 //!   - `ui/pattern/usefulness`
4 //!   - `ui/or-patterns`
5 //!   - `ui/consts/const_in_pattern`
6 //!   - `ui/rfc-2008-non-exhaustive`
7 //!   - `ui/half-open-range-patterns`
8 //!   - probably many others
9 //!
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`.
12 //!
13 //! -----
14 //!
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)
19 //!
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.
24 //!
25 //!
26 //! # Summary
27 //!
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.
34 //!
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:
37 //! ```rust
38 //! match x {
39 //!     Some(_) => ...,
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
43 //! }
44 //! ```
45 //!
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.
49 //! ```rust
50 //! match x {
51 //!     Some(0) => ...,
52 //!     None => ...,
53 //!     // not exhaustive: `_` is useful because it matches `Some(1)`
54 //! }
55 //! ```
56 //!
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.
59 //!
60 //!
61 //! # Constructors and fields
62 //!
63 //! Note: we will often abbreviate "constructor" as "ctor".
64 //!
65 //! The idea that powers everything that is done in this file is the following: a (matchable)
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.
70 //!
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 matchable 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`.
77 //!
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.
85 //!
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:
90 //!
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)`
100 //!
101 //! Constructors, fields and relevant operations are defined in the [`super::deconstruct_pat`] module.
102 //!
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.
108 //!
109 //! Whether constructors cover each other is computed by [`Constructor::is_covered_by`].
110 //!
111 //!
112 //! # Specialization
113 //!
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.
121 //!
122 //! Let's take the following example:
123 //! ```
124 //! match x {
125 //!     Enum::Variant1(_) => {} // `p1`
126 //!     Enum::Variant2(None, 0) => {} // `p2`
127 //!     Enum::Variant2(Some(_), 0) => {} // `q`
128 //! }
129 //! ```
130 //!
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:
135 //!
136 //! ```
137 //! match x {
138 //!     (None, 0) => {} // `p2'`
139 //!     (Some(_), 0) => {} // `q'`
140 //! }
141 //! ```
142 //!
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.
146 //!
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
152 //! happening:
153 //! ```
154 //! [Enum::Variant1(_)]
155 //! [Enum::Variant2(None, 0)]
156 //! [Enum::Variant2(Some(_), 0)]
157 //! //==>> specialize with `Variant2`
158 //! [None, 0]
159 //! [Some(_), 0]
160 //! //==>> specialize with `Some`
161 //! [_, 0]
162 //! //==>> specialize with `true` (say the type was `bool`)
163 //! [0]
164 //! //==>> specialize with `0`
165 //! []
166 //! ```
167 //!
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.
172 //!
173 //! - Specializing for the wrong constructor returns nothing
174 //!
175 //!   `specialize(None, Some(p0)) := []`
176 //!
177 //! - Specializing for the correct constructor returns a single row with the fields
178 //!
179 //!   `specialize(Variant1, Variant1(p0, p1, p2)) := [[p0, p1, p2]]`
180 //!
181 //!   `specialize(Foo{..}, Foo { bar: p0, baz: p1 }) := [[p0, p1]]`
182 //!
183 //! - For or-patterns, we specialize each branch and concatenate the results
184 //!
185 //!   `specialize(c, p0 | p1) := specialize(c, p0) ++ specialize(c, p1)`
186 //!
187 //! - We treat the other pattern constructors as if they were a large or-pattern of all the
188 //!   possibilities:
189 //!
190 //!   `specialize(c, _) := specialize(c, Variant1(_) | Variant2(_, _) | ...)`
191 //!
192 //!   `specialize(c, 1..=100) := specialize(c, 1 | ... | 100)`
193 //!
194 //!   `specialize(c, [p0, .., p1]) := specialize(c, [p0, p1] | [p0, _, p1] | [p0, _, _, p1] | ...)`
195 //!
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`].
198 //!
199 //!
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.
202 //!
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.
208 //!
209 //!
210 //! # Computing usefulness
211 //!
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.
217 //!
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`.
221 //!
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.
225 //!
226 //!     - for each such ctor `c`:
227 //!
228 //!         - for each `q'` returned by `specialize(c, q)`:
229 //!
230 //!             - we compute `usefulness(specialize(c, p_1) ... specialize(c, p_n), q')`
231 //!
232 //!         - for each witness found, we revert specialization by pushing the constructor `c` on top.
233 //!
234 //!     - We return the concatenation of all the witnesses found, if any.
235 //!
236 //! Example:
237 //! ```
238 //! [Some(true)] // p_1
239 //! [None] // p_2
240 //! [Some(_)] // q
241 //! //==>> try `None`: `specialize(None, q)` returns nothing
242 //! //==>> try `Some`: `specialize(Some, q)` returns a single row
243 //! [true] // p_1'
244 //! [_] // q'
245 //! //==>> try `true`: `specialize(true, q')` returns a single row
246 //! [] // p_1''
247 //! [] // q''
248 //! //==>> base case; `n != 0` so `q''` is not useful.
249 //! //==>> go back up a step
250 //! [true] // p_1'
251 //! [_] // q'
252 //! //==>> try `false`: `specialize(false, q')` returns a single row
253 //! [] // q''
254 //! //==>> base case; `n == 0` so `q''` is useful. We return the single witness `[]`
255 //! witnesses:
256 //! []
257 //! //==>> undo the specialization with `false`
258 //! witnesses:
259 //! [false]
260 //! //==>> undo the specialization with `Some`
261 //! witnesses:
262 //! [Some(false)]
263 //! //==>> we have tried all the constructors. The output is the single witness `[Some(false)]`.
264 //! ```
265 //!
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.
269 //!
270 //!
271 //! # Making usefulness tractable: constructor splitting
272 //!
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.
279 //!
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.
282
283 use self::ArmType::*;
284 use self::Usefulness::*;
285
286 use super::check_match::{joined_uncovered_patterns, pattern_not_covered_label};
287 use super::deconstruct_pat::{Constructor, DeconstructedPat, Fields, SplitWildcard};
288
289 use rustc_data_structures::captures::Captures;
290
291 use rustc_arena::TypedArena;
292 use rustc_data_structures::stack::ensure_sufficient_stack;
293 use rustc_hir::def_id::DefId;
294 use rustc_hir::HirId;
295 use rustc_middle::ty::{self, Ty, TyCtxt};
296 use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS;
297 use rustc_span::{Span, DUMMY_SP};
298
299 use smallvec::{smallvec, SmallVec};
300 use std::fmt;
301 use std::iter::once;
302
303 crate struct MatchCheckCtxt<'p, 'tcx> {
304     crate tcx: TyCtxt<'tcx>,
305     /// The module in which the match occurs. This is necessary for
306     /// checking inhabited-ness of types because whether a type is (visibly)
307     /// inhabited can depend on whether it was defined in the current module or
308     /// not. E.g., `struct Foo { _private: ! }` cannot be seen to be empty
309     /// outside its module and should not be matchable with an empty match statement.
310     crate module: DefId,
311     crate param_env: ty::ParamEnv<'tcx>,
312     crate pattern_arena: &'p TypedArena<DeconstructedPat<'p, 'tcx>>,
313 }
314
315 impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> {
316     pub(super) fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool {
317         if self.tcx.features().exhaustive_patterns {
318             self.tcx.is_ty_uninhabited_from(self.module, ty, self.param_env)
319         } else {
320             false
321         }
322     }
323
324     /// Returns whether the given type is an enum from another crate declared `#[non_exhaustive]`.
325     pub(super) fn is_foreign_non_exhaustive_enum(&self, ty: Ty<'tcx>) -> bool {
326         match ty.kind() {
327             ty::Adt(def, ..) => {
328                 def.is_enum() && def.is_variant_list_non_exhaustive() && !def.did().is_local()
329             }
330             _ => false,
331         }
332     }
333 }
334
335 #[derive(Copy, Clone)]
336 pub(super) struct PatCtxt<'a, 'p, 'tcx> {
337     pub(super) cx: &'a MatchCheckCtxt<'p, 'tcx>,
338     /// Type of the current column under investigation.
339     pub(super) ty: Ty<'tcx>,
340     /// Span of the current pattern under investigation.
341     pub(super) span: Span,
342     /// Whether the current pattern is the whole pattern as found in a match arm, or if it's a
343     /// subpattern.
344     pub(super) is_top_level: bool,
345     /// Whether the current pattern is from a `non_exhaustive` enum.
346     pub(super) is_non_exhaustive: bool,
347 }
348
349 impl<'a, 'p, 'tcx> fmt::Debug for PatCtxt<'a, 'p, 'tcx> {
350     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
351         f.debug_struct("PatCtxt").field("ty", &self.ty).finish()
352     }
353 }
354
355 /// A row of a matrix. Rows of len 1 are very common, which is why `SmallVec[_; 2]`
356 /// works well.
357 #[derive(Clone)]
358 struct PatStack<'p, 'tcx> {
359     pats: SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]>,
360 }
361
362 impl<'p, 'tcx> PatStack<'p, 'tcx> {
363     fn from_pattern(pat: &'p DeconstructedPat<'p, 'tcx>) -> Self {
364         Self::from_vec(smallvec![pat])
365     }
366
367     fn from_vec(vec: SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]>) -> Self {
368         PatStack { pats: vec }
369     }
370
371     fn is_empty(&self) -> bool {
372         self.pats.is_empty()
373     }
374
375     fn len(&self) -> usize {
376         self.pats.len()
377     }
378
379     fn head(&self) -> &'p DeconstructedPat<'p, 'tcx> {
380         self.pats[0]
381     }
382
383     fn iter(&self) -> impl Iterator<Item = &DeconstructedPat<'p, 'tcx>> {
384         self.pats.iter().copied()
385     }
386
387     // Recursively expand the first pattern into its subpatterns. Only useful if the pattern is an
388     // or-pattern. Panics if `self` is empty.
389     fn expand_or_pat<'a>(&'a self) -> impl Iterator<Item = PatStack<'p, 'tcx>> + Captures<'a> {
390         self.head().iter_fields().map(move |pat| {
391             let mut new_patstack = PatStack::from_pattern(pat);
392             new_patstack.pats.extend_from_slice(&self.pats[1..]);
393             new_patstack
394         })
395     }
396
397     /// This computes `S(self.head().ctor(), self)`. See top of the file for explanations.
398     ///
399     /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
400     /// fields filled with wild patterns.
401     ///
402     /// This is roughly the inverse of `Constructor::apply`.
403     fn pop_head_constructor(
404         &self,
405         cx: &MatchCheckCtxt<'p, 'tcx>,
406         ctor: &Constructor<'tcx>,
407     ) -> PatStack<'p, 'tcx> {
408         // We pop the head pattern and push the new fields extracted from the arguments of
409         // `self.head()`.
410         let mut new_fields: SmallVec<[_; 2]> = self.head().specialize(cx, ctor);
411         new_fields.extend_from_slice(&self.pats[1..]);
412         PatStack::from_vec(new_fields)
413     }
414 }
415
416 /// Pretty-printing for matrix row.
417 impl<'p, 'tcx> fmt::Debug for PatStack<'p, 'tcx> {
418     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
419         write!(f, "+")?;
420         for pat in self.iter() {
421             write!(f, " {:?} +", pat)?;
422         }
423         Ok(())
424     }
425 }
426
427 /// A 2D matrix.
428 #[derive(Clone)]
429 pub(super) struct Matrix<'p, 'tcx> {
430     patterns: Vec<PatStack<'p, 'tcx>>,
431 }
432
433 impl<'p, 'tcx> Matrix<'p, 'tcx> {
434     fn empty() -> Self {
435         Matrix { patterns: vec![] }
436     }
437
438     /// Number of columns of this matrix. `None` is the matrix is empty.
439     pub(super) fn column_count(&self) -> Option<usize> {
440         self.patterns.get(0).map(|r| r.len())
441     }
442
443     /// Pushes a new row to the matrix. If the row starts with an or-pattern, this recursively
444     /// expands it.
445     fn push(&mut self, row: PatStack<'p, 'tcx>) {
446         if !row.is_empty() && row.head().is_or_pat() {
447             self.patterns.extend(row.expand_or_pat());
448         } else {
449             self.patterns.push(row);
450         }
451     }
452
453     /// Iterate over the first component of each row
454     fn heads<'a>(
455         &'a self,
456     ) -> impl Iterator<Item = &'p DeconstructedPat<'p, 'tcx>> + Clone + Captures<'a> {
457         self.patterns.iter().map(|r| r.head())
458     }
459
460     /// This computes `S(constructor, self)`. See top of the file for explanations.
461     fn specialize_constructor(
462         &self,
463         pcx: PatCtxt<'_, 'p, 'tcx>,
464         ctor: &Constructor<'tcx>,
465     ) -> Matrix<'p, 'tcx> {
466         let mut matrix = Matrix::empty();
467         for row in &self.patterns {
468             if ctor.is_covered_by(pcx, row.head().ctor()) {
469                 let new_row = row.pop_head_constructor(pcx.cx, ctor);
470                 matrix.push(new_row);
471             }
472         }
473         matrix
474     }
475 }
476
477 /// Pretty-printer for matrices of patterns, example:
478 ///
479 /// ```text
480 /// + _     + []                +
481 /// + true  + [First]           +
482 /// + true  + [Second(true)]    +
483 /// + false + [_]               +
484 /// + _     + [_, _, tail @ ..] +
485 /// ```
486 impl<'p, 'tcx> fmt::Debug for Matrix<'p, 'tcx> {
487     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
488         write!(f, "\n")?;
489
490         let Matrix { patterns: m, .. } = self;
491         let pretty_printed_matrix: Vec<Vec<String>> =
492             m.iter().map(|row| row.iter().map(|pat| format!("{:?}", pat)).collect()).collect();
493
494         let column_count = m.iter().map(|row| row.len()).next().unwrap_or(0);
495         assert!(m.iter().all(|row| row.len() == column_count));
496         let column_widths: Vec<usize> = (0..column_count)
497             .map(|col| pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0))
498             .collect();
499
500         for row in pretty_printed_matrix {
501             write!(f, "+")?;
502             for (column, pat_str) in row.into_iter().enumerate() {
503                 write!(f, " ")?;
504                 write!(f, "{:1$}", pat_str, column_widths[column])?;
505                 write!(f, " +")?;
506             }
507             write!(f, "\n")?;
508         }
509         Ok(())
510     }
511 }
512
513 /// This carries the results of computing usefulness, as described at the top of the file. When
514 /// checking usefulness of a match branch, we use the `NoWitnesses` variant, which also keeps track
515 /// of potential unreachable sub-patterns (in the presence of or-patterns). When checking
516 /// exhaustiveness of a whole match, we use the `WithWitnesses` variant, which carries a list of
517 /// witnesses of non-exhaustiveness when there are any.
518 /// Which variant to use is dictated by `ArmType`.
519 #[derive(Debug)]
520 enum Usefulness<'p, 'tcx> {
521     /// If we don't care about witnesses, simply remember if the pattern was useful.
522     NoWitnesses { useful: bool },
523     /// Carries a list of witnesses of non-exhaustiveness. If empty, indicates that the whole
524     /// pattern is unreachable.
525     WithWitnesses(Vec<Witness<'p, 'tcx>>),
526 }
527
528 impl<'p, 'tcx> Usefulness<'p, 'tcx> {
529     fn new_useful(preference: ArmType) -> Self {
530         match preference {
531             // A single (empty) witness of reachability.
532             FakeExtraWildcard => WithWitnesses(vec![Witness(vec![])]),
533             RealArm => NoWitnesses { useful: true },
534         }
535     }
536
537     fn new_not_useful(preference: ArmType) -> Self {
538         match preference {
539             FakeExtraWildcard => WithWitnesses(vec![]),
540             RealArm => NoWitnesses { useful: false },
541         }
542     }
543
544     fn is_useful(&self) -> bool {
545         match self {
546             Usefulness::NoWitnesses { useful } => *useful,
547             Usefulness::WithWitnesses(witnesses) => !witnesses.is_empty(),
548         }
549     }
550
551     /// Combine usefulnesses from two branches. This is an associative operation.
552     fn extend(&mut self, other: Self) {
553         match (&mut *self, other) {
554             (WithWitnesses(_), WithWitnesses(o)) if o.is_empty() => {}
555             (WithWitnesses(s), WithWitnesses(o)) if s.is_empty() => *self = WithWitnesses(o),
556             (WithWitnesses(s), WithWitnesses(o)) => s.extend(o),
557             (NoWitnesses { useful: s_useful }, NoWitnesses { useful: o_useful }) => {
558                 *s_useful = *s_useful || o_useful
559             }
560             _ => unreachable!(),
561         }
562     }
563
564     /// After calculating usefulness after a specialization, call this to reconstruct a usefulness
565     /// that makes sense for the matrix pre-specialization. This new usefulness can then be merged
566     /// with the results of specializing with the other constructors.
567     fn apply_constructor(
568         self,
569         pcx: PatCtxt<'_, 'p, 'tcx>,
570         matrix: &Matrix<'p, 'tcx>, // used to compute missing ctors
571         ctor: &Constructor<'tcx>,
572     ) -> Self {
573         match self {
574             NoWitnesses { .. } => self,
575             WithWitnesses(ref witnesses) if witnesses.is_empty() => self,
576             WithWitnesses(witnesses) => {
577                 let new_witnesses = if let Constructor::Missing { .. } = ctor {
578                     // We got the special `Missing` constructor, so each of the missing constructors
579                     // gives a new pattern that is not caught by the match. We list those patterns.
580                     let new_patterns = if pcx.is_non_exhaustive {
581                         // Here we don't want the user to try to list all variants, we want them to add
582                         // a wildcard, so we only suggest that.
583                         vec![DeconstructedPat::wildcard(pcx.ty)]
584                     } else {
585                         let mut split_wildcard = SplitWildcard::new(pcx);
586                         split_wildcard.split(pcx, matrix.heads().map(DeconstructedPat::ctor));
587
588                         // This lets us know if we skipped any variants because they are marked
589                         // `doc(hidden)` or they are unstable feature gate (only stdlib types).
590                         let mut hide_variant_show_wild = false;
591                         // Construct for each missing constructor a "wild" version of this
592                         // constructor, that matches everything that can be built with
593                         // it. For example, if `ctor` is a `Constructor::Variant` for
594                         // `Option::Some`, we get the pattern `Some(_)`.
595                         let mut new: Vec<DeconstructedPat<'_, '_>> = split_wildcard
596                             .iter_missing(pcx)
597                             .filter_map(|missing_ctor| {
598                                 // Check if this variant is marked `doc(hidden)`
599                                 if missing_ctor.is_doc_hidden_variant(pcx)
600                                     || missing_ctor.is_unstable_variant(pcx)
601                                 {
602                                     hide_variant_show_wild = true;
603                                     return None;
604                                 }
605                                 Some(DeconstructedPat::wild_from_ctor(pcx, missing_ctor.clone()))
606                             })
607                             .collect();
608
609                         if hide_variant_show_wild {
610                             new.push(DeconstructedPat::wildcard(pcx.ty));
611                         }
612
613                         new
614                     };
615
616                     witnesses
617                         .into_iter()
618                         .flat_map(|witness| {
619                             new_patterns.iter().map(move |pat| {
620                                 Witness(
621                                     witness
622                                         .0
623                                         .iter()
624                                         .chain(once(pat))
625                                         .map(DeconstructedPat::clone_and_forget_reachability)
626                                         .collect(),
627                                 )
628                             })
629                         })
630                         .collect()
631                 } else {
632                     witnesses
633                         .into_iter()
634                         .map(|witness| witness.apply_constructor(pcx, &ctor))
635                         .collect()
636                 };
637                 WithWitnesses(new_witnesses)
638             }
639         }
640     }
641 }
642
643 #[derive(Copy, Clone, Debug)]
644 enum ArmType {
645     FakeExtraWildcard,
646     RealArm,
647 }
648
649 /// A witness of non-exhaustiveness for error reporting, represented
650 /// as a list of patterns (in reverse order of construction) with
651 /// wildcards inside to represent elements that can take any inhabitant
652 /// of the type as a value.
653 ///
654 /// A witness against a list of patterns should have the same types
655 /// and length as the pattern matched against. Because Rust `match`
656 /// is always against a single pattern, at the end the witness will
657 /// have length 1, but in the middle of the algorithm, it can contain
658 /// multiple patterns.
659 ///
660 /// For example, if we are constructing a witness for the match against
661 ///
662 /// ```
663 /// struct Pair(Option<(u32, u32)>, bool);
664 ///
665 /// match (p: Pair) {
666 ///    Pair(None, _) => {}
667 ///    Pair(_, false) => {}
668 /// }
669 /// ```
670 ///
671 /// We'll perform the following steps:
672 /// 1. Start with an empty witness
673 ///     `Witness(vec![])`
674 /// 2. Push a witness `true` against the `false`
675 ///     `Witness(vec![true])`
676 /// 3. Push a witness `Some(_)` against the `None`
677 ///     `Witness(vec![true, Some(_)])`
678 /// 4. Apply the `Pair` constructor to the witnesses
679 ///     `Witness(vec![Pair(Some(_), true)])`
680 ///
681 /// The final `Pair(Some(_), true)` is then the resulting witness.
682 #[derive(Debug)]
683 crate struct Witness<'p, 'tcx>(Vec<DeconstructedPat<'p, 'tcx>>);
684
685 impl<'p, 'tcx> Witness<'p, 'tcx> {
686     /// Asserts that the witness contains a single pattern, and returns it.
687     fn single_pattern(self) -> DeconstructedPat<'p, 'tcx> {
688         assert_eq!(self.0.len(), 1);
689         self.0.into_iter().next().unwrap()
690     }
691
692     /// Constructs a partial witness for a pattern given a list of
693     /// patterns expanded by the specialization step.
694     ///
695     /// When a pattern P is discovered to be useful, this function is used bottom-up
696     /// to reconstruct a complete witness, e.g., a pattern P' that covers a subset
697     /// of values, V, where each value in that set is not covered by any previously
698     /// used patterns and is covered by the pattern P'. Examples:
699     ///
700     /// left_ty: tuple of 3 elements
701     /// pats: [10, 20, _]           => (10, 20, _)
702     ///
703     /// left_ty: struct X { a: (bool, &'static str), b: usize}
704     /// pats: [(false, "foo"), 42]  => X { a: (false, "foo"), b: 42 }
705     fn apply_constructor(mut self, pcx: PatCtxt<'_, 'p, 'tcx>, ctor: &Constructor<'tcx>) -> Self {
706         let pat = {
707             let len = self.0.len();
708             let arity = ctor.arity(pcx);
709             let pats = self.0.drain((len - arity)..).rev();
710             let fields = Fields::from_iter(pcx.cx, pats);
711             DeconstructedPat::new(ctor.clone(), fields, pcx.ty, DUMMY_SP)
712         };
713
714         self.0.push(pat);
715
716         self
717     }
718 }
719
720 /// Report that a match of a `non_exhaustive` enum marked with `non_exhaustive_omitted_patterns`
721 /// is not exhaustive enough.
722 ///
723 /// NB: The partner lint for structs lives in `compiler/rustc_typeck/src/check/pat.rs`.
724 fn lint_non_exhaustive_omitted_patterns<'p, 'tcx>(
725     cx: &MatchCheckCtxt<'p, 'tcx>,
726     scrut_ty: Ty<'tcx>,
727     sp: Span,
728     hir_id: HirId,
729     witnesses: Vec<DeconstructedPat<'p, 'tcx>>,
730 ) {
731     let joined_patterns = joined_uncovered_patterns(cx, &witnesses);
732     cx.tcx.struct_span_lint_hir(NON_EXHAUSTIVE_OMITTED_PATTERNS, hir_id, sp, |build| {
733         let mut lint = build.build("some variants are not matched explicitly");
734         lint.span_label(sp, pattern_not_covered_label(&witnesses, &joined_patterns));
735         lint.help(
736             "ensure that all variants are matched explicitly by adding the suggested match arms",
737         );
738         lint.note(&format!(
739             "the matched value is of type `{}` and the `non_exhaustive_omitted_patterns` attribute was found",
740             scrut_ty,
741         ));
742         lint.emit();
743     });
744 }
745
746 /// Algorithm from <http://moscova.inria.fr/~maranget/papers/warn/index.html>.
747 /// The algorithm from the paper has been modified to correctly handle empty
748 /// types. The changes are:
749 ///   (0) We don't exit early if the pattern matrix has zero rows. We just
750 ///       continue to recurse over columns.
751 ///   (1) all_constructors will only return constructors that are statically
752 ///       possible. E.g., it will only return `Ok` for `Result<T, !>`.
753 ///
754 /// This finds whether a (row) vector `v` of patterns is 'useful' in relation
755 /// to a set of such vectors `m` - this is defined as there being a set of
756 /// inputs that will match `v` but not any of the sets in `m`.
757 ///
758 /// All the patterns at each column of the `matrix ++ v` matrix must have the same type.
759 ///
760 /// This is used both for reachability checking (if a pattern isn't useful in
761 /// relation to preceding patterns, it is not reachable) and exhaustiveness
762 /// checking (if a wildcard pattern is useful in relation to a matrix, the
763 /// matrix isn't exhaustive).
764 ///
765 /// `is_under_guard` is used to inform if the pattern has a guard. If it
766 /// has one it must not be inserted into the matrix. This shouldn't be
767 /// relied on for soundness.
768 #[instrument(level = "debug", skip(cx, matrix, hir_id))]
769 fn is_useful<'p, 'tcx>(
770     cx: &MatchCheckCtxt<'p, 'tcx>,
771     matrix: &Matrix<'p, 'tcx>,
772     v: &PatStack<'p, 'tcx>,
773     witness_preference: ArmType,
774     hir_id: HirId,
775     is_under_guard: bool,
776     is_top_level: bool,
777 ) -> Usefulness<'p, 'tcx> {
778     debug!("matrix,v={:?}{:?}", matrix, v);
779     let Matrix { patterns: rows, .. } = matrix;
780
781     // The base case. We are pattern-matching on () and the return value is
782     // based on whether our matrix has a row or not.
783     // NOTE: This could potentially be optimized by checking rows.is_empty()
784     // first and then, if v is non-empty, the return value is based on whether
785     // the type of the tuple we're checking is inhabited or not.
786     if v.is_empty() {
787         let ret = if rows.is_empty() {
788             Usefulness::new_useful(witness_preference)
789         } else {
790             Usefulness::new_not_useful(witness_preference)
791         };
792         debug!(?ret);
793         return ret;
794     }
795
796     debug_assert!(rows.iter().all(|r| r.len() == v.len()));
797
798     let ty = v.head().ty();
799     let is_non_exhaustive = cx.is_foreign_non_exhaustive_enum(ty);
800     debug!("v.head: {:?}, v.span: {:?}", v.head(), v.head().span());
801     let pcx = PatCtxt { cx, ty, span: v.head().span(), is_top_level, is_non_exhaustive };
802
803     // If the first pattern is an or-pattern, expand it.
804     let mut ret = Usefulness::new_not_useful(witness_preference);
805     if v.head().is_or_pat() {
806         debug!("expanding or-pattern");
807         // We try each or-pattern branch in turn.
808         let mut matrix = matrix.clone();
809         for v in v.expand_or_pat() {
810             debug!(?v);
811             let usefulness = ensure_sufficient_stack(|| {
812                 is_useful(cx, &matrix, &v, witness_preference, hir_id, is_under_guard, false)
813             });
814             debug!(?usefulness);
815             ret.extend(usefulness);
816             // If pattern has a guard don't add it to the matrix.
817             if !is_under_guard {
818                 // We push the already-seen patterns into the matrix in order to detect redundant
819                 // branches like `Some(_) | Some(0)`.
820                 matrix.push(v);
821             }
822         }
823     } else {
824         let v_ctor = v.head().ctor();
825         debug!(?v_ctor);
826         if let Constructor::IntRange(ctor_range) = &v_ctor {
827             // Lint on likely incorrect range patterns (#63987)
828             ctor_range.lint_overlapping_range_endpoints(
829                 pcx,
830                 matrix.heads(),
831                 matrix.column_count().unwrap_or(0),
832                 hir_id,
833             )
834         }
835         // We split the head constructor of `v`.
836         let split_ctors = v_ctor.split(pcx, matrix.heads().map(DeconstructedPat::ctor));
837         let is_non_exhaustive_and_wild = is_non_exhaustive && v_ctor.is_wildcard();
838         // For each constructor, we compute whether there's a value that starts with it that would
839         // witness the usefulness of `v`.
840         let start_matrix = &matrix;
841         for ctor in split_ctors {
842             debug!("specialize({:?})", ctor);
843             // We cache the result of `Fields::wildcards` because it is used a lot.
844             let spec_matrix = start_matrix.specialize_constructor(pcx, &ctor);
845             let v = v.pop_head_constructor(cx, &ctor);
846             let usefulness = ensure_sufficient_stack(|| {
847                 is_useful(cx, &spec_matrix, &v, witness_preference, hir_id, is_under_guard, false)
848             });
849             let usefulness = usefulness.apply_constructor(pcx, start_matrix, &ctor);
850
851             // When all the conditions are met we have a match with a `non_exhaustive` enum
852             // that has the potential to trigger the `non_exhaustive_omitted_patterns` lint.
853             // To understand the workings checkout `Constructor::split` and `SplitWildcard::new/into_ctors`
854             if is_non_exhaustive_and_wild
855                 // We check that the match has a wildcard pattern and that that wildcard is useful,
856                 // meaning there are variants that are covered by the wildcard. Without the check
857                 // for `witness_preference` the lint would trigger on `if let NonExhaustiveEnum::A = foo {}`
858                 && usefulness.is_useful() && matches!(witness_preference, RealArm)
859                 && matches!(
860                     &ctor,
861                     Constructor::Missing { nonexhaustive_enum_missing_real_variants: true }
862                 )
863             {
864                 let patterns = {
865                     let mut split_wildcard = SplitWildcard::new(pcx);
866                     split_wildcard.split(pcx, matrix.heads().map(DeconstructedPat::ctor));
867                     // Construct for each missing constructor a "wild" version of this
868                     // constructor, that matches everything that can be built with
869                     // it. For example, if `ctor` is a `Constructor::Variant` for
870                     // `Option::Some`, we get the pattern `Some(_)`.
871                     split_wildcard
872                         .iter_missing(pcx)
873                         // Filter out the `NonExhaustive` because we want to list only real
874                         // variants. Also remove any unstable feature gated variants.
875                         // Because of how we computed `nonexhaustive_enum_missing_real_variants`,
876                         // this will not return an empty `Vec`.
877                         .filter(|c| !(c.is_non_exhaustive() || c.is_unstable_variant(pcx)))
878                         .cloned()
879                         .map(|missing_ctor| DeconstructedPat::wild_from_ctor(pcx, missing_ctor))
880                         .collect::<Vec<_>>()
881                 };
882
883                 lint_non_exhaustive_omitted_patterns(pcx.cx, pcx.ty, pcx.span, hir_id, patterns);
884             }
885
886             ret.extend(usefulness);
887         }
888     }
889
890     if ret.is_useful() {
891         v.head().set_reachable();
892     }
893
894     debug!(?ret);
895     ret
896 }
897
898 /// The arm of a match expression.
899 #[derive(Clone, Copy, Debug)]
900 crate struct MatchArm<'p, 'tcx> {
901     /// The pattern must have been lowered through `check_match::MatchVisitor::lower_pattern`.
902     crate pat: &'p DeconstructedPat<'p, 'tcx>,
903     crate hir_id: HirId,
904     crate has_guard: bool,
905 }
906
907 /// Indicates whether or not a given arm is reachable.
908 #[derive(Clone, Debug)]
909 crate enum Reachability {
910     /// The arm is reachable. This additionally carries a set of or-pattern branches that have been
911     /// found to be unreachable despite the overall arm being reachable. Used only in the presence
912     /// of or-patterns, otherwise it stays empty.
913     Reachable(Vec<Span>),
914     /// The arm is unreachable.
915     Unreachable,
916 }
917
918 /// The output of checking a match for exhaustiveness and arm reachability.
919 crate struct UsefulnessReport<'p, 'tcx> {
920     /// For each arm of the input, whether that arm is reachable after the arms above it.
921     crate arm_usefulness: Vec<(MatchArm<'p, 'tcx>, Reachability)>,
922     /// If the match is exhaustive, this is empty. If not, this contains witnesses for the lack of
923     /// exhaustiveness.
924     crate non_exhaustiveness_witnesses: Vec<DeconstructedPat<'p, 'tcx>>,
925 }
926
927 /// The entrypoint for the usefulness algorithm. Computes whether a match is exhaustive and which
928 /// of its arms are reachable.
929 ///
930 /// Note: the input patterns must have been lowered through
931 /// `check_match::MatchVisitor::lower_pattern`.
932 #[instrument(skip(cx, arms), level = "debug")]
933 crate fn compute_match_usefulness<'p, 'tcx>(
934     cx: &MatchCheckCtxt<'p, 'tcx>,
935     arms: &[MatchArm<'p, 'tcx>],
936     scrut_hir_id: HirId,
937     scrut_ty: Ty<'tcx>,
938 ) -> UsefulnessReport<'p, 'tcx> {
939     let mut matrix = Matrix::empty();
940     let arm_usefulness: Vec<_> = arms
941         .iter()
942         .copied()
943         .map(|arm| {
944             debug!(?arm);
945             let v = PatStack::from_pattern(arm.pat);
946             is_useful(cx, &matrix, &v, RealArm, arm.hir_id, arm.has_guard, true);
947             if !arm.has_guard {
948                 matrix.push(v);
949             }
950             let reachability = if arm.pat.is_reachable() {
951                 Reachability::Reachable(arm.pat.unreachable_spans())
952             } else {
953                 Reachability::Unreachable
954             };
955             (arm, reachability)
956         })
957         .collect();
958
959     let wild_pattern = cx.pattern_arena.alloc(DeconstructedPat::wildcard(scrut_ty));
960     let v = PatStack::from_pattern(wild_pattern);
961     let usefulness = is_useful(cx, &matrix, &v, FakeExtraWildcard, scrut_hir_id, false, true);
962     let non_exhaustiveness_witnesses = match usefulness {
963         WithWitnesses(pats) => pats.into_iter().map(|w| w.single_pattern()).collect(),
964         NoWitnesses { .. } => bug!(),
965     };
966     UsefulnessReport { arm_usefulness, non_exhaustiveness_witnesses }
967 }