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