]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/thir/pattern/usefulness.rs
Rollup merge of #85766 - workingjubilee:file-options, r=yaahc
[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 (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.
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 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`.
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_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};
297
298 use smallvec::{smallvec, SmallVec};
299 use std::fmt;
300 use std::iter::once;
301
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.
309     crate module: DefId,
310     crate param_env: ty::ParamEnv<'tcx>,
311     crate pattern_arena: &'p TypedArena<DeconstructedPat<'p, 'tcx>>,
312 }
313
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)
318         } else {
319             false
320         }
321     }
322
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 {
325         match ty.kind() {
326             ty::Adt(def, ..) => {
327                 def.is_enum() && def.is_variant_list_non_exhaustive() && !def.did.is_local()
328             }
329             _ => false,
330         }
331     }
332 }
333
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
342     /// subpattern.
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,
346 }
347
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()
351     }
352 }
353
354 /// A row of a matrix. Rows of len 1 are very common, which is why `SmallVec[_; 2]`
355 /// works well.
356 #[derive(Clone)]
357 struct PatStack<'p, 'tcx> {
358     pats: SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]>,
359 }
360
361 impl<'p, 'tcx> PatStack<'p, 'tcx> {
362     fn from_pattern(pat: &'p DeconstructedPat<'p, 'tcx>) -> Self {
363         Self::from_vec(smallvec![pat])
364     }
365
366     fn from_vec(vec: SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]>) -> Self {
367         PatStack { pats: vec }
368     }
369
370     fn is_empty(&self) -> bool {
371         self.pats.is_empty()
372     }
373
374     fn len(&self) -> usize {
375         self.pats.len()
376     }
377
378     fn head(&self) -> &'p DeconstructedPat<'p, 'tcx> {
379         self.pats[0]
380     }
381
382     fn iter(&self) -> impl Iterator<Item = &DeconstructedPat<'p, 'tcx>> {
383         self.pats.iter().copied()
384     }
385
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..]);
392             new_patstack
393         })
394     }
395
396     /// This computes `S(self.head().ctor(), self)`. See top of the file for explanations.
397     ///
398     /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
399     /// fields filled with wild patterns.
400     ///
401     /// This is roughly the inverse of `Constructor::apply`.
402     fn pop_head_constructor(
403         &self,
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
408         // `self.head()`.
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)
412     }
413 }
414
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 {
418         write!(f, "+")?;
419         for pat in self.iter() {
420             write!(f, " {:?} +", pat)?;
421         }
422         Ok(())
423     }
424 }
425
426 /// A 2D matrix.
427 #[derive(Clone)]
428 pub(super) struct Matrix<'p, 'tcx> {
429     patterns: Vec<PatStack<'p, 'tcx>>,
430 }
431
432 impl<'p, 'tcx> Matrix<'p, 'tcx> {
433     fn empty() -> Self {
434         Matrix { patterns: vec![] }
435     }
436
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())
440     }
441
442     /// Pushes a new row to the matrix. If the row starts with an or-pattern, this recursively
443     /// expands it.
444     fn push(&mut self, row: PatStack<'p, 'tcx>) {
445         if !row.is_empty() && row.head().is_or_pat() {
446             self.patterns.extend(row.expand_or_pat());
447         } else {
448             self.patterns.push(row);
449         }
450     }
451
452     /// Iterate over the first component of each row
453     fn heads<'a>(
454         &'a self,
455     ) -> impl Iterator<Item = &'p DeconstructedPat<'p, 'tcx>> + Clone + Captures<'a> {
456         self.patterns.iter().map(|r| r.head())
457     }
458
459     /// This computes `S(constructor, self)`. See top of the file for explanations.
460     fn specialize_constructor(
461         &self,
462         pcx: PatCtxt<'_, 'p, 'tcx>,
463         ctor: &Constructor<'tcx>,
464     ) -> Matrix<'p, 'tcx> {
465         let mut matrix = Matrix::empty();
466         for row in &self.patterns {
467             if ctor.is_covered_by(pcx, row.head().ctor()) {
468                 let new_row = row.pop_head_constructor(pcx.cx, ctor);
469                 matrix.push(new_row);
470             }
471         }
472         matrix
473     }
474 }
475
476 /// Pretty-printer for matrices of patterns, example:
477 ///
478 /// ```text
479 /// + _     + []                +
480 /// + true  + [First]           +
481 /// + true  + [Second(true)]    +
482 /// + false + [_]               +
483 /// + _     + [_, _, tail @ ..] +
484 /// ```
485 impl<'p, 'tcx> fmt::Debug for Matrix<'p, 'tcx> {
486     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
487         write!(f, "\n")?;
488
489         let Matrix { patterns: m, .. } = self;
490         let pretty_printed_matrix: Vec<Vec<String>> =
491             m.iter().map(|row| row.iter().map(|pat| format!("{:?}", pat)).collect()).collect();
492
493         let column_count = m.iter().map(|row| row.len()).next().unwrap_or(0);
494         assert!(m.iter().all(|row| row.len() == column_count));
495         let column_widths: Vec<usize> = (0..column_count)
496             .map(|col| pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0))
497             .collect();
498
499         for row in pretty_printed_matrix {
500             write!(f, "+")?;
501             for (column, pat_str) in row.into_iter().enumerate() {
502                 write!(f, " ")?;
503                 write!(f, "{:1$}", pat_str, column_widths[column])?;
504                 write!(f, " +")?;
505             }
506             write!(f, "\n")?;
507         }
508         Ok(())
509     }
510 }
511
512 /// This carries the results of computing usefulness, as described at the top of the file. When
513 /// checking usefulness of a match branch, we use the `NoWitnesses` variant, which also keeps track
514 /// of potential unreachable sub-patterns (in the presence of or-patterns). When checking
515 /// exhaustiveness of a whole match, we use the `WithWitnesses` variant, which carries a list of
516 /// witnesses of non-exhaustiveness when there are any.
517 /// Which variant to use is dictated by `ArmType`.
518 #[derive(Debug)]
519 enum Usefulness<'p, 'tcx> {
520     /// If we don't care about witnesses, simply remember if the pattern was useful.
521     NoWitnesses { useful: bool },
522     /// Carries a list of witnesses of non-exhaustiveness. If empty, indicates that the whole
523     /// pattern is unreachable.
524     WithWitnesses(Vec<Witness<'p, 'tcx>>),
525 }
526
527 impl<'p, 'tcx> Usefulness<'p, 'tcx> {
528     fn new_useful(preference: ArmType) -> Self {
529         match preference {
530             // A single (empty) witness of reachability.
531             FakeExtraWildcard => WithWitnesses(vec![Witness(vec![])]),
532             RealArm => NoWitnesses { useful: true },
533         }
534     }
535
536     fn new_not_useful(preference: ArmType) -> Self {
537         match preference {
538             FakeExtraWildcard => WithWitnesses(vec![]),
539             RealArm => NoWitnesses { useful: false },
540         }
541     }
542
543     fn is_useful(&self) -> bool {
544         match self {
545             Usefulness::NoWitnesses { useful } => *useful,
546             Usefulness::WithWitnesses(witnesses) => !witnesses.is_empty(),
547         }
548     }
549
550     /// Combine usefulnesses from two branches. This is an associative operation.
551     fn extend(&mut self, other: Self) {
552         match (&mut *self, other) {
553             (WithWitnesses(_), WithWitnesses(o)) if o.is_empty() => {}
554             (WithWitnesses(s), WithWitnesses(o)) if s.is_empty() => *self = WithWitnesses(o),
555             (WithWitnesses(s), WithWitnesses(o)) => s.extend(o),
556             (NoWitnesses { useful: s_useful }, NoWitnesses { useful: o_useful }) => {
557                 *s_useful = *s_useful || o_useful
558             }
559             _ => unreachable!(),
560         }
561     }
562
563     /// After calculating usefulness after a specialization, call this to reconstruct a usefulness
564     /// that makes sense for the matrix pre-specialization. This new usefulness can then be merged
565     /// with the results of specializing with the other constructors.
566     fn apply_constructor(
567         self,
568         pcx: PatCtxt<'_, 'p, 'tcx>,
569         matrix: &Matrix<'p, 'tcx>, // used to compute missing ctors
570         ctor: &Constructor<'tcx>,
571     ) -> Self {
572         match self {
573             NoWitnesses { .. } => self,
574             WithWitnesses(ref witnesses) if witnesses.is_empty() => self,
575             WithWitnesses(witnesses) => {
576                 let new_witnesses = if let Constructor::Missing { .. } = ctor {
577                     // We got the special `Missing` constructor, so each of the missing constructors
578                     // gives a new pattern that is not caught by the match. We list those patterns.
579                     let new_patterns = if pcx.is_non_exhaustive {
580                         // Here we don't want the user to try to list all variants, we want them to add
581                         // a wildcard, so we only suggest that.
582                         vec![DeconstructedPat::wildcard(pcx.ty)]
583                     } else {
584                         let mut split_wildcard = SplitWildcard::new(pcx);
585                         split_wildcard.split(pcx, matrix.heads().map(DeconstructedPat::ctor));
586
587                         // This lets us know if we skipped any variants because they are marked
588                         // `doc(hidden)` or they are unstable feature gate (only stdlib types).
589                         let mut hide_variant_show_wild = false;
590                         // Construct for each missing constructor a "wild" version of this
591                         // constructor, that matches everything that can be built with
592                         // it. For example, if `ctor` is a `Constructor::Variant` for
593                         // `Option::Some`, we get the pattern `Some(_)`.
594                         let mut new: Vec<DeconstructedPat<'_, '_>> = split_wildcard
595                             .iter_missing(pcx)
596                             .filter_map(|missing_ctor| {
597                                 // Check if this variant is marked `doc(hidden)`
598                                 if missing_ctor.is_doc_hidden_variant(pcx)
599                                     || missing_ctor.is_unstable_variant(pcx)
600                                 {
601                                     hide_variant_show_wild = true;
602                                     return None;
603                                 }
604                                 Some(DeconstructedPat::wild_from_ctor(pcx, missing_ctor.clone()))
605                             })
606                             .collect();
607
608                         if hide_variant_show_wild {
609                             new.push(DeconstructedPat::wildcard(pcx.ty));
610                         }
611
612                         new
613                     };
614
615                     witnesses
616                         .into_iter()
617                         .flat_map(|witness| {
618                             new_patterns.iter().map(move |pat| {
619                                 Witness(
620                                     witness
621                                         .0
622                                         .iter()
623                                         .chain(once(pat))
624                                         .map(DeconstructedPat::clone_and_forget_reachability)
625                                         .collect(),
626                                 )
627                             })
628                         })
629                         .collect()
630                 } else {
631                     witnesses
632                         .into_iter()
633                         .map(|witness| witness.apply_constructor(pcx, &ctor))
634                         .collect()
635                 };
636                 WithWitnesses(new_witnesses)
637             }
638         }
639     }
640 }
641
642 #[derive(Copy, Clone, Debug)]
643 enum ArmType {
644     FakeExtraWildcard,
645     RealArm,
646 }
647
648 /// A witness of non-exhaustiveness for error reporting, represented
649 /// as a list of patterns (in reverse order of construction) with
650 /// wildcards inside to represent elements that can take any inhabitant
651 /// of the type as a value.
652 ///
653 /// A witness against a list of patterns should have the same types
654 /// and length as the pattern matched against. Because Rust `match`
655 /// is always against a single pattern, at the end the witness will
656 /// have length 1, but in the middle of the algorithm, it can contain
657 /// multiple patterns.
658 ///
659 /// For example, if we are constructing a witness for the match against
660 ///
661 /// ```
662 /// struct Pair(Option<(u32, u32)>, bool);
663 ///
664 /// match (p: Pair) {
665 ///    Pair(None, _) => {}
666 ///    Pair(_, false) => {}
667 /// }
668 /// ```
669 ///
670 /// We'll perform the following steps:
671 /// 1. Start with an empty witness
672 ///     `Witness(vec![])`
673 /// 2. Push a witness `true` against the `false`
674 ///     `Witness(vec![true])`
675 /// 3. Push a witness `Some(_)` against the `None`
676 ///     `Witness(vec![true, Some(_)])`
677 /// 4. Apply the `Pair` constructor to the witnesses
678 ///     `Witness(vec![Pair(Some(_), true)])`
679 ///
680 /// The final `Pair(Some(_), true)` is then the resulting witness.
681 #[derive(Debug)]
682 crate struct Witness<'p, 'tcx>(Vec<DeconstructedPat<'p, 'tcx>>);
683
684 impl<'p, 'tcx> Witness<'p, 'tcx> {
685     /// Asserts that the witness contains a single pattern, and returns it.
686     fn single_pattern(self) -> DeconstructedPat<'p, 'tcx> {
687         assert_eq!(self.0.len(), 1);
688         self.0.into_iter().next().unwrap()
689     }
690
691     /// Constructs a partial witness for a pattern given a list of
692     /// patterns expanded by the specialization step.
693     ///
694     /// When a pattern P is discovered to be useful, this function is used bottom-up
695     /// to reconstruct a complete witness, e.g., a pattern P' that covers a subset
696     /// of values, V, where each value in that set is not covered by any previously
697     /// used patterns and is covered by the pattern P'. Examples:
698     ///
699     /// left_ty: tuple of 3 elements
700     /// pats: [10, 20, _]           => (10, 20, _)
701     ///
702     /// left_ty: struct X { a: (bool, &'static str), b: usize}
703     /// pats: [(false, "foo"), 42]  => X { a: (false, "foo"), b: 42 }
704     fn apply_constructor(mut self, pcx: PatCtxt<'_, 'p, 'tcx>, ctor: &Constructor<'tcx>) -> Self {
705         let pat = {
706             let len = self.0.len();
707             let arity = ctor.arity(pcx);
708             let pats = self.0.drain((len - arity)..).rev();
709             let fields = Fields::from_iter(pcx.cx, pats);
710             DeconstructedPat::new(ctor.clone(), fields, pcx.ty, DUMMY_SP)
711         };
712
713         self.0.push(pat);
714
715         self
716     }
717 }
718
719 /// Report that a match of a `non_exhaustive` enum marked with `non_exhaustive_omitted_patterns`
720 /// is not exhaustive enough.
721 ///
722 /// NB: The partner lint for structs lives in `compiler/rustc_typeck/src/check/pat.rs`.
723 fn lint_non_exhaustive_omitted_patterns<'p, 'tcx>(
724     cx: &MatchCheckCtxt<'p, 'tcx>,
725     scrut_ty: Ty<'tcx>,
726     sp: Span,
727     hir_id: HirId,
728     witnesses: Vec<DeconstructedPat<'p, 'tcx>>,
729 ) {
730     let joined_patterns = joined_uncovered_patterns(cx, &witnesses);
731     cx.tcx.struct_span_lint_hir(NON_EXHAUSTIVE_OMITTED_PATTERNS, hir_id, sp, |build| {
732         let mut lint = build.build("some variants are not matched explicitly");
733         lint.span_label(sp, pattern_not_covered_label(&witnesses, &joined_patterns));
734         lint.help(
735             "ensure that all variants are matched explicitly by adding the suggested match arms",
736         );
737         lint.note(&format!(
738             "the matched value is of type `{}` and the `non_exhaustive_omitted_patterns` attribute was found",
739             scrut_ty,
740         ));
741         lint.emit();
742     });
743 }
744
745 /// Algorithm from <http://moscova.inria.fr/~maranget/papers/warn/index.html>.
746 /// The algorithm from the paper has been modified to correctly handle empty
747 /// types. The changes are:
748 ///   (0) We don't exit early if the pattern matrix has zero rows. We just
749 ///       continue to recurse over columns.
750 ///   (1) all_constructors will only return constructors that are statically
751 ///       possible. E.g., it will only return `Ok` for `Result<T, !>`.
752 ///
753 /// This finds whether a (row) vector `v` of patterns is 'useful' in relation
754 /// to a set of such vectors `m` - this is defined as there being a set of
755 /// inputs that will match `v` but not any of the sets in `m`.
756 ///
757 /// All the patterns at each column of the `matrix ++ v` matrix must have the same type.
758 ///
759 /// This is used both for reachability checking (if a pattern isn't useful in
760 /// relation to preceding patterns, it is not reachable) and exhaustiveness
761 /// checking (if a wildcard pattern is useful in relation to a matrix, the
762 /// matrix isn't exhaustive).
763 ///
764 /// `is_under_guard` is used to inform if the pattern has a guard. If it
765 /// has one it must not be inserted into the matrix. This shouldn't be
766 /// relied on for soundness.
767 #[instrument(
768     level = "debug",
769     skip(cx, matrix, witness_preference, hir_id, is_under_guard, is_top_level)
770 )]
771 fn is_useful<'p, 'tcx>(
772     cx: &MatchCheckCtxt<'p, 'tcx>,
773     matrix: &Matrix<'p, 'tcx>,
774     v: &PatStack<'p, 'tcx>,
775     witness_preference: ArmType,
776     hir_id: HirId,
777     is_under_guard: bool,
778     is_top_level: bool,
779 ) -> Usefulness<'p, 'tcx> {
780     debug!("matrix,v={:?}{:?}", matrix, v);
781     let Matrix { patterns: rows, .. } = matrix;
782
783     // The base case. We are pattern-matching on () and the return value is
784     // based on whether our matrix has a row or not.
785     // NOTE: This could potentially be optimized by checking rows.is_empty()
786     // first and then, if v is non-empty, the return value is based on whether
787     // the type of the tuple we're checking is inhabited or not.
788     if v.is_empty() {
789         let ret = if rows.is_empty() {
790             Usefulness::new_useful(witness_preference)
791         } else {
792             Usefulness::new_not_useful(witness_preference)
793         };
794         debug!(?ret);
795         return ret;
796     }
797
798     debug_assert!(rows.iter().all(|r| r.len() == v.len()));
799
800     let ty = v.head().ty();
801     let is_non_exhaustive = cx.is_foreign_non_exhaustive_enum(ty);
802     let pcx = PatCtxt { cx, ty, span: v.head().span(), is_top_level, is_non_exhaustive };
803
804     // If the first pattern is an or-pattern, expand it.
805     let mut ret = Usefulness::new_not_useful(witness_preference);
806     if v.head().is_or_pat() {
807         debug!("expanding or-pattern");
808         // We try each or-pattern branch in turn.
809         let mut matrix = matrix.clone();
810         for v in v.expand_or_pat() {
811             let usefulness =
812                 is_useful(cx, &matrix, &v, witness_preference, hir_id, is_under_guard, false);
813             ret.extend(usefulness);
814             // If pattern has a guard don't add it to the matrix.
815             if !is_under_guard {
816                 // We push the already-seen patterns into the matrix in order to detect redundant
817                 // branches like `Some(_) | Some(0)`.
818                 matrix.push(v);
819             }
820         }
821     } else {
822         let v_ctor = v.head().ctor();
823         if let Constructor::IntRange(ctor_range) = &v_ctor {
824             // Lint on likely incorrect range patterns (#63987)
825             ctor_range.lint_overlapping_range_endpoints(
826                 pcx,
827                 matrix.heads(),
828                 matrix.column_count().unwrap_or(0),
829                 hir_id,
830             )
831         }
832         // We split the head constructor of `v`.
833         let split_ctors = v_ctor.split(pcx, matrix.heads().map(DeconstructedPat::ctor));
834         let is_non_exhaustive_and_wild = is_non_exhaustive && v_ctor.is_wildcard();
835         // For each constructor, we compute whether there's a value that starts with it that would
836         // witness the usefulness of `v`.
837         let start_matrix = &matrix;
838         for ctor in split_ctors {
839             debug!("specialize({:?})", ctor);
840             // We cache the result of `Fields::wildcards` because it is used a lot.
841             let spec_matrix = start_matrix.specialize_constructor(pcx, &ctor);
842             let v = v.pop_head_constructor(cx, &ctor);
843             let usefulness =
844                 is_useful(cx, &spec_matrix, &v, witness_preference, hir_id, is_under_guard, false);
845             let usefulness = usefulness.apply_constructor(pcx, start_matrix, &ctor);
846
847             // When all the conditions are met we have a match with a `non_exhaustive` enum
848             // that has the potential to trigger the `non_exhaustive_omitted_patterns` lint.
849             // To understand the workings checkout `Constructor::split` and `SplitWildcard::new/into_ctors`
850             if is_non_exhaustive_and_wild
851                 // We check that the match has a wildcard pattern and that that wildcard is useful,
852                 // meaning there are variants that are covered by the wildcard. Without the check
853                 // for `witness_preference` the lint would trigger on `if let NonExhaustiveEnum::A = foo {}`
854                 && usefulness.is_useful() && matches!(witness_preference, RealArm)
855                 && matches!(
856                     &ctor,
857                     Constructor::Missing { nonexhaustive_enum_missing_real_variants: true }
858                 )
859             {
860                 let patterns = {
861                     let mut split_wildcard = SplitWildcard::new(pcx);
862                     split_wildcard.split(pcx, matrix.heads().map(DeconstructedPat::ctor));
863                     // Construct for each missing constructor a "wild" version of this
864                     // constructor, that matches everything that can be built with
865                     // it. For example, if `ctor` is a `Constructor::Variant` for
866                     // `Option::Some`, we get the pattern `Some(_)`.
867                     split_wildcard
868                         .iter_missing(pcx)
869                         // Filter out the `NonExhaustive` because we want to list only real
870                         // variants. Also remove any unstable feature gated variants.
871                         // Because of how we computed `nonexhaustive_enum_missing_real_variants`,
872                         // this will not return an empty `Vec`.
873                         .filter(|c| !(c.is_non_exhaustive() || c.is_unstable_variant(pcx)))
874                         .cloned()
875                         .map(|missing_ctor| DeconstructedPat::wild_from_ctor(pcx, missing_ctor))
876                         .collect::<Vec<_>>()
877                 };
878
879                 lint_non_exhaustive_omitted_patterns(pcx.cx, pcx.ty, pcx.span, hir_id, patterns);
880             }
881
882             ret.extend(usefulness);
883         }
884     }
885
886     if ret.is_useful() {
887         v.head().set_reachable();
888     }
889
890     debug!(?ret);
891     ret
892 }
893
894 /// The arm of a match expression.
895 #[derive(Clone, Copy)]
896 crate struct MatchArm<'p, 'tcx> {
897     /// The pattern must have been lowered through `check_match::MatchVisitor::lower_pattern`.
898     crate pat: &'p DeconstructedPat<'p, 'tcx>,
899     crate hir_id: HirId,
900     crate has_guard: bool,
901 }
902
903 /// Indicates whether or not a given arm is reachable.
904 #[derive(Clone, Debug)]
905 crate enum Reachability {
906     /// The arm is reachable. This additionally carries a set of or-pattern branches that have been
907     /// found to be unreachable despite the overall arm being reachable. Used only in the presence
908     /// of or-patterns, otherwise it stays empty.
909     Reachable(Vec<Span>),
910     /// The arm is unreachable.
911     Unreachable,
912 }
913
914 /// The output of checking a match for exhaustiveness and arm reachability.
915 crate struct UsefulnessReport<'p, 'tcx> {
916     /// For each arm of the input, whether that arm is reachable after the arms above it.
917     crate arm_usefulness: Vec<(MatchArm<'p, 'tcx>, Reachability)>,
918     /// If the match is exhaustive, this is empty. If not, this contains witnesses for the lack of
919     /// exhaustiveness.
920     crate non_exhaustiveness_witnesses: Vec<DeconstructedPat<'p, 'tcx>>,
921 }
922
923 /// The entrypoint for the usefulness algorithm. Computes whether a match is exhaustive and which
924 /// of its arms are reachable.
925 ///
926 /// Note: the input patterns must have been lowered through
927 /// `check_match::MatchVisitor::lower_pattern`.
928 crate fn compute_match_usefulness<'p, 'tcx>(
929     cx: &MatchCheckCtxt<'p, 'tcx>,
930     arms: &[MatchArm<'p, 'tcx>],
931     scrut_hir_id: HirId,
932     scrut_ty: Ty<'tcx>,
933 ) -> UsefulnessReport<'p, 'tcx> {
934     let mut matrix = Matrix::empty();
935     let arm_usefulness: Vec<_> = arms
936         .iter()
937         .copied()
938         .map(|arm| {
939             let v = PatStack::from_pattern(arm.pat);
940             is_useful(cx, &matrix, &v, RealArm, arm.hir_id, arm.has_guard, true);
941             if !arm.has_guard {
942                 matrix.push(v);
943             }
944             let reachability = if arm.pat.is_reachable() {
945                 Reachability::Reachable(arm.pat.unreachable_spans())
946             } else {
947                 Reachability::Unreachable
948             };
949             (arm, reachability)
950         })
951         .collect();
952
953     let wild_pattern = cx.pattern_arena.alloc(DeconstructedPat::wildcard(scrut_ty));
954     let v = PatStack::from_pattern(wild_pattern);
955     let usefulness = is_useful(cx, &matrix, &v, FakeExtraWildcard, scrut_hir_id, false, true);
956     let non_exhaustiveness_witnesses = match usefulness {
957         WithWitnesses(pats) => pats.into_iter().map(|w| w.single_pattern()).collect(),
958         NoWitnesses { .. } => bug!(),
959     };
960     UsefulnessReport { arm_usefulness, non_exhaustiveness_witnesses }
961 }