]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/diagnostics/match_check/usefulness.rs
internal: Normalize field type after substituting
[rust.git] / crates / hir_ty / src / diagnostics / match_check / usefulness.rs
1 //! Based on rust-lang/rust (last sync f31622a50 2021-11-12)
2 //! <https://github.com/rust-lang/rust/blob/f31622a50/compiler/rustc_mir_build/src/thir/pattern/usefulness.rs>
3 //!
4 //! -----
5 //!
6 //! This file includes the logic for exhaustiveness and reachability checking for pattern-matching.
7 //! Specifically, given a list of patterns for a type, we can tell whether:
8 //! (a) each pattern is reachable (reachability)
9 //! (b) the patterns cover every possible value for the type (exhaustiveness)
10 //!
11 //! The algorithm implemented here is a modified version of the one described in [this
12 //! paper](http://moscova.inria.fr/~maranget/papers/warn/index.html). We have however generalized
13 //! it to accommodate the variety of patterns that Rust supports. We thus explain our version here,
14 //! without being as rigorous.
15 //!
16 //!
17 //! # Summary
18 //!
19 //! The core of the algorithm is the notion of "usefulness". A pattern `q` is said to be *useful*
20 //! relative to another pattern `p` of the same type if there is a value that is matched by `q` and
21 //! not matched by `p`. This generalizes to many `p`s: `q` is useful w.r.t. a list of patterns
22 //! `p_1 .. p_n` if there is a value that is matched by `q` and by none of the `p_i`. We write
23 //! `usefulness(p_1 .. p_n, q)` for a function that returns a list of such values. The aim of this
24 //! file is to compute it efficiently.
25 //!
26 //! This is enough to compute reachability: a pattern in a `match` expression is reachable iff it
27 //! is useful w.r.t. the patterns above it:
28 //! ```rust
29 //! match x {
30 //!     Some(_) => ...,
31 //!     None => ..., // reachable: `None` is matched by this but not the branch above
32 //!     Some(0) => ..., // unreachable: all the values this matches are already matched by
33 //!                     // `Some(_)` above
34 //! }
35 //! ```
36 //!
37 //! This is also enough to compute exhaustiveness: a match is exhaustive iff the wildcard `_`
38 //! pattern is _not_ useful w.r.t. the patterns in the match. The values returned by `usefulness`
39 //! are used to tell the user which values are missing.
40 //! ```rust
41 //! match x {
42 //!     Some(0) => ...,
43 //!     None => ...,
44 //!     // not exhaustive: `_` is useful because it matches `Some(1)`
45 //! }
46 //! ```
47 //!
48 //! The entrypoint of this file is the [`compute_match_usefulness`] function, which computes
49 //! reachability for each match branch and exhaustiveness for the whole match.
50 //!
51 //!
52 //! # Constructors and fields
53 //!
54 //! Note: we will often abbreviate "constructor" as "ctor".
55 //!
56 //! The idea that powers everything that is done in this file is the following: a (matcheable)
57 //! value is made from a constructor applied to a number of subvalues. Examples of constructors are
58 //! `Some`, `None`, `(,)` (the 2-tuple constructor), `Foo {..}` (the constructor for a struct
59 //! `Foo`), and `2` (the constructor for the number `2`). This is natural when we think of
60 //! pattern-matching, and this is the basis for what follows.
61 //!
62 //! Some of the ctors listed above might feel weird: `None` and `2` don't take any arguments.
63 //! That's ok: those are ctors that take a list of 0 arguments; they are the simplest case of
64 //! ctors. We treat `2` as a ctor because `u64` and other number types behave exactly like a huge
65 //! `enum`, with one variant for each number. This allows us to see any matcheable value as made up
66 //! from a tree of ctors, each having a set number of children. For example: `Foo { bar: None,
67 //! baz: Ok(0) }` is made from 4 different ctors, namely `Foo{..}`, `None`, `Ok` and `0`.
68 //!
69 //! This idea can be extended to patterns: they are also made from constructors applied to fields.
70 //! A pattern for a given type is allowed to use all the ctors for values of that type (which we
71 //! call "value constructors"), but there are also pattern-only ctors. The most important one is
72 //! the wildcard (`_`), and the others are integer ranges (`0..=10`), variable-length slices (`[x,
73 //! ..]`), and or-patterns (`Ok(0) | Err(_)`). Examples of valid patterns are `42`, `Some(_)`, `Foo
74 //! { bar: Some(0) | None, baz: _ }`. Note that a binder in a pattern (e.g. `Some(x)`) matches the
75 //! same values as a wildcard (e.g. `Some(_)`), so we treat both as wildcards.
76 //!
77 //! From this deconstruction we can compute whether a given value matches a given pattern; we
78 //! simply look at ctors one at a time. Given a pattern `p` and a value `v`, we want to compute
79 //! `matches!(v, p)`. It's mostly straightforward: we compare the head ctors and when they match
80 //! we compare their fields recursively. A few representative examples:
81 //!
82 //! - `matches!(v, _) := true`
83 //! - `matches!((v0,  v1), (p0,  p1)) := matches!(v0, p0) && matches!(v1, p1)`
84 //! - `matches!(Foo { bar: v0, baz: v1 }, Foo { bar: p0, baz: p1 }) := matches!(v0, p0) && matches!(v1, p1)`
85 //! - `matches!(Ok(v0), Ok(p0)) := matches!(v0, p0)`
86 //! - `matches!(Ok(v0), Err(p0)) := false` (incompatible variants)
87 //! - `matches!(v, 1..=100) := matches!(v, 1) || ... || matches!(v, 100)`
88 //! - `matches!([v0], [p0, .., p1]) := false` (incompatible lengths)
89 //! - `matches!([v0, v1, v2], [p0, .., p1]) := matches!(v0, p0) && matches!(v2, p1)`
90 //! - `matches!(v, p0 | p1) := matches!(v, p0) || matches!(v, p1)`
91 //!
92 //! Constructors, fields and relevant operations are defined in the [`super::deconstruct_pat`] module.
93 //!
94 //! Note: this constructors/fields distinction may not straightforwardly apply to every Rust type.
95 //! For example a value of type `Rc<u64>` can't be deconstructed that way, and `&str` has an
96 //! infinitude of constructors. There are also subtleties with visibility of fields and
97 //! uninhabitedness and various other things. The constructors idea can be extended to handle most
98 //! of these subtleties though; caveats are documented where relevant throughout the code.
99 //!
100 //! Whether constructors cover each other is computed by [`Constructor::is_covered_by`].
101 //!
102 //!
103 //! # Specialization
104 //!
105 //! Recall that we wish to compute `usefulness(p_1 .. p_n, q)`: given a list of patterns `p_1 ..
106 //! p_n` and a pattern `q`, all of the same type, we want to find a list of values (called
107 //! "witnesses") that are matched by `q` and by none of the `p_i`. We obviously don't just
108 //! enumerate all possible values. From the discussion above we see that we can proceed
109 //! ctor-by-ctor: for each value ctor of the given type, we ask "is there a value that starts with
110 //! this constructor and matches `q` and none of the `p_i`?". As we saw above, there's a lot we can
111 //! say from knowing only the first constructor of our candidate value.
112 //!
113 //! Let's take the following example:
114 //! ```
115 //! match x {
116 //!     Enum::Variant1(_) => {} // `p1`
117 //!     Enum::Variant2(None, 0) => {} // `p2`
118 //!     Enum::Variant2(Some(_), 0) => {} // `q`
119 //! }
120 //! ```
121 //!
122 //! We can easily see that if our candidate value `v` starts with `Variant1` it will not match `q`.
123 //! If `v = Variant2(v0, v1)` however, whether or not it matches `p2` and `q` will depend on `v0`
124 //! and `v1`. In fact, such a `v` will be a witness of usefulness of `q` exactly when the tuple
125 //! `(v0, v1)` is a witness of usefulness of `q'` in the following reduced match:
126 //!
127 //! ```
128 //! match x {
129 //!     (None, 0) => {} // `p2'`
130 //!     (Some(_), 0) => {} // `q'`
131 //! }
132 //! ```
133 //!
134 //! This motivates a new step in computing usefulness, that we call _specialization_.
135 //! Specialization consist of filtering a list of patterns for those that match a constructor, and
136 //! then looking into the constructor's fields. This enables usefulness to be computed recursively.
137 //!
138 //! Instead of acting on a single pattern in each row, we will consider a list of patterns for each
139 //! row, and we call such a list a _pattern-stack_. The idea is that we will specialize the
140 //! leftmost pattern, which amounts to popping the constructor and pushing its fields, which feels
141 //! like a stack. We note a pattern-stack simply with `[p_1 ... p_n]`.
142 //! Here's a sequence of specializations of a list of pattern-stacks, to illustrate what's
143 //! happening:
144 //! ```
145 //! [Enum::Variant1(_)]
146 //! [Enum::Variant2(None, 0)]
147 //! [Enum::Variant2(Some(_), 0)]
148 //! //==>> specialize with `Variant2`
149 //! [None, 0]
150 //! [Some(_), 0]
151 //! //==>> specialize with `Some`
152 //! [_, 0]
153 //! //==>> specialize with `true` (say the type was `bool`)
154 //! [0]
155 //! //==>> specialize with `0`
156 //! []
157 //! ```
158 //!
159 //! The function `specialize(c, p)` takes a value constructor `c` and a pattern `p`, and returns 0
160 //! or more pattern-stacks. If `c` does not match the head constructor of `p`, it returns nothing;
161 //! otherwise if returns the fields of the constructor. This only returns more than one
162 //! pattern-stack if `p` has a pattern-only constructor.
163 //!
164 //! - Specializing for the wrong constructor returns nothing
165 //!
166 //!   `specialize(None, Some(p0)) := []`
167 //!
168 //! - Specializing for the correct constructor returns a single row with the fields
169 //!
170 //!   `specialize(Variant1, Variant1(p0, p1, p2)) := [[p0, p1, p2]]`
171 //!
172 //!   `specialize(Foo{..}, Foo { bar: p0, baz: p1 }) := [[p0, p1]]`
173 //!
174 //! - For or-patterns, we specialize each branch and concatenate the results
175 //!
176 //!   `specialize(c, p0 | p1) := specialize(c, p0) ++ specialize(c, p1)`
177 //!
178 //! - We treat the other pattern constructors as if they were a large or-pattern of all the
179 //!   possibilities:
180 //!
181 //!   `specialize(c, _) := specialize(c, Variant1(_) | Variant2(_, _) | ...)`
182 //!
183 //!   `specialize(c, 1..=100) := specialize(c, 1 | ... | 100)`
184 //!
185 //!   `specialize(c, [p0, .., p1]) := specialize(c, [p0, p1] | [p0, _, p1] | [p0, _, _, p1] | ...)`
186 //!
187 //! - If `c` is a pattern-only constructor, `specialize` is defined on a case-by-case basis. See
188 //!   the discussion about constructor splitting in [`super::deconstruct_pat`].
189 //!
190 //!
191 //! We then extend this function to work with pattern-stacks as input, by acting on the first
192 //! column and keeping the other columns untouched.
193 //!
194 //! Specialization for the whole matrix is done in [`Matrix::specialize_constructor`]. Note that
195 //! or-patterns in the first column are expanded before being stored in the matrix. Specialization
196 //! for a single patstack is done from a combination of [`Constructor::is_covered_by`] and
197 //! [`PatStack::pop_head_constructor`]. The internals of how it's done mostly live in the
198 //! [`Fields`] struct.
199 //!
200 //!
201 //! # Computing usefulness
202 //!
203 //! We now have all we need to compute usefulness. The inputs to usefulness are a list of
204 //! pattern-stacks `p_1 ... p_n` (one per row), and a new pattern_stack `q`. The paper and this
205 //! file calls the list of patstacks a _matrix_. They must all have the same number of columns and
206 //! the patterns in a given column must all have the same type. `usefulness` returns a (possibly
207 //! empty) list of witnesses of usefulness. These witnesses will also be pattern-stacks.
208 //!
209 //! - base case: `n_columns == 0`.
210 //!     Since a pattern-stack functions like a tuple of patterns, an empty one functions like the
211 //!     unit type. Thus `q` is useful iff there are no rows above it, i.e. if `n == 0`.
212 //!
213 //! - inductive case: `n_columns > 0`.
214 //!     We need a way to list the constructors we want to try. We will be more clever in the next
215 //!     section but for now assume we list all value constructors for the type of the first column.
216 //!
217 //!     - for each such ctor `c`:
218 //!
219 //!         - for each `q'` returned by `specialize(c, q)`:
220 //!
221 //!             - we compute `usefulness(specialize(c, p_1) ... specialize(c, p_n), q')`
222 //!
223 //!         - for each witness found, we revert specialization by pushing the constructor `c` on top.
224 //!
225 //!     - We return the concatenation of all the witnesses found, if any.
226 //!
227 //! Example:
228 //! ```
229 //! [Some(true)] // p_1
230 //! [None] // p_2
231 //! [Some(_)] // q
232 //! //==>> try `None`: `specialize(None, q)` returns nothing
233 //! //==>> try `Some`: `specialize(Some, q)` returns a single row
234 //! [true] // p_1'
235 //! [_] // q'
236 //! //==>> try `true`: `specialize(true, q')` returns a single row
237 //! [] // p_1''
238 //! [] // q''
239 //! //==>> base case; `n != 0` so `q''` is not useful.
240 //! //==>> go back up a step
241 //! [true] // p_1'
242 //! [_] // q'
243 //! //==>> try `false`: `specialize(false, q')` returns a single row
244 //! [] // q''
245 //! //==>> base case; `n == 0` so `q''` is useful. We return the single witness `[]`
246 //! witnesses:
247 //! []
248 //! //==>> undo the specialization with `false`
249 //! witnesses:
250 //! [false]
251 //! //==>> undo the specialization with `Some`
252 //! witnesses:
253 //! [Some(false)]
254 //! //==>> we have tried all the constructors. The output is the single witness `[Some(false)]`.
255 //! ```
256 //!
257 //! This computation is done in [`is_useful`]. In practice we don't care about the list of
258 //! witnesses when computing reachability; we only need to know whether any exist. We do keep the
259 //! witnesses when computing exhaustiveness to report them to the user.
260 //!
261 //!
262 //! # Making usefulness tractable: constructor splitting
263 //!
264 //! We're missing one last detail: which constructors do we list? Naively listing all value
265 //! constructors cannot work for types like `u64` or `&str`, so we need to be more clever. The
266 //! first obvious insight is that we only want to list constructors that are covered by the head
267 //! constructor of `q`. If it's a value constructor, we only try that one. If it's a pattern-only
268 //! constructor, we use the final clever idea for this algorithm: _constructor splitting_, where we
269 //! group together constructors that behave the same.
270 //!
271 //! The details are not necessary to understand this file, so we explain them in
272 //! [`super::deconstruct_pat`]. Splitting is done by the [`Constructor::split`] function.
273
274 use std::iter::once;
275
276 use hir_def::{AdtId, DefWithBodyId, HasModule, ModuleId};
277 use smallvec::{smallvec, SmallVec};
278 use typed_arena::Arena;
279
280 use crate::{db::HirDatabase, Ty, TyExt};
281
282 use super::deconstruct_pat::{Constructor, DeconstructedPat, Fields, SplitWildcard};
283
284 use self::{helper::Captures, ArmType::*, Usefulness::*};
285
286 pub(crate) struct MatchCheckCtx<'a, 'p> {
287     pub(crate) module: ModuleId,
288     pub(crate) body: DefWithBodyId,
289     pub(crate) db: &'a dyn HirDatabase,
290     /// Lowered patterns from arms plus generated by the check.
291     pub(crate) pattern_arena: &'p Arena<DeconstructedPat<'p>>,
292 }
293
294 impl<'a, 'p> MatchCheckCtx<'a, 'p> {
295     pub(super) fn is_uninhabited(&self, _ty: &Ty) -> bool {
296         // FIXME(iDawer) implement exhaustive_patterns feature. More info in:
297         // Tracking issue for RFC 1872: exhaustive_patterns feature https://github.com/rust-lang/rust/issues/51085
298         false
299     }
300
301     /// Returns whether the given type is an enum from another crate declared `#[non_exhaustive]`.
302     pub(super) fn is_foreign_non_exhaustive_enum(&self, ty: &Ty) -> bool {
303         match ty.as_adt() {
304             Some((adt @ AdtId::EnumId(_), _)) => {
305                 let has_non_exhaustive_attr =
306                     self.db.attrs(adt.into()).by_key("non_exhaustive").exists();
307                 let is_local = adt.module(self.db.upcast()).krate() == self.module.krate();
308                 has_non_exhaustive_attr && !is_local
309             }
310             _ => false,
311         }
312     }
313
314     // Rust feature described as "Allows exhaustive pattern matching on types that contain uninhabited types."
315     pub(super) fn feature_exhaustive_patterns(&self) -> bool {
316         // FIXME see MatchCheckCtx::is_uninhabited
317         false
318     }
319 }
320
321 #[derive(Copy, Clone)]
322 pub(super) struct PatCtxt<'a, 'p> {
323     pub(super) cx: &'a MatchCheckCtx<'a, 'p>,
324     /// Type of the current column under investigation.
325     pub(super) ty: &'a Ty,
326     /// Whether the current pattern is the whole pattern as found in a match arm, or if it's a
327     /// subpattern.
328     pub(super) is_top_level: bool,
329     /// Wether the current pattern is from a `non_exhaustive` enum.
330     pub(super) is_non_exhaustive: bool,
331 }
332
333 /// A row of a matrix. Rows of len 1 are very common, which is why `SmallVec[_; 2]`
334 /// works well.
335 #[derive(Clone)]
336 pub(super) struct PatStack<'p> {
337     pats: SmallVec<[&'p DeconstructedPat<'p>; 2]>,
338 }
339
340 impl<'p> PatStack<'p> {
341     fn from_pattern(pat: &'p DeconstructedPat<'p>) -> Self {
342         Self::from_vec(smallvec![pat])
343     }
344
345     fn from_vec(vec: SmallVec<[&'p DeconstructedPat<'p>; 2]>) -> Self {
346         PatStack { pats: vec }
347     }
348
349     fn is_empty(&self) -> bool {
350         self.pats.is_empty()
351     }
352
353     fn len(&self) -> usize {
354         self.pats.len()
355     }
356
357     fn head(&self) -> &'p DeconstructedPat<'p> {
358         self.pats[0]
359     }
360
361     // Recursively expand the first pattern into its subpatterns. Only useful if the pattern is an
362     // or-pattern. Panics if `self` is empty.
363     fn expand_or_pat(&self) -> impl Iterator<Item = PatStack<'p>> + Captures<'_> {
364         self.head().iter_fields().map(move |pat| {
365             let mut new_patstack = PatStack::from_pattern(pat);
366             new_patstack.pats.extend_from_slice(&self.pats[1..]);
367             new_patstack
368         })
369     }
370
371     /// This computes `S(self.head().ctor(), self)`. See top of the file for explanations.
372     ///
373     /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
374     /// fields filled with wild patterns.
375     ///
376     /// This is roughly the inverse of `Constructor::apply`.
377     fn pop_head_constructor(&self, cx: &MatchCheckCtx<'_, 'p>, ctor: &Constructor) -> PatStack<'p> {
378         // We pop the head pattern and push the new fields extracted from the arguments of
379         // `self.head()`.
380         let mut new_fields: SmallVec<[_; 2]> = self.head().specialize(cx, ctor);
381         new_fields.extend_from_slice(&self.pats[1..]);
382         PatStack::from_vec(new_fields)
383     }
384 }
385
386 /// A 2D matrix.
387 #[derive(Clone)]
388 pub(super) struct Matrix<'p> {
389     patterns: Vec<PatStack<'p>>,
390 }
391
392 impl<'p> Matrix<'p> {
393     fn empty() -> Self {
394         Matrix { patterns: vec![] }
395     }
396
397     /// Number of columns of this matrix. `None` is the matrix is empty.
398     pub(super) fn _column_count(&self) -> Option<usize> {
399         self.patterns.get(0).map(|r| r.len())
400     }
401
402     /// Pushes a new row to the matrix. If the row starts with an or-pattern, this recursively
403     /// expands it.
404     fn push(&mut self, row: PatStack<'p>) {
405         if !row.is_empty() && row.head().is_or_pat() {
406             self.patterns.extend(row.expand_or_pat());
407         } else {
408             self.patterns.push(row);
409         }
410     }
411
412     /// Iterate over the first component of each row
413     fn heads(&self) -> impl Iterator<Item = &'p DeconstructedPat<'p>> + Clone + Captures<'_> {
414         self.patterns.iter().map(|r| r.head())
415     }
416
417     /// This computes `S(constructor, self)`. See top of the file for explanations.
418     fn specialize_constructor(&self, pcx: PatCtxt<'_, 'p>, ctor: &Constructor) -> Matrix<'p> {
419         let mut matrix = Matrix::empty();
420         for row in &self.patterns {
421             if ctor.is_covered_by(pcx, row.head().ctor()) {
422                 let new_row = row.pop_head_constructor(pcx.cx, ctor);
423                 matrix.push(new_row);
424             }
425         }
426         matrix
427     }
428 }
429
430 /// This carries the results of computing usefulness, as described at the top of the file. When
431 /// checking usefulness of a match branch, we use the `NoWitnesses` variant, which also keeps track
432 /// of potential unreachable sub-patterns (in the presence of or-patterns). When checking
433 /// exhaustiveness of a whole match, we use the `WithWitnesses` variant, which carries a list of
434 /// witnesses of non-exhaustiveness when there are any.
435 /// Which variant to use is dictated by `ArmType`.
436 enum Usefulness<'p> {
437     /// If we don't care about witnesses, simply remember if the pattern was useful.
438     NoWitnesses { useful: bool },
439     /// Carries a list of witnesses of non-exhaustiveness. If empty, indicates that the whole
440     /// pattern is unreachable.
441     WithWitnesses(Vec<Witness<'p>>),
442 }
443
444 impl<'p> Usefulness<'p> {
445     fn new_useful(preference: ArmType) -> Self {
446         match preference {
447             // A single (empty) witness of reachability.
448             FakeExtraWildcard => WithWitnesses(vec![Witness(vec![])]),
449             RealArm => NoWitnesses { useful: true },
450         }
451     }
452     fn new_not_useful(preference: ArmType) -> Self {
453         match preference {
454             FakeExtraWildcard => WithWitnesses(vec![]),
455             RealArm => NoWitnesses { useful: false },
456         }
457     }
458
459     fn is_useful(&self) -> bool {
460         match self {
461             Usefulness::NoWitnesses { useful } => *useful,
462             Usefulness::WithWitnesses(witnesses) => !witnesses.is_empty(),
463         }
464     }
465
466     /// Combine usefulnesses from two branches. This is an associative operation.
467     fn extend(&mut self, other: Self) {
468         match (&mut *self, other) {
469             (WithWitnesses(_), WithWitnesses(o)) if o.is_empty() => {}
470             (WithWitnesses(s), WithWitnesses(o)) if s.is_empty() => *self = WithWitnesses(o),
471             (WithWitnesses(s), WithWitnesses(o)) => s.extend(o),
472             (NoWitnesses { useful: s_useful }, NoWitnesses { useful: o_useful }) => {
473                 *s_useful = *s_useful || o_useful
474             }
475             _ => unreachable!(),
476         }
477     }
478
479     /// After calculating usefulness after a specialization, call this to reconstruct a usefulness
480     /// that makes sense for the matrix pre-specialization. This new usefulness can then be merged
481     /// with the results of specializing with the other constructors.
482     fn apply_constructor(
483         self,
484         pcx: PatCtxt<'_, 'p>,
485         matrix: &Matrix<'p>,
486         ctor: &Constructor,
487     ) -> Self {
488         match self {
489             NoWitnesses { .. } => self,
490             WithWitnesses(ref witnesses) if witnesses.is_empty() => self,
491             WithWitnesses(witnesses) => {
492                 let new_witnesses = if let Constructor::Missing { .. } = ctor {
493                     // We got the special `Missing` constructor, so each of the missing constructors
494                     // gives a new pattern that is not caught by the match. We list those patterns.
495                     let new_patterns = if pcx.is_non_exhaustive {
496                         // Here we don't want the user to try to list all variants, we want them to add
497                         // a wildcard, so we only suggest that.
498                         vec![DeconstructedPat::wildcard(pcx.ty.clone())]
499                     } else {
500                         let mut split_wildcard = SplitWildcard::new(pcx);
501                         split_wildcard.split(pcx, matrix.heads().map(DeconstructedPat::ctor));
502
503                         // This lets us know if we skipped any variants because they are marked
504                         // `doc(hidden)` or they are unstable feature gate (only stdlib types).
505                         let mut hide_variant_show_wild = false;
506                         // Construct for each missing constructor a "wild" version of this
507                         // constructor, that matches everything that can be built with
508                         // it. For example, if `ctor` is a `Constructor::Variant` for
509                         // `Option::Some`, we get the pattern `Some(_)`.
510                         let mut new: Vec<DeconstructedPat<'_>> = split_wildcard
511                             .iter_missing(pcx)
512                             .filter_map(|missing_ctor| {
513                                 // Check if this variant is marked `doc(hidden)`
514                                 if missing_ctor.is_doc_hidden_variant(pcx)
515                                     || missing_ctor.is_unstable_variant(pcx)
516                                 {
517                                     hide_variant_show_wild = true;
518                                     return None;
519                                 }
520                                 Some(DeconstructedPat::wild_from_ctor(pcx, missing_ctor.clone()))
521                             })
522                             .collect();
523
524                         if hide_variant_show_wild {
525                             new.push(DeconstructedPat::wildcard(pcx.ty.clone()))
526                         }
527
528                         new
529                     };
530
531                     witnesses
532                         .into_iter()
533                         .flat_map(|witness| {
534                             new_patterns.iter().map(move |pat| {
535                                 Witness(
536                                     witness
537                                         .0
538                                         .iter()
539                                         .chain(once(pat))
540                                         .map(DeconstructedPat::clone_and_forget_reachability)
541                                         .collect(),
542                                 )
543                             })
544                         })
545                         .collect()
546                 } else {
547                     witnesses
548                         .into_iter()
549                         .map(|witness| witness.apply_constructor(pcx, ctor))
550                         .collect()
551                 };
552                 WithWitnesses(new_witnesses)
553             }
554         }
555     }
556 }
557
558 #[derive(Copy, Clone, Debug)]
559 enum ArmType {
560     FakeExtraWildcard,
561     RealArm,
562 }
563
564 /// A witness of non-exhaustiveness for error reporting, represented
565 /// as a list of patterns (in reverse order of construction) with
566 /// wildcards inside to represent elements that can take any inhabitant
567 /// of the type as a value.
568 ///
569 /// A witness against a list of patterns should have the same types
570 /// and length as the pattern matched against. Because Rust `match`
571 /// is always against a single pattern, at the end the witness will
572 /// have length 1, but in the middle of the algorithm, it can contain
573 /// multiple patterns.
574 ///
575 /// For example, if we are constructing a witness for the match against
576 ///
577 /// ```
578 /// struct Pair(Option<(u32, u32)>, bool);
579 ///
580 /// match (p: Pair) {
581 ///    Pair(None, _) => {}
582 ///    Pair(_, false) => {}
583 /// }
584 /// ```
585 ///
586 /// We'll perform the following steps:
587 /// 1. Start with an empty witness
588 ///     `Witness(vec![])`
589 /// 2. Push a witness `true` against the `false`
590 ///     `Witness(vec![true])`
591 /// 3. Push a witness `Some(_)` against the `None`
592 ///     `Witness(vec![true, Some(_)])`
593 /// 4. Apply the `Pair` constructor to the witnesses
594 ///     `Witness(vec![Pair(Some(_), true)])`
595 ///
596 /// The final `Pair(Some(_), true)` is then the resulting witness.
597 pub(crate) struct Witness<'p>(Vec<DeconstructedPat<'p>>);
598
599 impl<'p> Witness<'p> {
600     /// Asserts that the witness contains a single pattern, and returns it.
601     fn single_pattern(self) -> DeconstructedPat<'p> {
602         assert_eq!(self.0.len(), 1);
603         self.0.into_iter().next().unwrap()
604     }
605
606     /// Constructs a partial witness for a pattern given a list of
607     /// patterns expanded by the specialization step.
608     ///
609     /// When a pattern P is discovered to be useful, this function is used bottom-up
610     /// to reconstruct a complete witness, e.g., a pattern P' that covers a subset
611     /// of values, V, where each value in that set is not covered by any previously
612     /// used patterns and is covered by the pattern P'. Examples:
613     ///
614     /// left_ty: tuple of 3 elements
615     /// pats: [10, 20, _]           => (10, 20, _)
616     ///
617     /// left_ty: struct X { a: (bool, &'static str), b: usize}
618     /// pats: [(false, "foo"), 42]  => X { a: (false, "foo"), b: 42 }
619     fn apply_constructor(mut self, pcx: PatCtxt<'_, 'p>, ctor: &Constructor) -> Self {
620         let pat = {
621             let len = self.0.len();
622             let arity = ctor.arity(pcx);
623             let pats = self.0.drain((len - arity)..).rev();
624             let fields = Fields::from_iter(pcx.cx, pats);
625             DeconstructedPat::new(ctor.clone(), fields, pcx.ty.clone())
626         };
627
628         self.0.push(pat);
629
630         self
631     }
632 }
633
634 /// Algorithm from <http://moscova.inria.fr/~maranget/papers/warn/index.html>.
635 /// The algorithm from the paper has been modified to correctly handle empty
636 /// types. The changes are:
637 ///   (0) We don't exit early if the pattern matrix has zero rows. We just
638 ///       continue to recurse over columns.
639 ///   (1) all_constructors will only return constructors that are statically
640 ///       possible. E.g., it will only return `Ok` for `Result<T, !>`.
641 ///
642 /// This finds whether a (row) vector `v` of patterns is 'useful' in relation
643 /// to a set of such vectors `m` - this is defined as there being a set of
644 /// inputs that will match `v` but not any of the sets in `m`.
645 ///
646 /// All the patterns at each column of the `matrix ++ v` matrix must have the same type.
647 ///
648 /// This is used both for reachability checking (if a pattern isn't useful in
649 /// relation to preceding patterns, it is not reachable) and exhaustiveness
650 /// checking (if a wildcard pattern is useful in relation to a matrix, the
651 /// matrix isn't exhaustive).
652 ///
653 /// `is_under_guard` is used to inform if the pattern has a guard. If it
654 /// has one it must not be inserted into the matrix. This shouldn't be
655 /// relied on for soundness.
656 fn is_useful<'p>(
657     cx: &MatchCheckCtx<'_, 'p>,
658     matrix: &Matrix<'p>,
659     v: &PatStack<'p>,
660     witness_preference: ArmType,
661     is_under_guard: bool,
662     is_top_level: bool,
663 ) -> Usefulness<'p> {
664     let Matrix { patterns: rows, .. } = matrix;
665
666     // The base case. We are pattern-matching on () and the return value is
667     // based on whether our matrix has a row or not.
668     // NOTE: This could potentially be optimized by checking rows.is_empty()
669     // first and then, if v is non-empty, the return value is based on whether
670     // the type of the tuple we're checking is inhabited or not.
671     if v.is_empty() {
672         let ret = if rows.is_empty() {
673             Usefulness::new_useful(witness_preference)
674         } else {
675             Usefulness::new_not_useful(witness_preference)
676         };
677         return ret;
678     }
679
680     debug_assert!(rows.iter().all(|r| r.len() == v.len()));
681
682     let ty = v.head().ty();
683     let is_non_exhaustive = cx.is_foreign_non_exhaustive_enum(ty);
684     let pcx = PatCtxt { cx, ty, is_top_level, is_non_exhaustive };
685
686     // If the first pattern is an or-pattern, expand it.
687     let mut ret = Usefulness::new_not_useful(witness_preference);
688     if v.head().is_or_pat() {
689         // We try each or-pattern branch in turn.
690         let mut matrix = matrix.clone();
691         for v in v.expand_or_pat() {
692             let usefulness = is_useful(cx, &matrix, &v, witness_preference, is_under_guard, false);
693             ret.extend(usefulness);
694             // If pattern has a guard don't add it to the matrix.
695             if !is_under_guard {
696                 // We push the already-seen patterns into the matrix in order to detect redundant
697                 // branches like `Some(_) | Some(0)`.
698                 matrix.push(v);
699             }
700         }
701     } else {
702         let v_ctor = v.head().ctor();
703
704         // FIXME: implement `overlapping_range_endpoints` lint
705
706         // We split the head constructor of `v`.
707         let split_ctors = v_ctor.split(pcx, matrix.heads().map(DeconstructedPat::ctor));
708         // For each constructor, we compute whether there's a value that starts with it that would
709         // witness the usefulness of `v`.
710         let start_matrix = matrix;
711         for ctor in split_ctors {
712             // We cache the result of `Fields::wildcards` because it is used a lot.
713             let spec_matrix = start_matrix.specialize_constructor(pcx, &ctor);
714             let v = v.pop_head_constructor(cx, &ctor);
715             let usefulness =
716                 is_useful(cx, &spec_matrix, &v, witness_preference, is_under_guard, false);
717             let usefulness = usefulness.apply_constructor(pcx, start_matrix, &ctor);
718
719             // FIXME: implement `non_exhaustive_omitted_patterns` lint
720
721             ret.extend(usefulness);
722         }
723     };
724
725     if ret.is_useful() {
726         v.head().set_reachable();
727     }
728
729     ret
730 }
731
732 /// The arm of a match expression.
733 #[derive(Clone, Copy)]
734 pub(crate) struct MatchArm<'p> {
735     pub(crate) pat: &'p DeconstructedPat<'p>,
736     pub(crate) has_guard: bool,
737 }
738
739 /// Indicates whether or not a given arm is reachable.
740 #[derive(Clone, Debug)]
741 pub(crate) enum Reachability {
742     /// The arm is reachable. This additionally carries a set of or-pattern branches that have been
743     /// found to be unreachable despite the overall arm being reachable. Used only in the presence
744     /// of or-patterns, otherwise it stays empty.
745     // FIXME: store ureachable subpattern IDs
746     Reachable,
747     /// The arm is unreachable.
748     Unreachable,
749 }
750
751 /// The output of checking a match for exhaustiveness and arm reachability.
752 pub(crate) struct UsefulnessReport<'p> {
753     /// For each arm of the input, whether that arm is reachable after the arms above it.
754     pub(crate) _arm_usefulness: Vec<(MatchArm<'p>, Reachability)>,
755     /// If the match is exhaustive, this is empty. If not, this contains witnesses for the lack of
756     /// exhaustiveness.
757     pub(crate) non_exhaustiveness_witnesses: Vec<DeconstructedPat<'p>>,
758 }
759
760 /// The entrypoint for the usefulness algorithm. Computes whether a match is exhaustive and which
761 /// of its arms are reachable.
762 ///
763 /// Note: the input patterns must have been lowered through
764 /// `check_match::MatchVisitor::lower_pattern`.
765 pub(crate) fn compute_match_usefulness<'p>(
766     cx: &MatchCheckCtx<'_, 'p>,
767     arms: &[MatchArm<'p>],
768     scrut_ty: &Ty,
769 ) -> UsefulnessReport<'p> {
770     let mut matrix = Matrix::empty();
771     let arm_usefulness = arms
772         .iter()
773         .copied()
774         .map(|arm| {
775             let v = PatStack::from_pattern(arm.pat);
776             is_useful(cx, &matrix, &v, RealArm, arm.has_guard, true);
777             if !arm.has_guard {
778                 matrix.push(v);
779             }
780             let reachability = if arm.pat.is_reachable() {
781                 Reachability::Reachable
782             } else {
783                 Reachability::Unreachable
784             };
785             (arm, reachability)
786         })
787         .collect();
788
789     let wild_pattern = cx.pattern_arena.alloc(DeconstructedPat::wildcard(scrut_ty.clone()));
790     let v = PatStack::from_pattern(wild_pattern);
791     let usefulness = is_useful(cx, &matrix, &v, FakeExtraWildcard, false, true);
792     let non_exhaustiveness_witnesses = match usefulness {
793         WithWitnesses(pats) => pats.into_iter().map(Witness::single_pattern).collect(),
794         NoWitnesses { .. } => panic!("bug"),
795     };
796     UsefulnessReport { _arm_usefulness: arm_usefulness, non_exhaustiveness_witnesses }
797 }
798
799 pub(crate) mod helper {
800     // Copy-pasted from rust/compiler/rustc_data_structures/src/captures.rs
801     /// "Signaling" trait used in impl trait to tag lifetimes that you may
802     /// need to capture but don't really need for other reasons.
803     /// Basically a workaround; see [this comment] for details.
804     ///
805     /// [this comment]: https://github.com/rust-lang/rust/issues/34511#issuecomment-373423999
806     // FIXME(eddyb) false positive, the lifetime parameter is "phantom" but needed.
807     #[allow(unused_lifetimes)]
808     pub(crate) trait Captures<'a> {}
809
810     impl<'a, T: ?Sized> Captures<'a> for T {}
811 }