]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_mir_build/src/thir/pattern/usefulness.rs
New upstream version 1.74.1+dfsg1
[rustc.git] / compiler / rustc_mir_build / src / thir / pattern / usefulness.rs
CommitLineData
fc512014
XL
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
04454e1e 38//! # fn foo(x: Option<i32>) {
fc512014 39//! match x {
04454e1e
FG
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
fc512014 44//! }
04454e1e 45//! # }
fc512014
XL
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.
04454e1e
FG
51//! ```compile_fail,E0004
52//! # fn foo(x: Option<i32>) {
fc512014 53//! match x {
04454e1e
FG
54//! Some(0) => {},
55//! None => {},
fc512014
XL
56//! // not exhaustive: `_` is useful because it matches `Some(1)`
57//! }
04454e1e 58//! # }
fc512014
XL
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//!
5e7ed085 69//! The idea that powers everything that is done in this file is the following: a (matchable)
fc512014
XL
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
5e7ed085 78//! `enum`, with one variant for each number. This allows us to see any matchable value as made up
fc512014
XL
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:
04454e1e
FG
127//! ```compile_fail,E0004
128//! # enum Enum { Variant1(()), Variant2(Option<bool>, u32)}
129//! # fn foo(x: Enum) {
fc512014
XL
130//! match x {
131//! Enum::Variant1(_) => {} // `p1`
132//! Enum::Variant2(None, 0) => {} // `p2`
133//! Enum::Variant2(Some(_), 0) => {} // `q`
134//! }
04454e1e 135//! # }
fc512014
XL
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//!
04454e1e
FG
143//! ```compile_fail,E0004
144//! # fn foo(x: (Option<bool>, u32)) {
fc512014
XL
145//! match x {
146//! (None, 0) => {} // `p2'`
147//! (Some(_), 0) => {} // `q'`
148//! }
04454e1e 149//! # }
fc512014
XL
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:
04454e1e 162//! ```ignore (illustrative)
fc512014
XL
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:
04454e1e 246//! ```ignore (illustrative)
fc512014
XL
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.
49aad941
FG
291//!
292//! # Constants in patterns
293//!
294//! There are two kinds of constants in patterns:
295//!
296//! * literals (`1`, `true`, `"foo"`)
297//! * named or inline consts (`FOO`, `const { 5 + 6 }`)
298//!
299//! The latter are converted into other patterns with literals at the leaves. For example
300//! `const_to_pat(const { [1, 2, 3] })` becomes an `Array(vec![Const(1), Const(2), Const(3)])`
301//! pattern. This gets problematic when comparing the constant via `==` would behave differently
302//! from matching on the constant converted to a pattern. Situations like that can occur, when
303//! the user implements `PartialEq` manually, and thus could make `==` behave arbitrarily different.
304//! In order to honor the `==` implementation, constants of types that implement `PartialEq` manually
305//! stay as a full constant and become an `Opaque` pattern. These `Opaque` patterns do not participate
306//! in exhaustiveness, specialization or overlap checking.
fc512014 307
c295e0f8 308use self::ArmType::*;
fc512014 309use self::Usefulness::*;
c295e0f8 310use super::deconstruct_pat::{Constructor, DeconstructedPat, Fields, SplitWildcard};
9c376795 311use crate::errors::{NonExhaustiveOmittedPattern, Uncovered};
fc512014
XL
312
313use rustc_data_structures::captures::Captures;
fc512014
XL
314
315use rustc_arena::TypedArena;
3c0e092e 316use rustc_data_structures::stack::ensure_sufficient_stack;
fc512014
XL
317use rustc_hir::def_id::DefId;
318use rustc_hir::HirId;
319use rustc_middle::ty::{self, Ty, TyCtxt};
c295e0f8
XL
320use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS;
321use rustc_span::{Span, DUMMY_SP};
fc512014
XL
322
323use smallvec::{smallvec, SmallVec};
324use std::fmt;
c295e0f8 325use std::iter::once;
fc512014 326
923072b8
FG
327pub(crate) struct MatchCheckCtxt<'p, 'tcx> {
328 pub(crate) tcx: TyCtxt<'tcx>,
fc512014
XL
329 /// The module in which the match occurs. This is necessary for
330 /// checking inhabited-ness of types because whether a type is (visibly)
331 /// inhabited can depend on whether it was defined in the current module or
332 /// not. E.g., `struct Foo { _private: ! }` cannot be seen to be empty
333 /// outside its module and should not be matchable with an empty match statement.
923072b8
FG
334 pub(crate) module: DefId,
335 pub(crate) param_env: ty::ParamEnv<'tcx>,
336 pub(crate) pattern_arena: &'p TypedArena<DeconstructedPat<'p, 'tcx>>,
353b0b11
FG
337 /// Only produce `NON_EXHAUSTIVE_OMITTED_PATTERNS` lint on refutable patterns.
338 pub(crate) refutable: bool,
fc512014
XL
339}
340
341impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> {
342 pub(super) fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool {
343 if self.tcx.features().exhaustive_patterns {
487cf647 344 !ty.is_inhabited_from(self.tcx, self.module, self.param_env)
fc512014
XL
345 } else {
346 false
347 }
348 }
349
350 /// Returns whether the given type is an enum from another crate declared `#[non_exhaustive]`.
351 pub(super) fn is_foreign_non_exhaustive_enum(&self, ty: Ty<'tcx>) -> bool {
352 match ty.kind() {
353 ty::Adt(def, ..) => {
5e7ed085 354 def.is_enum() && def.is_variant_list_non_exhaustive() && !def.did().is_local()
fc512014
XL
355 }
356 _ => false,
357 }
358 }
359}
360
361#[derive(Copy, Clone)]
362pub(super) struct PatCtxt<'a, 'p, 'tcx> {
363 pub(super) cx: &'a MatchCheckCtxt<'p, 'tcx>,
364 /// Type of the current column under investigation.
365 pub(super) ty: Ty<'tcx>,
366 /// Span of the current pattern under investigation.
367 pub(super) span: Span,
368 /// Whether the current pattern is the whole pattern as found in a match arm, or if it's a
369 /// subpattern.
370 pub(super) is_top_level: bool,
5e7ed085 371 /// Whether the current pattern is from a `non_exhaustive` enum.
c295e0f8 372 pub(super) is_non_exhaustive: bool,
fc512014
XL
373}
374
6a06907d
XL
375impl<'a, 'p, 'tcx> fmt::Debug for PatCtxt<'a, 'p, 'tcx> {
376 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377 f.debug_struct("PatCtxt").field("ty", &self.ty).finish()
378 }
379}
380
fc512014
XL
381/// A row of a matrix. Rows of len 1 are very common, which is why `SmallVec[_; 2]`
382/// works well.
6a06907d 383#[derive(Clone)]
f2b60f7d
FG
384pub(crate) struct PatStack<'p, 'tcx> {
385 pub(crate) pats: SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]>,
fc512014
XL
386}
387
388impl<'p, 'tcx> PatStack<'p, 'tcx> {
c295e0f8 389 fn from_pattern(pat: &'p DeconstructedPat<'p, 'tcx>) -> Self {
fc512014
XL
390 Self::from_vec(smallvec![pat])
391 }
392
c295e0f8
XL
393 fn from_vec(vec: SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]>) -> Self {
394 PatStack { pats: vec }
fc512014
XL
395 }
396
397 fn is_empty(&self) -> bool {
398 self.pats.is_empty()
399 }
400
401 fn len(&self) -> usize {
402 self.pats.len()
403 }
404
c295e0f8 405 fn head(&self) -> &'p DeconstructedPat<'p, 'tcx> {
fc512014
XL
406 self.pats[0]
407 }
408
c295e0f8 409 fn iter(&self) -> impl Iterator<Item = &DeconstructedPat<'p, 'tcx>> {
fc512014
XL
410 self.pats.iter().copied()
411 }
412
6a06907d
XL
413 // Recursively expand the first pattern into its subpatterns. Only useful if the pattern is an
414 // or-pattern. Panics if `self` is empty.
415 fn expand_or_pat<'a>(&'a self) -> impl Iterator<Item = PatStack<'p, 'tcx>> + Captures<'a> {
c295e0f8 416 self.head().iter_fields().map(move |pat| {
6a06907d
XL
417 let mut new_patstack = PatStack::from_pattern(pat);
418 new_patstack.pats.extend_from_slice(&self.pats[1..]);
419 new_patstack
420 })
fc512014
XL
421 }
422
f2b60f7d
FG
423 // Recursively expand all patterns into their subpatterns and push each `PatStack` to matrix.
424 fn expand_and_extend<'a>(&'a self, matrix: &mut Matrix<'p, 'tcx>) {
425 if !self.is_empty() && self.head().is_or_pat() {
426 for pat in self.head().iter_fields() {
427 let mut new_patstack = PatStack::from_pattern(pat);
428 new_patstack.pats.extend_from_slice(&self.pats[1..]);
429 if !new_patstack.is_empty() && new_patstack.head().is_or_pat() {
430 new_patstack.expand_and_extend(matrix);
431 } else if !new_patstack.is_empty() {
432 matrix.push(new_patstack);
433 }
434 }
435 }
436 }
437
c295e0f8 438 /// This computes `S(self.head().ctor(), self)`. See top of the file for explanations.
fc512014
XL
439 ///
440 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
441 /// fields filled with wild patterns.
442 ///
443 /// This is roughly the inverse of `Constructor::apply`.
c295e0f8
XL
444 fn pop_head_constructor(
445 &self,
064997fb 446 pcx: &PatCtxt<'_, 'p, 'tcx>,
c295e0f8
XL
447 ctor: &Constructor<'tcx>,
448 ) -> PatStack<'p, 'tcx> {
fc512014
XL
449 // We pop the head pattern and push the new fields extracted from the arguments of
450 // `self.head()`.
064997fb 451 let mut new_fields: SmallVec<[_; 2]> = self.head().specialize(pcx, ctor);
fc512014
XL
452 new_fields.extend_from_slice(&self.pats[1..]);
453 PatStack::from_vec(new_fields)
454 }
455}
456
6a06907d
XL
457/// Pretty-printing for matrix row.
458impl<'p, 'tcx> fmt::Debug for PatStack<'p, 'tcx> {
459 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
460 write!(f, "+")?;
461 for pat in self.iter() {
add651ee 462 write!(f, " {pat:?} +")?;
6a06907d
XL
463 }
464 Ok(())
465 }
466}
467
fc512014 468/// A 2D matrix.
c295e0f8 469#[derive(Clone)]
fc512014 470pub(super) struct Matrix<'p, 'tcx> {
f2b60f7d 471 pub patterns: Vec<PatStack<'p, 'tcx>>,
fc512014
XL
472}
473
474impl<'p, 'tcx> Matrix<'p, 'tcx> {
475 fn empty() -> Self {
476 Matrix { patterns: vec![] }
477 }
478
479 /// Number of columns of this matrix. `None` is the matrix is empty.
480 pub(super) fn column_count(&self) -> Option<usize> {
481 self.patterns.get(0).map(|r| r.len())
482 }
483
6a06907d
XL
484 /// Pushes a new row to the matrix. If the row starts with an or-pattern, this recursively
485 /// expands it.
fc512014 486 fn push(&mut self, row: PatStack<'p, 'tcx>) {
c295e0f8 487 if !row.is_empty() && row.head().is_or_pat() {
f2b60f7d 488 row.expand_and_extend(self);
fc512014
XL
489 } else {
490 self.patterns.push(row);
491 }
492 }
493
494 /// Iterate over the first component of each row
c295e0f8 495 fn heads<'a>(
fc512014 496 &'a self,
c295e0f8
XL
497 ) -> impl Iterator<Item = &'p DeconstructedPat<'p, 'tcx>> + Clone + Captures<'a> {
498 self.patterns.iter().map(|r| r.head())
fc512014
XL
499 }
500
501 /// This computes `S(constructor, self)`. See top of the file for explanations.
502 fn specialize_constructor(
503 &self,
064997fb 504 pcx: &PatCtxt<'_, 'p, 'tcx>,
fc512014 505 ctor: &Constructor<'tcx>,
fc512014 506 ) -> Matrix<'p, 'tcx> {
c295e0f8
XL
507 let mut matrix = Matrix::empty();
508 for row in &self.patterns {
509 if ctor.is_covered_by(pcx, row.head().ctor()) {
064997fb 510 let new_row = row.pop_head_constructor(pcx, ctor);
c295e0f8
XL
511 matrix.push(new_row);
512 }
513 }
514 matrix
fc512014
XL
515 }
516}
517
518/// Pretty-printer for matrices of patterns, example:
519///
520/// ```text
fc512014 521/// + _ + [] +
fc512014 522/// + true + [First] +
fc512014 523/// + true + [Second(true)] +
fc512014 524/// + false + [_] +
fc512014 525/// + _ + [_, _, tail @ ..] +
fc512014
XL
526/// ```
527impl<'p, 'tcx> fmt::Debug for Matrix<'p, 'tcx> {
528 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
529 write!(f, "\n")?;
530
531 let Matrix { patterns: m, .. } = self;
532 let pretty_printed_matrix: Vec<Vec<String>> =
add651ee 533 m.iter().map(|row| row.iter().map(|pat| format!("{pat:?}")).collect()).collect();
fc512014 534
6a06907d 535 let column_count = m.iter().map(|row| row.len()).next().unwrap_or(0);
fc512014
XL
536 assert!(m.iter().all(|row| row.len() == column_count));
537 let column_widths: Vec<usize> = (0..column_count)
538 .map(|col| pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0))
539 .collect();
540
fc512014
XL
541 for row in pretty_printed_matrix {
542 write!(f, "+")?;
543 for (column, pat_str) in row.into_iter().enumerate() {
544 write!(f, " ")?;
545 write!(f, "{:1$}", pat_str, column_widths[column])?;
546 write!(f, " +")?;
547 }
548 write!(f, "\n")?;
fc512014
XL
549 }
550 Ok(())
551 }
552}
553
6a06907d
XL
554/// This carries the results of computing usefulness, as described at the top of the file. When
555/// checking usefulness of a match branch, we use the `NoWitnesses` variant, which also keeps track
556/// of potential unreachable sub-patterns (in the presence of or-patterns). When checking
557/// exhaustiveness of a whole match, we use the `WithWitnesses` variant, which carries a list of
558/// witnesses of non-exhaustiveness when there are any.
c295e0f8
XL
559/// Which variant to use is dictated by `ArmType`.
560#[derive(Debug)]
6a06907d 561enum Usefulness<'p, 'tcx> {
c295e0f8
XL
562 /// If we don't care about witnesses, simply remember if the pattern was useful.
563 NoWitnesses { useful: bool },
6a06907d
XL
564 /// Carries a list of witnesses of non-exhaustiveness. If empty, indicates that the whole
565 /// pattern is unreachable.
c295e0f8 566 WithWitnesses(Vec<Witness<'p, 'tcx>>),
fc512014
XL
567}
568
6a06907d 569impl<'p, 'tcx> Usefulness<'p, 'tcx> {
c295e0f8 570 fn new_useful(preference: ArmType) -> Self {
fc512014 571 match preference {
c295e0f8
XL
572 // A single (empty) witness of reachability.
573 FakeExtraWildcard => WithWitnesses(vec![Witness(vec![])]),
574 RealArm => NoWitnesses { useful: true },
6a06907d
XL
575 }
576 }
c295e0f8
XL
577
578 fn new_not_useful(preference: ArmType) -> Self {
6a06907d 579 match preference {
c295e0f8
XL
580 FakeExtraWildcard => WithWitnesses(vec![]),
581 RealArm => NoWitnesses { useful: false },
582 }
583 }
584
585 fn is_useful(&self) -> bool {
586 match self {
587 Usefulness::NoWitnesses { useful } => *useful,
588 Usefulness::WithWitnesses(witnesses) => !witnesses.is_empty(),
6a06907d
XL
589 }
590 }
591
592 /// Combine usefulnesses from two branches. This is an associative operation.
593 fn extend(&mut self, other: Self) {
594 match (&mut *self, other) {
595 (WithWitnesses(_), WithWitnesses(o)) if o.is_empty() => {}
596 (WithWitnesses(s), WithWitnesses(o)) if s.is_empty() => *self = WithWitnesses(o),
597 (WithWitnesses(s), WithWitnesses(o)) => s.extend(o),
c295e0f8
XL
598 (NoWitnesses { useful: s_useful }, NoWitnesses { useful: o_useful }) => {
599 *s_useful = *s_useful || o_useful
fc512014 600 }
c295e0f8 601 _ => unreachable!(),
fc512014
XL
602 }
603 }
604
c295e0f8 605 /// After calculating usefulness after a specialization, call this to reconstruct a usefulness
fc512014
XL
606 /// that makes sense for the matrix pre-specialization. This new usefulness can then be merged
607 /// with the results of specializing with the other constructors.
6a06907d 608 fn apply_constructor(
fc512014 609 self,
064997fb 610 pcx: &PatCtxt<'_, 'p, 'tcx>,
fc512014
XL
611 matrix: &Matrix<'p, 'tcx>, // used to compute missing ctors
612 ctor: &Constructor<'tcx>,
fc512014
XL
613 ) -> Self {
614 match self {
c295e0f8
XL
615 NoWitnesses { .. } => self,
616 WithWitnesses(ref witnesses) if witnesses.is_empty() => self,
6a06907d 617 WithWitnesses(witnesses) => {
c295e0f8
XL
618 let new_witnesses = if let Constructor::Missing { .. } = ctor {
619 // We got the special `Missing` constructor, so each of the missing constructors
620 // gives a new pattern that is not caught by the match. We list those patterns.
781aab86
FG
621 if pcx.is_non_exhaustive {
622 witnesses
623 .into_iter()
624 // Here we don't want the user to try to list all variants, we want them to add
625 // a wildcard, so we only suggest that.
626 .map(|witness| {
627 witness.apply_constructor(pcx, &Constructor::NonExhaustive)
628 })
629 .collect()
c295e0f8
XL
630 } else {
631 let mut split_wildcard = SplitWildcard::new(pcx);
632 split_wildcard.split(pcx, matrix.heads().map(DeconstructedPat::ctor));
633
634 // This lets us know if we skipped any variants because they are marked
635 // `doc(hidden)` or they are unstable feature gate (only stdlib types).
636 let mut hide_variant_show_wild = false;
637 // Construct for each missing constructor a "wild" version of this
638 // constructor, that matches everything that can be built with
639 // it. For example, if `ctor` is a `Constructor::Variant` for
640 // `Option::Some`, we get the pattern `Some(_)`.
781aab86 641 let mut new_patterns: Vec<DeconstructedPat<'_, '_>> = split_wildcard
c295e0f8
XL
642 .iter_missing(pcx)
643 .filter_map(|missing_ctor| {
644 // Check if this variant is marked `doc(hidden)`
645 if missing_ctor.is_doc_hidden_variant(pcx)
646 || missing_ctor.is_unstable_variant(pcx)
647 {
648 hide_variant_show_wild = true;
649 return None;
650 }
651 Some(DeconstructedPat::wild_from_ctor(pcx, missing_ctor.clone()))
652 })
653 .collect();
654
655 if hide_variant_show_wild {
781aab86 656 new_patterns.push(DeconstructedPat::wildcard(pcx.ty, pcx.span));
c295e0f8
XL
657 }
658
781aab86
FG
659 witnesses
660 .into_iter()
661 .flat_map(|witness| {
662 new_patterns.iter().map(move |pat| {
663 Witness(
664 witness
665 .0
666 .iter()
667 .chain(once(pat))
668 .map(DeconstructedPat::clone_and_forget_reachability)
669 .collect(),
670 )
671 })
fc512014 672 })
781aab86
FG
673 .collect()
674 }
fc512014
XL
675 } else {
676 witnesses
677 .into_iter()
c295e0f8 678 .map(|witness| witness.apply_constructor(pcx, &ctor))
fc512014
XL
679 .collect()
680 };
6a06907d 681 WithWitnesses(new_witnesses)
fc512014 682 }
fc512014
XL
683 }
684 }
685}
686
687#[derive(Copy, Clone, Debug)]
c295e0f8
XL
688enum ArmType {
689 FakeExtraWildcard,
690 RealArm,
fc512014
XL
691}
692
693/// A witness of non-exhaustiveness for error reporting, represented
694/// as a list of patterns (in reverse order of construction) with
695/// wildcards inside to represent elements that can take any inhabitant
696/// of the type as a value.
697///
698/// A witness against a list of patterns should have the same types
699/// and length as the pattern matched against. Because Rust `match`
700/// is always against a single pattern, at the end the witness will
701/// have length 1, but in the middle of the algorithm, it can contain
702/// multiple patterns.
703///
704/// For example, if we are constructing a witness for the match against
705///
04454e1e 706/// ```compile_fail,E0004
fc512014 707/// struct Pair(Option<(u32, u32)>, bool);
04454e1e 708/// # fn foo(p: Pair) {
49aad941 709/// match p {
fc512014
XL
710/// Pair(None, _) => {}
711/// Pair(_, false) => {}
712/// }
04454e1e 713/// # }
fc512014
XL
714/// ```
715///
716/// We'll perform the following steps:
717/// 1. Start with an empty witness
718/// `Witness(vec![])`
719/// 2. Push a witness `true` against the `false`
720/// `Witness(vec![true])`
721/// 3. Push a witness `Some(_)` against the `None`
722/// `Witness(vec![true, Some(_)])`
723/// 4. Apply the `Pair` constructor to the witnesses
724/// `Witness(vec![Pair(Some(_), true)])`
725///
726/// The final `Pair(Some(_), true)` is then the resulting witness.
c295e0f8 727#[derive(Debug)]
923072b8 728pub(crate) struct Witness<'p, 'tcx>(Vec<DeconstructedPat<'p, 'tcx>>);
fc512014 729
c295e0f8 730impl<'p, 'tcx> Witness<'p, 'tcx> {
fc512014 731 /// Asserts that the witness contains a single pattern, and returns it.
c295e0f8 732 fn single_pattern(self) -> DeconstructedPat<'p, 'tcx> {
fc512014
XL
733 assert_eq!(self.0.len(), 1);
734 self.0.into_iter().next().unwrap()
735 }
736
737 /// Constructs a partial witness for a pattern given a list of
738 /// patterns expanded by the specialization step.
739 ///
740 /// When a pattern P is discovered to be useful, this function is used bottom-up
741 /// to reconstruct a complete witness, e.g., a pattern P' that covers a subset
742 /// of values, V, where each value in that set is not covered by any previously
743 /// used patterns and is covered by the pattern P'. Examples:
744 ///
745 /// left_ty: tuple of 3 elements
746 /// pats: [10, 20, _] => (10, 20, _)
747 ///
748 /// left_ty: struct X { a: (bool, &'static str), b: usize}
749 /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 }
064997fb 750 fn apply_constructor(mut self, pcx: &PatCtxt<'_, 'p, 'tcx>, ctor: &Constructor<'tcx>) -> Self {
fc512014
XL
751 let pat = {
752 let len = self.0.len();
c295e0f8 753 let arity = ctor.arity(pcx);
fc512014 754 let pats = self.0.drain((len - arity)..).rev();
c295e0f8 755 let fields = Fields::from_iter(pcx.cx, pats);
353b0b11 756 DeconstructedPat::new(ctor.clone(), fields, pcx.ty, pcx.span)
fc512014
XL
757 };
758
759 self.0.push(pat);
760
761 self
762 }
763}
764
765/// Algorithm from <http://moscova.inria.fr/~maranget/papers/warn/index.html>.
766/// The algorithm from the paper has been modified to correctly handle empty
767/// types. The changes are:
768/// (0) We don't exit early if the pattern matrix has zero rows. We just
769/// continue to recurse over columns.
770/// (1) all_constructors will only return constructors that are statically
771/// possible. E.g., it will only return `Ok` for `Result<T, !>`.
772///
773/// This finds whether a (row) vector `v` of patterns is 'useful' in relation
774/// to a set of such vectors `m` - this is defined as there being a set of
775/// inputs that will match `v` but not any of the sets in `m`.
776///
777/// All the patterns at each column of the `matrix ++ v` matrix must have the same type.
778///
779/// This is used both for reachability checking (if a pattern isn't useful in
780/// relation to preceding patterns, it is not reachable) and exhaustiveness
781/// checking (if a wildcard pattern is useful in relation to a matrix, the
782/// matrix isn't exhaustive).
783///
784/// `is_under_guard` is used to inform if the pattern has a guard. If it
785/// has one it must not be inserted into the matrix. This shouldn't be
786/// relied on for soundness.
353b0b11 787#[instrument(level = "debug", skip(cx, matrix, lint_root), ret)]
fc512014
XL
788fn is_useful<'p, 'tcx>(
789 cx: &MatchCheckCtxt<'p, 'tcx>,
790 matrix: &Matrix<'p, 'tcx>,
791 v: &PatStack<'p, 'tcx>,
c295e0f8 792 witness_preference: ArmType,
353b0b11 793 lint_root: HirId,
fc512014
XL
794 is_under_guard: bool,
795 is_top_level: bool,
6a06907d 796) -> Usefulness<'p, 'tcx> {
064997fb 797 debug!(?matrix, ?v);
fc512014 798 let Matrix { patterns: rows, .. } = matrix;
fc512014
XL
799
800 // The base case. We are pattern-matching on () and the return value is
801 // based on whether our matrix has a row or not.
802 // NOTE: This could potentially be optimized by checking rows.is_empty()
803 // first and then, if v is non-empty, the return value is based on whether
804 // the type of the tuple we're checking is inhabited or not.
805 if v.is_empty() {
6a06907d 806 let ret = if rows.is_empty() {
fc512014
XL
807 Usefulness::new_useful(witness_preference)
808 } else {
6a06907d 809 Usefulness::new_not_useful(witness_preference)
fc512014 810 };
6a06907d
XL
811 debug!(?ret);
812 return ret;
813 }
fc512014 814
3c0e092e 815 debug_assert!(rows.iter().all(|r| r.len() == v.len()));
fc512014 816
fc512014 817 // If the first pattern is an or-pattern, expand it.
c295e0f8
XL
818 let mut ret = Usefulness::new_not_useful(witness_preference);
819 if v.head().is_or_pat() {
6a06907d 820 debug!("expanding or-pattern");
6a06907d 821 // We try each or-pattern branch in turn.
fc512014 822 let mut matrix = matrix.clone();
c295e0f8 823 for v in v.expand_or_pat() {
04454e1e 824 debug!(?v);
3c0e092e 825 let usefulness = ensure_sufficient_stack(|| {
353b0b11 826 is_useful(cx, &matrix, &v, witness_preference, lint_root, is_under_guard, false)
3c0e092e 827 });
04454e1e 828 debug!(?usefulness);
c295e0f8 829 ret.extend(usefulness);
fc512014
XL
830 // If pattern has a guard don't add it to the matrix.
831 if !is_under_guard {
832 // We push the already-seen patterns into the matrix in order to detect redundant
833 // branches like `Some(_) | Some(0)`.
834 matrix.push(v);
835 }
c295e0f8 836 }
fc512014 837 } else {
2b03887a
FG
838 let mut ty = v.head().ty();
839
840 // Opaque types can't get destructured/split, but the patterns can
841 // actually hint at hidden types, so we use the patterns' types instead.
9c376795 842 if let ty::Alias(ty::Opaque, ..) = ty.kind() {
2b03887a
FG
843 if let Some(row) = rows.first() {
844 ty = row.head().ty();
845 }
846 }
064997fb
FG
847 let is_non_exhaustive = cx.is_foreign_non_exhaustive_enum(ty);
848 debug!("v.head: {:?}, v.span: {:?}", v.head(), v.head().span());
849 let pcx = &PatCtxt { cx, ty, span: v.head().span(), is_top_level, is_non_exhaustive };
850
c295e0f8 851 let v_ctor = v.head().ctor();
04454e1e 852 debug!(?v_ctor);
fc512014
XL
853 if let Constructor::IntRange(ctor_range) = &v_ctor {
854 // Lint on likely incorrect range patterns (#63987)
855 ctor_range.lint_overlapping_range_endpoints(
856 pcx,
c295e0f8 857 matrix.heads(),
fc512014 858 matrix.column_count().unwrap_or(0),
353b0b11 859 lint_root,
fc512014
XL
860 )
861 }
862 // We split the head constructor of `v`.
c295e0f8
XL
863 let split_ctors = v_ctor.split(pcx, matrix.heads().map(DeconstructedPat::ctor));
864 let is_non_exhaustive_and_wild = is_non_exhaustive && v_ctor.is_wildcard();
fc512014
XL
865 // For each constructor, we compute whether there's a value that starts with it that would
866 // witness the usefulness of `v`.
867 let start_matrix = &matrix;
c295e0f8 868 for ctor in split_ctors {
6a06907d 869 debug!("specialize({:?})", ctor);
fc512014 870 // We cache the result of `Fields::wildcards` because it is used a lot.
c295e0f8 871 let spec_matrix = start_matrix.specialize_constructor(pcx, &ctor);
064997fb 872 let v = v.pop_head_constructor(pcx, &ctor);
3c0e092e 873 let usefulness = ensure_sufficient_stack(|| {
353b0b11
FG
874 is_useful(
875 cx,
876 &spec_matrix,
877 &v,
878 witness_preference,
879 lint_root,
880 is_under_guard,
881 false,
882 )
3c0e092e 883 });
c295e0f8
XL
884 let usefulness = usefulness.apply_constructor(pcx, start_matrix, &ctor);
885
886 // When all the conditions are met we have a match with a `non_exhaustive` enum
887 // that has the potential to trigger the `non_exhaustive_omitted_patterns` lint.
888 // To understand the workings checkout `Constructor::split` and `SplitWildcard::new/into_ctors`
889 if is_non_exhaustive_and_wild
353b0b11
FG
890 // Only emit a lint on refutable patterns.
891 && cx.refutable
2b03887a 892 // We check that the match has a wildcard pattern and that wildcard is useful,
c295e0f8
XL
893 // meaning there are variants that are covered by the wildcard. Without the check
894 // for `witness_preference` the lint would trigger on `if let NonExhaustiveEnum::A = foo {}`
895 && usefulness.is_useful() && matches!(witness_preference, RealArm)
896 && matches!(
897 &ctor,
898 Constructor::Missing { nonexhaustive_enum_missing_real_variants: true }
899 )
900 {
901 let patterns = {
902 let mut split_wildcard = SplitWildcard::new(pcx);
903 split_wildcard.split(pcx, matrix.heads().map(DeconstructedPat::ctor));
904 // Construct for each missing constructor a "wild" version of this
905 // constructor, that matches everything that can be built with
906 // it. For example, if `ctor` is a `Constructor::Variant` for
907 // `Option::Some`, we get the pattern `Some(_)`.
908 split_wildcard
909 .iter_missing(pcx)
910 // Filter out the `NonExhaustive` because we want to list only real
911 // variants. Also remove any unstable feature gated variants.
912 // Because of how we computed `nonexhaustive_enum_missing_real_variants`,
913 // this will not return an empty `Vec`.
914 .filter(|c| !(c.is_non_exhaustive() || c.is_unstable_variant(pcx)))
915 .cloned()
916 .map(|missing_ctor| DeconstructedPat::wild_from_ctor(pcx, missing_ctor))
917 .collect::<Vec<_>>()
918 };
919
9c376795
FG
920 // Report that a match of a `non_exhaustive` enum marked with `non_exhaustive_omitted_patterns`
921 // is not exhaustive enough.
922 //
923 // NB: The partner lint for structs lives in `compiler/rustc_hir_analysis/src/check/pat.rs`.
924 cx.tcx.emit_spanned_lint(
925 NON_EXHAUSTIVE_OMITTED_PATTERNS,
353b0b11 926 lint_root,
9c376795
FG
927 pcx.span,
928 NonExhaustiveOmittedPattern {
929 scrut_ty: pcx.ty,
930 uncovered: Uncovered::new(pcx.span, pcx.cx, patterns),
931 },
932 );
c295e0f8
XL
933 }
934
935 ret.extend(usefulness);
936 }
937 }
938
939 if ret.is_useful() {
940 v.head().set_reachable();
941 }
942
fc512014
XL
943 ret
944}
945
946/// The arm of a match expression.
04454e1e 947#[derive(Clone, Copy, Debug)]
923072b8 948pub(crate) struct MatchArm<'p, 'tcx> {
fc512014 949 /// The pattern must have been lowered through `check_match::MatchVisitor::lower_pattern`.
923072b8
FG
950 pub(crate) pat: &'p DeconstructedPat<'p, 'tcx>,
951 pub(crate) hir_id: HirId,
952 pub(crate) has_guard: bool,
fc512014
XL
953}
954
6a06907d
XL
955/// Indicates whether or not a given arm is reachable.
956#[derive(Clone, Debug)]
923072b8 957pub(crate) enum Reachability {
6a06907d
XL
958 /// The arm is reachable. This additionally carries a set of or-pattern branches that have been
959 /// found to be unreachable despite the overall arm being reachable. Used only in the presence
960 /// of or-patterns, otherwise it stays empty.
961 Reachable(Vec<Span>),
962 /// The arm is unreachable.
963 Unreachable,
964}
965
fc512014 966/// The output of checking a match for exhaustiveness and arm reachability.
923072b8 967pub(crate) struct UsefulnessReport<'p, 'tcx> {
fc512014 968 /// For each arm of the input, whether that arm is reachable after the arms above it.
923072b8 969 pub(crate) arm_usefulness: Vec<(MatchArm<'p, 'tcx>, Reachability)>,
fc512014
XL
970 /// If the match is exhaustive, this is empty. If not, this contains witnesses for the lack of
971 /// exhaustiveness.
923072b8 972 pub(crate) non_exhaustiveness_witnesses: Vec<DeconstructedPat<'p, 'tcx>>,
fc512014
XL
973}
974
975/// The entrypoint for the usefulness algorithm. Computes whether a match is exhaustive and which
976/// of its arms are reachable.
977///
978/// Note: the input patterns must have been lowered through
979/// `check_match::MatchVisitor::lower_pattern`.
04454e1e 980#[instrument(skip(cx, arms), level = "debug")]
923072b8 981pub(crate) fn compute_match_usefulness<'p, 'tcx>(
fc512014
XL
982 cx: &MatchCheckCtxt<'p, 'tcx>,
983 arms: &[MatchArm<'p, 'tcx>],
353b0b11 984 lint_root: HirId,
fc512014
XL
985 scrut_ty: Ty<'tcx>,
986) -> UsefulnessReport<'p, 'tcx> {
987 let mut matrix = Matrix::empty();
988 let arm_usefulness: Vec<_> = arms
989 .iter()
990 .copied()
991 .map(|arm| {
04454e1e 992 debug!(?arm);
fc512014 993 let v = PatStack::from_pattern(arm.pat);
c295e0f8 994 is_useful(cx, &matrix, &v, RealArm, arm.hir_id, arm.has_guard, true);
fc512014
XL
995 if !arm.has_guard {
996 matrix.push(v);
997 }
c295e0f8
XL
998 let reachability = if arm.pat.is_reachable() {
999 Reachability::Reachable(arm.pat.unreachable_spans())
1000 } else {
1001 Reachability::Unreachable
6a06907d
XL
1002 };
1003 (arm, reachability)
fc512014
XL
1004 })
1005 .collect();
1006
353b0b11 1007 let wild_pattern = cx.pattern_arena.alloc(DeconstructedPat::wildcard(scrut_ty, DUMMY_SP));
fc512014 1008 let v = PatStack::from_pattern(wild_pattern);
353b0b11 1009 let usefulness = is_useful(cx, &matrix, &v, FakeExtraWildcard, lint_root, false, true);
fc512014 1010 let non_exhaustiveness_witnesses = match usefulness {
6a06907d 1011 WithWitnesses(pats) => pats.into_iter().map(|w| w.single_pattern()).collect(),
c295e0f8 1012 NoWitnesses { .. } => bug!(),
fc512014
XL
1013 };
1014 UsefulnessReport { arm_usefulness, non_exhaustiveness_witnesses }
1015}