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