ra_ap_rustc_pattern_analysis/
usefulness.rs

1//! # Match exhaustiveness and redundancy algorithm
2//!
3//! This file contains the logic for exhaustiveness and usefulness checking for pattern-matching.
4//! Specifically, given a list of patterns in a match, we can tell whether:
5//! (a) a given pattern is redundant
6//! (b) the patterns cover every possible value for the type (exhaustiveness)
7//!
8//! The algorithm implemented here is inspired from the one described in [this
9//! paper](http://moscova.inria.fr/~maranget/papers/warn/index.html). We have however changed it in
10//! various ways to accommodate the variety of patterns that Rust supports. We thus explain our
11//! version here, without being as precise.
12//!
13//! Fun fact: computing exhaustiveness is NP-complete, because we can encode a SAT problem as an
14//! exhaustiveness problem. See [here](https://niedzejkob.p4.team/rust-np) for the fun details.
15//!
16//!
17//! # Summary
18//!
19//! The algorithm is given as input a list of patterns, one for each arm of a match, and computes
20//! the following:
21//! - a set of values that match none of the patterns (if any),
22//! - for each subpattern (taking into account or-patterns), whether removing it would change
23//!     anything about how the match executes, i.e. whether it is useful/not redundant.
24//!
25//! To a first approximation, the algorithm works by exploring all possible values for the type
26//! being matched on, and determining which arm(s) catch which value. To make this tractable we
27//! cleverly group together values, as we'll see below.
28//!
29//! The entrypoint of this file is the [`compute_match_usefulness`] function, which computes
30//! usefulness for each subpattern and exhaustiveness for the whole match.
31//!
32//! In this page we explain the necessary concepts to understand how the algorithm works.
33//!
34//!
35//! # Usefulness
36//!
37//! The central concept of this file is the notion of "usefulness". Given some patterns `p_1 ..
38//! p_n`, a pattern `q` is said to be *useful* if there is a value that is matched by `q` and by
39//! none of the `p_i`. We write `usefulness(p_1 .. p_n, q)` for a function that returns a list of
40//! such values. The aim of this file is to compute it efficiently.
41//!
42//! This is enough to compute usefulness: a pattern in a `match` expression is redundant iff it is
43//! not useful w.r.t. the patterns above it:
44//! ```compile_fail,E0004
45//! # fn foo() {
46//! match Some(0u32) {
47//!     Some(0..100) => {},
48//!     Some(90..190) => {}, // useful: `Some(150)` is matched by this but not the branch above
49//!     Some(50..150) => {}, // redundant: all the values this matches are already matched by
50//!                          //   the branches above
51//!     None => {},          // useful: `None` is matched by this but not the branches above
52//! }
53//! # }
54//! ```
55//!
56//! This is also enough to compute exhaustiveness: a match is exhaustive iff the wildcard `_`
57//! pattern is _not_ useful w.r.t. the patterns in the match. The values returned by `usefulness`
58//! are used to tell the user which values are missing.
59//! ```compile_fail,E0004
60//! # fn foo(x: Option<u32>) {
61//! match x {
62//!     None => {},
63//!     Some(0) => {},
64//!     // not exhaustive: `_` is useful because it matches `Some(1)`
65//! }
66//! # }
67//! ```
68//!
69//!
70//! # Constructors and fields
71//!
72//! In the value `Pair(Some(0), true)`, `Pair` is called the constructor of the value, and `Some(0)`
73//! and `true` are its fields. Every matchable value can be decomposed in this way. Examples of
74//! constructors are: `Some`, `None`, `(,)` (the 2-tuple constructor), `Foo {..}` (the constructor
75//! for a struct `Foo`), and `2` (the constructor for the number `2`).
76//!
77//! Each constructor takes a fixed number of fields; this is called its arity. `Pair` and `(,)` have
78//! arity 2, `Some` has arity 1, `None` and `42` have arity 0. Each type has a known set of
79//! constructors. Some types have many constructors (like `u64`) or even an infinitely many (like
80//! `&str` and `&[T]`).
81//!
82//! Patterns are similar: `Pair(Some(_), _)` has constructor `Pair` and two fields. The difference
83//! is that we get some extra pattern-only constructors, namely: the wildcard `_`, variable
84//! bindings, integer ranges like `0..=10`, and variable-length slices like `[_, .., _]`. We treat
85//! or-patterns separately, see the dedicated section below.
86//!
87//! Now to check if a value `v` matches a pattern `p`, we check if `v`'s constructor matches `p`'s
88//! constructor, then recursively compare their fields if necessary. A few representative examples:
89//!
90//! - `matches!(v, _) := true`
91//! - `matches!((v0,  v1), (p0,  p1)) := matches!(v0, p0) && matches!(v1, p1)`
92//! - `matches!(Foo { bar: v0, baz: v1 }, Foo { bar: p0, baz: p1 }) := matches!(v0, p0) && matches!(v1, p1)`
93//! - `matches!(Ok(v0), Ok(p0)) := matches!(v0, p0)`
94//! - `matches!(Ok(v0), Err(p0)) := false` (incompatible variants)
95//! - `matches!(v, 1..=100) := matches!(v, 1) || ... || matches!(v, 100)`
96//! - `matches!([v0], [p0, .., p1]) := false` (incompatible lengths)
97//! - `matches!([v0, v1, v2], [p0, .., p1]) := matches!(v0, p0) && matches!(v2, p1)`
98//!
99//! Constructors and relevant operations are defined in the [`crate::constructor`] module. A
100//! representation of patterns that uses constructors is available in [`crate::pat`]. The question
101//! of whether a constructor is matched by another one is answered by
102//! [`Constructor::is_covered_by`].
103//!
104//! Note 1: variable bindings (like the `x` in `Some(x)`) match anything, so we treat them as wildcards.
105//! Note 2: this only applies to matchable values. For example a value of type `Rc<u64>` can't be
106//! deconstructed that way.
107//!
108//!
109//!
110//! # Specialization
111//!
112//! The examples in the previous section motivate the operation at the heart of the algorithm:
113//! "specialization". It captures this idea of "removing one layer of constructor".
114//!
115//! `specialize(c, p)` takes a value-only constructor `c` and a pattern `p`, and returns a
116//! pattern-tuple or nothing. It works as follows:
117//!
118//! - Specializing for the wrong constructor returns nothing
119//!
120//!   - `specialize(None, Some(p0)) := <nothing>`
121//!   - `specialize([,,,], [p0]) := <nothing>`
122//!
123//! - Specializing for the correct constructor returns a tuple of the fields
124//!
125//!   - `specialize(Variant1, Variant1(p0, p1, p2)) := (p0, p1, p2)`
126//!   - `specialize(Foo{ bar, baz, quz }, Foo { bar: p0, baz: p1, .. }) := (p0, p1, _)`
127//!   - `specialize([,,,], [p0, .., p1]) := (p0, _, _, p1)`
128//!
129//! We get the following property: for any values `v_1, .., v_n` of appropriate types, we have:
130//! ```text
131//! matches!(c(v_1, .., v_n), p)
132//! <=> specialize(c, p) returns something
133//!     && matches!((v_1, .., v_n), specialize(c, p))
134//! ```
135//!
136//! We also extend specialization to pattern-tuples by applying it to the first pattern:
137//! `specialize(c, (p_0, .., p_n)) := specialize(c, p_0) ++ (p_1, .., p_m)`
138//! where `++` is concatenation of tuples.
139//!
140//!
141//! The previous property extends to pattern-tuples:
142//! ```text
143//! matches!((c(v_1, .., v_n), w_1, .., w_m), (p_0, p_1, .., p_m))
144//! <=> specialize(c, p_0) does not error
145//!     && matches!((v_1, .., v_n, w_1, .., w_m), specialize(c, (p_0, p_1, .., p_m)))
146//! ```
147//!
148//! Whether specialization returns something or not is given by [`Constructor::is_covered_by`].
149//! Specialization of a pattern is computed in [`DeconstructedPat::specialize`]. Specialization for
150//! a pattern-tuple is computed in [`PatStack::pop_head_constructor`]. Finally, specialization for a
151//! set of pattern-tuples is computed in [`Matrix::specialize_constructor`].
152//!
153//!
154//!
155//! # Undoing specialization
156//!
157//! To construct witnesses we will need an inverse of specialization. If `c` is a constructor of
158//! arity `n`, we define `unspecialize` as:
159//! `unspecialize(c, (p_1, .., p_n, q_1, .., q_m)) := (c(p_1, .., p_n), q_1, .., q_m)`.
160//!
161//! This is done for a single witness-tuple in [`WitnessStack::apply_constructor`], and for a set of
162//! witness-tuples in [`WitnessMatrix::apply_constructor`].
163//!
164//!
165//!
166//! # Computing usefulness
167//!
168//! We now present a naive version of the algorithm for computing usefulness. From now on we operate
169//! on pattern-tuples.
170//!
171//! Let `pt_1, .., pt_n` and `qt` be length-m tuples of patterns for the same type `(T_1, .., T_m)`.
172//! We compute `usefulness(tp_1, .., tp_n, tq)` as follows:
173//!
174//! - Base case: `m == 0`.
175//!     The pattern-tuples are all empty, i.e. they're all `()`. Thus `tq` is useful iff there are
176//!     no rows above it, i.e. if `n == 0`. In that case we return `()` as a witness-tuple of
177//!     usefulness of `tq`.
178//!
179//! - Inductive case: `m > 0`.
180//!     In this naive version, we list all the possible constructors for values of type `T1` (we
181//!     will be more clever in the next section).
182//!
183//!     - For each such constructor `c` for which `specialize(c, tq)` is not nothing:
184//!         - We recursively compute `usefulness(specialize(c, tp_1) ... specialize(c, tp_n), specialize(c, tq))`,
185//!             where we discard any `specialize(c, p_i)` that returns nothing.
186//!         - For each witness-tuple `w` found, we apply `unspecialize(c, w)` to it.
187//!
188//!     - We return the all the witnesses found, if any.
189//!
190//!
191//! Let's take the following example:
192//! ```compile_fail,E0004
193//! # enum Enum { Variant1(()), Variant2(Option<bool>, u32)}
194//! # use Enum::*;
195//! # fn foo(x: Enum) {
196//! match x {
197//!     Variant1(_) => {} // `p1`
198//!     Variant2(None, 0) => {} // `p2`
199//!     Variant2(Some(_), 0) => {} // `q`
200//! }
201//! # }
202//! ```
203//!
204//! To compute the usefulness of `q`, we would proceed as follows:
205//! ```text
206//! Start:
207//!   `tp1 = [Variant1(_)]`
208//!   `tp2 = [Variant2(None, 0)]`
209//!   `tq  = [Variant2(Some(true), 0)]`
210//!
211//!   Constructors are `Variant1` and `Variant2`. Only `Variant2` can specialize `tq`.
212//!   Specialize with `Variant2`:
213//!     `tp2 = [None, 0]`
214//!     `tq  = [Some(true), 0]`
215//!
216//!     Constructors are `None` and `Some`. Only `Some` can specialize `tq`.
217//!     Specialize with `Some`:
218//!       `tq  = [true, 0]`
219//!
220//!       Constructors are `false` and `true`. Only `true` can specialize `tq`.
221//!       Specialize with `true`:
222//!         `tq  = [0]`
223//!
224//!         Constructors are `0`, `1`, .. up to infinity. Only `0` can specialize `tq`.
225//!         Specialize with `0`:
226//!           `tq  = []`
227//!
228//!           m == 0 and n == 0, so `tq` is useful with witness `[]`.
229//!             `witness  = []`
230//!
231//!         Unspecialize with `0`:
232//!           `witness  = [0]`
233//!       Unspecialize with `true`:
234//!         `witness  = [true, 0]`
235//!     Unspecialize with `Some`:
236//!       `witness  = [Some(true), 0]`
237//!   Unspecialize with `Variant2`:
238//!     `witness  = [Variant2(Some(true), 0)]`
239//! ```
240//!
241//! Therefore `usefulness(tp_1, tp_2, tq)` returns the single witness-tuple `[Variant2(Some(true), 0)]`.
242//!
243//!
244//! Computing the set of constructors for a type is done in [`PatCx::ctors_for_ty`]. See
245//! the following sections for more accurate versions of the algorithm and corresponding links.
246//!
247//!
248//!
249//! # Computing usefulness and exhaustiveness in one go
250//!
251//! The algorithm we have described so far computes usefulness of each pattern in turn, and ends by
252//! checking if `_` is useful to determine exhaustiveness of the whole match. In practice, instead
253//! of doing "for each pattern { for each constructor { ... } }", we do "for each constructor { for
254//! each pattern { ... } }". This allows us to compute everything in one go.
255//!
256//! [`Matrix`] stores the set of pattern-tuples under consideration. We track usefulness of each
257//! row mutably in the matrix as we go along. We ignore witnesses of usefulness of the match rows.
258//! We gather witnesses of the usefulness of `_` in [`WitnessMatrix`]. The algorithm that computes
259//! all this is in [`compute_exhaustiveness_and_usefulness`].
260//!
261//! See the full example at the bottom of this documentation.
262//!
263//!
264//!
265//! # Making usefulness tractable: constructor splitting
266//!
267//! We're missing one last detail: which constructors do we list? Naively listing all value
268//! constructors cannot work for types like `u64` or `&str`, so we need to be more clever. The final
269//! clever idea for this algorithm is that we can group together constructors that behave the same.
270//!
271//! Examples:
272//! ```compile_fail,E0004
273//! match (0, false) {
274//!     (0 ..=100, true) => {}
275//!     (50..=150, false) => {}
276//!     (0 ..=200, _) => {}
277//! }
278//! ```
279//!
280//! In this example, trying any of `0`, `1`, .., `49` will give the same specialized matrix, and
281//! thus the same usefulness/exhaustiveness results. We can thus accelerate the algorithm by
282//! trying them all at once. Here in fact, the only cases we need to consider are: `0..50`,
283//! `50..=100`, `101..=150`,`151..=200` and `201..`.
284//!
285//! ```
286//! enum Direction { North, South, East, West }
287//! # let wind = (Direction::North, 0u8);
288//! match wind {
289//!     (Direction::North, 50..) => {}
290//!     (_, _) => {}
291//! }
292//! ```
293//!
294//! In this example, trying any of `South`, `East`, `West` will give the same specialized matrix. By
295//! the same reasoning, we only need to try two cases: `North`, and "everything else".
296//!
297//! We call _constructor splitting_ the operation that computes such a minimal set of cases to try.
298//! This is done in [`ConstructorSet::split`] and explained in [`crate::constructor`].
299//!
300//!
301//!
302//! # `Missing` and relevancy
303//!
304//! ## Relevant values
305//!
306//! Take the following example:
307//!
308//! ```compile_fail,E0004
309//! # let foo = (true, true);
310//! match foo {
311//!     (true, _) => 1,
312//!     (_, true) => 2,
313//! };
314//! ```
315//!
316//! Consider the value `(true, true)`:
317//! - Row 2 does not distinguish `(true, true)` and `(false, true)`;
318//! - `false` does not show up in the first column of the match, so without knowing anything else we
319//!     can deduce that `(false, true)` matches the same or fewer rows than `(true, true)`.
320//!
321//! Using those two facts together, we deduce that `(true, true)` will not give us more usefulness
322//! information about row 2 than `(false, true)` would. We say that "`(true, true)` is made
323//! irrelevant for row 2 by `(false, true)`". We will use this idea to prune the search tree.
324//!
325//!
326//! ## Computing relevancy
327//!
328//! We now generalize from the above example to approximate relevancy in a simple way. Note that we
329//! will only compute an approximation: we can sometimes determine when a case is irrelevant, but
330//! computing this precisely is at least as hard as computing usefulness.
331//!
332//! Our computation of relevancy relies on the `Missing` constructor. As explained in
333//! [`crate::constructor`], `Missing` represents the constructors not present in a given column. For
334//! example in the following:
335//!
336//! ```compile_fail,E0004
337//! enum Direction { North, South, East, West }
338//! # let wind = (Direction::North, 0u8);
339//! match wind {
340//!     (Direction::North, _) => 1,
341//!     (_, 50..) => 2,
342//! };
343//! ```
344//!
345//! Here `South`, `East` and `West` are missing in the first column, and `0..50`  is missing in the
346//! second. Both of these sets are represented by `Constructor::Missing` in their corresponding
347//! column.
348//!
349//! We then compute relevancy as follows: during the course of the algorithm, for a row `r`:
350//! - if `r` has a wildcard in the first column;
351//! - and some constructors are missing in that column;
352//! - then any `c != Missing` is considered irrelevant for row `r`.
353//!
354//! By this we mean that continuing the algorithm by specializing with `c` is guaranteed not to
355//! contribute more information about the usefulness of row `r` than what we would get by
356//! specializing with `Missing`. The argument is the same as in the previous subsection.
357//!
358//! Once we've specialized by a constructor `c` that is irrelevant for row `r`, we're guaranteed to
359//! only explore values irrelevant for `r`. If we then ever reach a point where we're only exploring
360//! values that are irrelevant to all of the rows (including the virtual wildcard row used for
361//! exhaustiveness), we skip that case entirely.
362//!
363//!
364//! ## Example
365//!
366//! Let's go through a variation on the first example:
367//!
368//! ```compile_fail,E0004
369//! # let foo = (true, true, true);
370//! match foo {
371//!     (true, _, true) => 1,
372//!     (_, true, _) => 2,
373//! };
374//! ```
375//!
376//! ```text
377//!  ┐ Patterns:
378//!  │   1. `[(true, _, true)]`
379//!  │   2. `[(_, true, _)]`
380//!  │   3. `[_]` // virtual extra wildcard row
381//!  │
382//!  │ Specialize with `(,,)`:
383//!  ├─┐ Patterns:
384//!  │ │   1. `[true, _, true]`
385//!  │ │   2. `[_, true, _]`
386//!  │ │   3. `[_, _, _]`
387//!  │ │
388//!  │ │ There are missing constructors in the first column (namely `false`), hence
389//!  │ │ `true` is irrelevant for rows 2 and 3.
390//!  │ │
391//!  │ │ Specialize with `true`:
392//!  │ ├─┐ Patterns:
393//!  │ │ │   1. `[_, true]`
394//!  │ │ │   2. `[true, _]` // now exploring irrelevant cases
395//!  │ │ │   3. `[_, _]`    // now exploring irrelevant cases
396//!  │ │ │
397//!  │ │ │ There are missing constructors in the first column (namely `false`), hence
398//!  │ │ │ `true` is irrelevant for rows 1 and 3.
399//!  │ │ │
400//!  │ │ │ Specialize with `true`:
401//!  │ │ ├─┐ Patterns:
402//!  │ │ │ │   1. `[true]` // now exploring irrelevant cases
403//!  │ │ │ │   2. `[_]`    // now exploring irrelevant cases
404//!  │ │ │ │   3. `[_]`    // now exploring irrelevant cases
405//!  │ │ │ │
406//!  │ │ │ │ The current case is irrelevant for all rows: we backtrack immediately.
407//!  │ │ ├─┘
408//!  │ │ │
409//!  │ │ │ Specialize with `false`:
410//!  │ │ ├─┐ Patterns:
411//!  │ │ │ │   1. `[true]`
412//!  │ │ │ │   3. `[_]`    // now exploring irrelevant cases
413//!  │ │ │ │
414//!  │ │ │ │ Specialize with `true`:
415//!  │ │ │ ├─┐ Patterns:
416//!  │ │ │ │ │   1. `[]`
417//!  │ │ │ │ │   3. `[]`    // now exploring irrelevant cases
418//!  │ │ │ │ │
419//!  │ │ │ │ │ Row 1 is therefore useful.
420//!  │ │ │ ├─┘
421//! <etc...>
422//! ```
423//!
424//! Relevancy allowed us to skip the case `(true, true, _)` entirely. In some cases this pruning can
425//! give drastic speedups. The case this was built for is the following (#118437):
426//!
427//! ```ignore(illustrative)
428//! match foo {
429//!     (true, _, _, _, ..) => 1,
430//!     (_, true, _, _, ..) => 2,
431//!     (_, _, true, _, ..) => 3,
432//!     (_, _, _, true, ..) => 4,
433//!     ...
434//! }
435//! ```
436//!
437//! Without considering relevancy, we would explore all 2^n combinations of the `true` and `Missing`
438//! constructors. Relevancy tells us that e.g. `(true, true, false, false, false, ...)` is
439//! irrelevant for all the rows. This allows us to skip all cases with more than one `true`
440//! constructor, changing the runtime from exponential to linear.
441//!
442//!
443//! ## Relevancy and exhaustiveness
444//!
445//! For exhaustiveness, we do something slightly different w.r.t relevancy: we do not report
446//! witnesses of non-exhaustiveness that are irrelevant for the virtual wildcard row. For example,
447//! in:
448//!
449//! ```ignore(illustrative)
450//! match foo {
451//!     (true, true) => {}
452//! }
453//! ```
454//!
455//! we only report `(false, _)` as missing. This was a deliberate choice made early in the
456//! development of rust, for diagnostic and performance purposes. As showed in the previous section,
457//! ignoring irrelevant cases preserves usefulness, so this choice still correctly computes whether
458//! a match is exhaustive.
459//!
460//!
461//!
462//! # Or-patterns
463//!
464//! What we have described so far works well if there are no or-patterns. To handle them, if the
465//! first pattern of any row in the matrix is an or-pattern, we expand it by duplicating the rest of
466//! the row as necessary. For code reuse, this is implemented as "specializing with the `Or`
467//! constructor".
468//!
469//! This makes usefulness tracking subtle, because we also want to compute whether an alternative of
470//! an or-pattern is redundant, e.g. in `Some(_) | Some(0)`. We therefore track usefulness of each
471//! subpattern of the match.
472//!
473//!
474//!
475//! # Constants and opaques
476//!
477//! There are two kinds of constants in patterns:
478//!
479//! * literals (`1`, `true`, `"foo"`)
480//! * named or inline consts (`FOO`, `const { 5 + 6 }`)
481//!
482//! The latter are converted into the corresponding patterns by a previous phase. For example
483//! `const_to_pat(const { [1, 2, 3] })` becomes an `Array(vec![Const(1), Const(2), Const(3)])`
484//! pattern. This gets problematic when comparing the constant via `==` would behave differently
485//! from matching on the constant converted to a pattern. The situation around this is currently
486//! unclear and the lang team is working on clarifying what we want to do there. In any case, there
487//! are constants we will not turn into patterns. We capture these with `Constructor::Opaque`. These
488//! `Opaque` patterns do not participate in exhaustiveness, specialization or overlap checking.
489//!
490//!
491//!
492//! # Usefulness vs reachability, validity, and empty patterns
493//!
494//! This is likely the subtlest aspect of the algorithm. To be fully precise, a match doesn't
495//! operate on a value, it operates on a place. In certain unsafe circumstances, it is possible for
496//! a place to not contain valid data for its type. This has subtle consequences for empty types.
497//! Take the following:
498//!
499//! ```rust
500//! enum Void {}
501//! let x: u8 = 0;
502//! let ptr: *const Void = &x as *const u8 as *const Void;
503//! unsafe {
504//!     match *ptr {
505//!         _ => println!("Reachable!"),
506//!     }
507//! }
508//! ```
509//!
510//! In this example, `ptr` is a valid pointer pointing to a place with invalid data. The `_` pattern
511//! does not look at the contents of `*ptr`, so this is ok and the arm is taken. In other words,
512//! despite the place we are inspecting being of type `Void`, there is a reachable arm. If the
513//! arm had a binding however:
514//!
515//! ```rust
516//! # #[derive(Copy, Clone)]
517//! # enum Void {}
518//! # let x: u8 = 0;
519//! # let ptr: *const Void = &x as *const u8 as *const Void;
520//! # unsafe {
521//! match *ptr {
522//!     _a => println!("Unreachable!"),
523//! }
524//! # }
525//! ```
526//!
527//! Here the binding loads the value of type `Void` from the `*ptr` place. In this example, this
528//! causes UB since the data is not valid. In the general case, this asserts validity of the data at
529//! `*ptr`. Either way, this arm will never be taken.
530//!
531//! Finally, let's consider the empty match `match *ptr {}`. If we consider this exhaustive, then
532//! having invalid data at `*ptr` is invalid. In other words, the empty match is semantically
533//! equivalent to the `_a => ...` match. In the interest of explicitness, we prefer the case with an
534//! arm, hence we won't tell the user to remove the `_a` arm. In other words, the `_a` arm is
535//! unreachable yet not redundant. This is why we lint on redundant arms rather than unreachable
536//! arms, despite the fact that the lint says "unreachable".
537//!
538//! These considerations only affects certain places, namely those that can contain non-valid data
539//! without UB. These are: pointer dereferences, reference dereferences, and union field accesses.
540//! We track in the algorithm whether a given place is known to contain valid data. This is done
541//! first by inspecting the scrutinee syntactically (which gives us `cx.known_valid_scrutinee`), and
542//! then by tracking validity of each column of the matrix (which correspond to places) as we
543//! recurse into subpatterns. That second part is done through [`PlaceValidity`], most notably
544//! [`PlaceValidity::specialize`].
545//!
546//! Having said all that, we don't fully follow what's been presented in this section. For
547//! backwards-compatibility, we ignore place validity when checking whether a pattern is required
548//! for exhaustiveness in two cases: when the `exhaustive_patterns` feature gate is on, or when the
549//! match scrutinee itself has type `!` or `EmptyEnum`. I (Nadrieril) hope to deprecate this
550//! exception.
551//!
552//!
553//!
554//! # Full example
555//!
556//! We illustrate a full run of the algorithm on the following match.
557//!
558//! ```compile_fail,E0004
559//! # struct Pair(Option<u32>, bool);
560//! # fn foo(x: Pair) -> u32 {
561//! match x {
562//!     Pair(Some(0), _) => 1,
563//!     Pair(_, false) => 2,
564//!     Pair(Some(0), false) => 3,
565//! }
566//! # }
567//! ```
568//!
569//! We keep track of the original row for illustration purposes, this is not what the algorithm
570//! actually does (it tracks usefulness as a boolean on each row).
571//!
572//! ```text
573//!  ┐ Patterns:
574//!  │   1. `[Pair(Some(0), _)]`
575//!  │   2. `[Pair(_, false)]`
576//!  │   3. `[Pair(Some(0), false)]`
577//!  │
578//!  │ Specialize with `Pair`:
579//!  ├─┐ Patterns:
580//!  │ │   1. `[Some(0), _]`
581//!  │ │   2. `[_, false]`
582//!  │ │   3. `[Some(0), false]`
583//!  │ │
584//!  │ │ Specialize with `Some`:
585//!  │ ├─┐ Patterns:
586//!  │ │ │   1. `[0, _]`
587//!  │ │ │   2. `[_, false]`
588//!  │ │ │   3. `[0, false]`
589//!  │ │ │
590//!  │ │ │ Specialize with `0`:
591//!  │ │ ├─┐ Patterns:
592//!  │ │ │ │   1. `[_]`
593//!  │ │ │ │   3. `[false]`
594//!  │ │ │ │
595//!  │ │ │ │ Specialize with `true`:
596//!  │ │ │ ├─┐ Patterns:
597//!  │ │ │ │ │   1. `[]`
598//!  │ │ │ │ │
599//!  │ │ │ │ │ We note arm 1 is useful (by `Pair(Some(0), true)`).
600//!  │ │ │ ├─┘
601//!  │ │ │ │
602//!  │ │ │ │ Specialize with `false`:
603//!  │ │ │ ├─┐ Patterns:
604//!  │ │ │ │ │   1. `[]`
605//!  │ │ │ │ │   3. `[]`
606//!  │ │ │ │ │
607//!  │ │ │ │ │ We note arm 1 is useful (by `Pair(Some(0), false)`).
608//!  │ │ │ ├─┘
609//!  │ │ ├─┘
610//!  │ │ │
611//!  │ │ │ Specialize with `1..`:
612//!  │ │ ├─┐ Patterns:
613//!  │ │ │ │   2. `[false]`
614//!  │ │ │ │
615//!  │ │ │ │ Specialize with `true`:
616//!  │ │ │ ├─┐ Patterns:
617//!  │ │ │ │ │   // no rows left
618//!  │ │ │ │ │
619//!  │ │ │ │ │ We have found an unmatched value (`Pair(Some(1..), true)`)! This gives us a witness.
620//!  │ │ │ │ │ New witnesses:
621//!  │ │ │ │ │   `[]`
622//!  │ │ │ ├─┘
623//!  │ │ │ │ Unspecialize new witnesses with `true`:
624//!  │ │ │ │   `[true]`
625//!  │ │ │ │
626//!  │ │ │ │ Specialize with `false`:
627//!  │ │ │ ├─┐ Patterns:
628//!  │ │ │ │ │   2. `[]`
629//!  │ │ │ │ │
630//!  │ │ │ │ │ We note arm 2 is useful (by `Pair(Some(1..), false)`).
631//!  │ │ │ ├─┘
632//!  │ │ │ │
633//!  │ │ │ │ Total witnesses for `1..`:
634//!  │ │ │ │   `[true]`
635//!  │ │ ├─┘
636//!  │ │ │ Unspecialize new witnesses with `1..`:
637//!  │ │ │   `[1.., true]`
638//!  │ │ │
639//!  │ │ │ Total witnesses for `Some`:
640//!  │ │ │   `[1.., true]`
641//!  │ ├─┘
642//!  │ │ Unspecialize new witnesses with `Some`:
643//!  │ │   `[Some(1..), true]`
644//!  │ │
645//!  │ │ Specialize with `None`:
646//!  │ ├─┐ Patterns:
647//!  │ │ │   2. `[false]`
648//!  │ │ │
649//!  │ │ │ Specialize with `true`:
650//!  │ │ ├─┐ Patterns:
651//!  │ │ │ │   // no rows left
652//!  │ │ │ │
653//!  │ │ │ │ We have found an unmatched value (`Pair(None, true)`)! This gives us a witness.
654//!  │ │ │ │ New witnesses:
655//!  │ │ │ │   `[]`
656//!  │ │ ├─┘
657//!  │ │ │ Unspecialize new witnesses with `true`:
658//!  │ │ │   `[true]`
659//!  │ │ │
660//!  │ │ │ Specialize with `false`:
661//!  │ │ ├─┐ Patterns:
662//!  │ │ │ │   2. `[]`
663//!  │ │ │ │
664//!  │ │ │ │ We note arm 2 is useful (by `Pair(None, false)`).
665//!  │ │ ├─┘
666//!  │ │ │
667//!  │ │ │ Total witnesses for `None`:
668//!  │ │ │   `[true]`
669//!  │ ├─┘
670//!  │ │ Unspecialize new witnesses with `None`:
671//!  │ │   `[None, true]`
672//!  │ │
673//!  │ │ Total witnesses for `Pair`:
674//!  │ │   `[Some(1..), true]`
675//!  │ │   `[None, true]`
676//!  ├─┘
677//!  │ Unspecialize new witnesses with `Pair`:
678//!  │   `[Pair(Some(1..), true)]`
679//!  │   `[Pair(None, true)]`
680//!  │
681//!  │ Final witnesses:
682//!  │   `[Pair(Some(1..), true)]`
683//!  │   `[Pair(None, true)]`
684//!  ┘
685//! ```
686//!
687//! We conclude:
688//! - Arm 3 is redundant (it was never marked as useful);
689//! - The match is not exhaustive;
690//! - Adding arms with `Pair(Some(1..), true)` and `Pair(None, true)` would make the match exhaustive.
691//!
692//! Note that when we're deep in the algorithm, we don't know what specialization steps got us here.
693//! We can only figure out what our witnesses correspond to by unspecializing back up the stack.
694//!
695//!
696//! # Tests
697//!
698//! Note: tests specific to this file can be found in:
699//!
700//!   - `ui/pattern/usefulness`
701//!   - `ui/or-patterns`
702//!   - `ui/consts/const_in_pattern`
703//!   - `ui/rfc-2008-non-exhaustive`
704//!   - `ui/half-open-range-patterns`
705//!   - `ui/pattern/deref-patterns`
706//!   - probably many others
707//!
708//! I (Nadrieril) prefer to put new tests in `ui/pattern/usefulness` unless there's a specific
709//! reason not to, for example if they crucially depend on a particular feature like `or_patterns`.
710
711use std::fmt;
712
713#[cfg(feature = "rustc")]
714use rustc_data_structures::stack::ensure_sufficient_stack;
715use rustc_hash::{FxHashMap, FxHashSet};
716use rustc_index::bit_set::DenseBitSet;
717use smallvec::{SmallVec, smallvec};
718use tracing::{debug, instrument};
719
720use self::PlaceValidity::*;
721use crate::constructor::{Constructor, ConstructorSet, IntRange};
722use crate::pat::{DeconstructedPat, PatId, PatOrWild, WitnessPat};
723use crate::{MatchArm, PatCx, PrivateUninhabitedField, checks};
724#[cfg(not(feature = "rustc"))]
725pub fn ensure_sufficient_stack<R>(f: impl FnOnce() -> R) -> R {
726    f()
727}
728
729/// A pattern is a "branch" if it is the immediate child of an or-pattern, or if it is the whole
730/// pattern of a match arm. These are the patterns that can be meaningfully considered "redundant",
731/// since e.g. `0` in `(0, 1)` cannot be redundant on its own.
732///
733/// We track for each branch pattern whether it is useful, and if not why.
734struct BranchPatUsefulness<'p, Cx: PatCx> {
735    /// Whether this pattern is useful.
736    useful: bool,
737    /// A set of patterns that:
738    /// - come before this one in the match;
739    /// - intersect this one;
740    /// - at the end of the algorithm, if `!self.useful`, their union covers this pattern.
741    covered_by: FxHashSet<&'p DeconstructedPat<Cx>>,
742}
743
744impl<'p, Cx: PatCx> BranchPatUsefulness<'p, Cx> {
745    /// Update `self` with the usefulness information found in `row`.
746    fn update(&mut self, row: &MatrixRow<'p, Cx>, matrix: &Matrix<'p, Cx>) {
747        self.useful |= row.useful;
748        // This deserves an explanation: `intersects_at_least` does not contain all intersections
749        // because we skip irrelevant values (see the docs for `intersects_at_least` for an
750        // example). Yet we claim this suffices to build a covering set.
751        //
752        // Let `p` be our pattern. Assume it is found not useful. For a value `v`, if the value was
753        // relevant then we explored that value and found that there was another pattern `q` before
754        // `p` that matches it too. We therefore recorded an intersection with `q`. If `v` was
755        // irrelevant, we know there's another value `v2` that matches strictly fewer rows (while
756        // still matching our row) and is relevant. Since `p` is not useful, there must have been a
757        // `q` before `p` that matches `v2`, and we recorded that intersection. Since `v2` matches
758        // strictly fewer rows than `v`, `q` also matches `v`. In either case, we recorded in
759        // `intersects_at_least` a pattern that matches `v`. Hence using `intersects_at_least` is
760        // sufficient to build a covering set.
761        for row_id in row.intersects_at_least.iter() {
762            let row = &matrix.rows[row_id];
763            if row.useful && !row.is_under_guard {
764                if let PatOrWild::Pat(intersecting) = row.head() {
765                    self.covered_by.insert(intersecting);
766                }
767            }
768        }
769    }
770
771    /// Check whether this pattern is redundant, and if so explain why.
772    fn is_redundant(&self) -> Option<RedundancyExplanation<'p, Cx>> {
773        if self.useful {
774            None
775        } else {
776            // We avoid instability by sorting by `uid`. The order of `uid`s only depends on the
777            // pattern structure.
778            #[cfg_attr(feature = "rustc", allow(rustc::potential_query_instability))]
779            let mut covered_by: Vec<_> = self.covered_by.iter().copied().collect();
780            covered_by.sort_by_key(|pat| pat.uid); // sort to avoid instability
781            Some(RedundancyExplanation { covered_by })
782        }
783    }
784}
785
786impl<'p, Cx: PatCx> Default for BranchPatUsefulness<'p, Cx> {
787    fn default() -> Self {
788        Self { useful: Default::default(), covered_by: Default::default() }
789    }
790}
791
792/// Context that provides information for usefulness checking.
793struct UsefulnessCtxt<'a, 'p, Cx: PatCx> {
794    /// The context for type information.
795    tycx: &'a Cx,
796    /// Track information about the usefulness of branch patterns (see definition of "branch
797    /// pattern" at [`BranchPatUsefulness`]).
798    branch_usefulness: FxHashMap<PatId, BranchPatUsefulness<'p, Cx>>,
799    // Ideally this field would have type `Limit`, but this crate is used by
800    // rust-analyzer which cannot have a dependency on `Limit`, because `Limit`
801    // is from crate `rustc_session` which uses unstable Rust features.
802    complexity_limit: usize,
803    complexity_level: usize,
804}
805
806impl<'a, 'p, Cx: PatCx> UsefulnessCtxt<'a, 'p, Cx> {
807    fn increase_complexity_level(&mut self, complexity_add: usize) -> Result<(), Cx::Error> {
808        self.complexity_level += complexity_add;
809        if self.complexity_level <= self.complexity_limit {
810            Ok(())
811        } else {
812            self.tycx.complexity_exceeded()
813        }
814    }
815}
816
817/// Context that provides information local to a place under investigation.
818struct PlaceCtxt<'a, Cx: PatCx> {
819    cx: &'a Cx,
820    /// Type of the place under investigation.
821    ty: &'a Cx::Ty,
822}
823
824impl<'a, Cx: PatCx> Copy for PlaceCtxt<'a, Cx> {}
825impl<'a, Cx: PatCx> Clone for PlaceCtxt<'a, Cx> {
826    fn clone(&self) -> Self {
827        Self { cx: self.cx, ty: self.ty }
828    }
829}
830
831impl<'a, Cx: PatCx> fmt::Debug for PlaceCtxt<'a, Cx> {
832    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
833        fmt.debug_struct("PlaceCtxt").field("ty", self.ty).finish()
834    }
835}
836
837impl<'a, Cx: PatCx> PlaceCtxt<'a, Cx> {
838    fn ctor_arity(&self, ctor: &Constructor<Cx>) -> usize {
839        self.cx.ctor_arity(ctor, self.ty)
840    }
841    fn wild_from_ctor(&self, ctor: Constructor<Cx>) -> WitnessPat<Cx> {
842        WitnessPat::wild_from_ctor(self.cx, ctor, self.ty.clone())
843    }
844}
845
846/// Track whether a given place (aka column) is known to contain a valid value or not.
847#[derive(Debug, Copy, Clone, PartialEq, Eq)]
848pub enum PlaceValidity {
849    ValidOnly,
850    MaybeInvalid,
851}
852
853impl PlaceValidity {
854    pub fn from_bool(is_valid_only: bool) -> Self {
855        if is_valid_only { ValidOnly } else { MaybeInvalid }
856    }
857
858    fn is_known_valid(self) -> bool {
859        matches!(self, ValidOnly)
860    }
861
862    /// If the place has validity given by `self` and we read that the value at the place has
863    /// constructor `ctor`, this computes what we can assume about the validity of the constructor
864    /// fields.
865    ///
866    /// Pending further opsem decisions, the current behavior is: validity is preserved, except
867    /// inside `&` and union fields where validity is reset to `MaybeInvalid`.
868    fn specialize<Cx: PatCx>(self, ctor: &Constructor<Cx>) -> Self {
869        // We preserve validity except when we go inside a reference or a union field.
870        if matches!(ctor, Constructor::Ref | Constructor::DerefPattern(_) | Constructor::UnionField)
871        {
872            // Validity of `x: &T` does not imply validity of `*x: T`.
873            MaybeInvalid
874        } else {
875            self
876        }
877    }
878}
879
880impl fmt::Display for PlaceValidity {
881    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
882        let s = match self {
883            ValidOnly => "✓",
884            MaybeInvalid => "?",
885        };
886        write!(f, "{s}")
887    }
888}
889
890/// Data about a place under investigation. Its methods contain a lot of the logic used to analyze
891/// the constructors in the matrix.
892struct PlaceInfo<Cx: PatCx> {
893    /// The type of the place.
894    ty: Cx::Ty,
895    /// Whether the place is a private uninhabited field. If so we skip this field during analysis
896    /// so that we don't observe its emptiness.
897    private_uninhabited: bool,
898    /// Whether the place is known to contain valid data.
899    validity: PlaceValidity,
900    /// Whether the place is the scrutinee itself or a subplace of it.
901    is_scrutinee: bool,
902}
903
904impl<Cx: PatCx> PlaceInfo<Cx> {
905    /// Given a constructor for the current place, we return one `PlaceInfo` for each field of the
906    /// constructor.
907    fn specialize(
908        &self,
909        cx: &Cx,
910        ctor: &Constructor<Cx>,
911    ) -> impl Iterator<Item = Self> + ExactSizeIterator {
912        let ctor_sub_tys = cx.ctor_sub_tys(ctor, &self.ty);
913        let ctor_sub_validity = self.validity.specialize(ctor);
914        ctor_sub_tys.map(move |(ty, PrivateUninhabitedField(private_uninhabited))| PlaceInfo {
915            ty,
916            private_uninhabited,
917            validity: ctor_sub_validity,
918            is_scrutinee: false,
919        })
920    }
921
922    /// This analyzes a column of constructors corresponding to the current place. It returns a pair
923    /// `(split_ctors, missing_ctors)`.
924    ///
925    /// `split_ctors` is a splitted list of constructors that cover the whole type. This will be
926    /// used to specialize the matrix.
927    ///
928    /// `missing_ctors` is a list of the constructors not found in the column, for reporting
929    /// purposes.
930    fn split_column_ctors<'a>(
931        &self,
932        cx: &Cx,
933        ctors: impl Iterator<Item = &'a Constructor<Cx>> + Clone,
934    ) -> Result<(SmallVec<[Constructor<Cx>; 1]>, Vec<Constructor<Cx>>), Cx::Error>
935    where
936        Cx: 'a,
937    {
938        debug!(?self.ty);
939        if self.private_uninhabited {
940            // Skip the whole column
941            return Ok((smallvec![Constructor::PrivateUninhabited], vec![]));
942        }
943
944        if ctors.clone().any(|c| matches!(c, Constructor::Or)) {
945            // If any constructor is `Or`, we expand or-patterns.
946            return Ok((smallvec![Constructor::Or], vec![]));
947        }
948
949        let ctors_for_ty = cx.ctors_for_ty(&self.ty)?;
950        debug!(?ctors_for_ty);
951
952        // We treat match scrutinees of type `!` or `EmptyEnum` differently.
953        let is_toplevel_exception =
954            self.is_scrutinee && matches!(ctors_for_ty, ConstructorSet::NoConstructors);
955        // Whether empty patterns are counted as useful or not. We only warn an empty arm unreachable if
956        // it is guaranteed unreachable by the opsem (i.e. if the place is `known_valid`).
957        // We don't want to warn empty patterns as unreachable by default just yet. We will in a
958        // later version of rust or under a different lint name, see
959        // https://github.com/rust-lang/rust/pull/129103.
960        let empty_arms_are_unreachable = self.validity.is_known_valid()
961            && (is_toplevel_exception || cx.is_exhaustive_patterns_feature_on());
962        // Whether empty patterns can be omitted for exhaustiveness. We ignore place validity in the
963        // toplevel exception and `exhaustive_patterns` cases for backwards compatibility.
964        let can_omit_empty_arms = self.validity.is_known_valid()
965            || is_toplevel_exception
966            || cx.is_exhaustive_patterns_feature_on();
967
968        // Analyze the constructors present in this column.
969        let mut split_set = ctors_for_ty.split(ctors);
970        debug!(?split_set);
971        let all_missing = split_set.present.is_empty();
972
973        // Build the set of constructors we will specialize with. It must cover the whole type, so
974        // we add `Missing` to represent the missing ones. This is explained under "Constructor
975        // Splitting" at the top of this file.
976        let mut split_ctors = split_set.present;
977        if !(split_set.missing.is_empty()
978            && (split_set.missing_empty.is_empty() || empty_arms_are_unreachable))
979        {
980            split_ctors.push(Constructor::Missing);
981        }
982
983        // Which empty constructors are considered missing. We ensure that
984        // `!missing_ctors.is_empty() => split_ctors.contains(Missing)`. The converse usually holds
985        // except when `!self.validity.is_known_valid()`.
986        let mut missing_ctors = split_set.missing;
987        if !can_omit_empty_arms {
988            missing_ctors.append(&mut split_set.missing_empty);
989        }
990
991        // Whether we should report "Enum::A and Enum::C are missing" or "_ is missing". At the top
992        // level we prefer to list all constructors.
993        let report_individual_missing_ctors = self.is_scrutinee || !all_missing;
994        if !missing_ctors.is_empty() && !report_individual_missing_ctors {
995            // Report `_` as missing.
996            missing_ctors = vec![Constructor::Wildcard];
997        } else if missing_ctors.iter().any(|c| c.is_non_exhaustive()) && !cx.exhaustive_witnesses()
998        {
999            // We need to report a `_` anyway, so listing other constructors would be redundant.
1000            // `NonExhaustive` is displayed as `_` just like `Wildcard`, but it will be picked
1001            // up by diagnostics to add a note about why `_` is required here.
1002            missing_ctors = vec![Constructor::NonExhaustive];
1003        }
1004
1005        Ok((split_ctors, missing_ctors))
1006    }
1007}
1008
1009impl<Cx: PatCx> Clone for PlaceInfo<Cx> {
1010    fn clone(&self) -> Self {
1011        Self {
1012            ty: self.ty.clone(),
1013            private_uninhabited: self.private_uninhabited,
1014            validity: self.validity,
1015            is_scrutinee: self.is_scrutinee,
1016        }
1017    }
1018}
1019
1020/// Represents a pattern-tuple under investigation.
1021// The three lifetimes are:
1022// - 'p coming from the input
1023// - Cx global compilation context
1024struct PatStack<'p, Cx: PatCx> {
1025    // Rows of len 1 are very common, which is why `SmallVec[_; 2]` works well.
1026    pats: SmallVec<[PatOrWild<'p, Cx>; 2]>,
1027    /// Sometimes we know that as far as this row is concerned, the current case is already handled
1028    /// by a different, more general, case. When the case is irrelevant for all rows this allows us
1029    /// to skip a case entirely. This is purely an optimization. See at the top for details.
1030    relevant: bool,
1031}
1032
1033impl<'p, Cx: PatCx> Clone for PatStack<'p, Cx> {
1034    fn clone(&self) -> Self {
1035        Self { pats: self.pats.clone(), relevant: self.relevant }
1036    }
1037}
1038
1039impl<'p, Cx: PatCx> PatStack<'p, Cx> {
1040    fn from_pattern(pat: &'p DeconstructedPat<Cx>) -> Self {
1041        PatStack { pats: smallvec![PatOrWild::Pat(pat)], relevant: true }
1042    }
1043
1044    fn len(&self) -> usize {
1045        self.pats.len()
1046    }
1047
1048    fn head(&self) -> PatOrWild<'p, Cx> {
1049        self.pats[0]
1050    }
1051
1052    fn iter(&self) -> impl Iterator<Item = PatOrWild<'p, Cx>> {
1053        self.pats.iter().copied()
1054    }
1055
1056    // Expand the first or-pattern into its subpatterns. Only useful if the pattern is an
1057    // or-pattern. Panics if `self` is empty.
1058    fn expand_or_pat(&self) -> impl Iterator<Item = PatStack<'p, Cx>> {
1059        self.head().expand_or_pat().into_iter().map(move |pat| {
1060            let mut new = self.clone();
1061            new.pats[0] = pat;
1062            new
1063        })
1064    }
1065
1066    /// This computes `specialize(ctor, self)`. See top of the file for explanations.
1067    /// Only call if `ctor.is_covered_by(self.head().ctor())` is true.
1068    fn pop_head_constructor(
1069        &self,
1070        cx: &Cx,
1071        ctor: &Constructor<Cx>,
1072        ctor_arity: usize,
1073        ctor_is_relevant: bool,
1074    ) -> Result<PatStack<'p, Cx>, Cx::Error> {
1075        let head_pat = self.head();
1076        if head_pat.as_pat().is_some_and(|pat| pat.arity() > ctor_arity) {
1077            // Arity can be smaller in case of variable-length slices, but mustn't be larger.
1078            return Err(cx.bug(format_args!(
1079                "uncaught type error: pattern {:?} has inconsistent arity (expected arity <= {ctor_arity})",
1080                head_pat.as_pat().unwrap()
1081            )));
1082        }
1083        // We pop the head pattern and push the new fields extracted from the arguments of
1084        // `self.head()`.
1085        let mut new_pats = head_pat.specialize(ctor, ctor_arity);
1086        new_pats.extend_from_slice(&self.pats[1..]);
1087        // `ctor` is relevant for this row if it is the actual constructor of this row, or if the
1088        // row has a wildcard and `ctor` is relevant for wildcards.
1089        let ctor_is_relevant =
1090            !matches!(self.head().ctor(), Constructor::Wildcard) || ctor_is_relevant;
1091        Ok(PatStack { pats: new_pats, relevant: self.relevant && ctor_is_relevant })
1092    }
1093}
1094
1095impl<'p, Cx: PatCx> fmt::Debug for PatStack<'p, Cx> {
1096    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1097        // We pretty-print similarly to the `Debug` impl of `Matrix`.
1098        write!(f, "+")?;
1099        for pat in self.iter() {
1100            write!(f, " {pat:?} +")?;
1101        }
1102        Ok(())
1103    }
1104}
1105
1106/// A row of the matrix.
1107#[derive(Clone)]
1108struct MatrixRow<'p, Cx: PatCx> {
1109    // The patterns in the row.
1110    pats: PatStack<'p, Cx>,
1111    /// Whether the original arm had a guard. This is inherited when specializing.
1112    is_under_guard: bool,
1113    /// When we specialize, we remember which row of the original matrix produced a given row of the
1114    /// specialized matrix. When we unspecialize, we use this to propagate usefulness back up the
1115    /// callstack. On creation, this stores the index of the original match arm.
1116    parent_row: usize,
1117    /// False when the matrix is just built. This is set to `true` by
1118    /// [`compute_exhaustiveness_and_usefulness`] if the arm is found to be useful.
1119    /// This is reset to `false` when specializing.
1120    useful: bool,
1121    /// Tracks some rows above this one that have an intersection with this one, i.e. such that
1122    /// there is a value that matches both rows.
1123    /// Because of relevancy we may miss some intersections. The intersections we do find are
1124    /// correct. In other words, this is an underapproximation of the real set of intersections.
1125    ///
1126    /// For example:
1127    /// ```rust,ignore(illustrative)
1128    /// match ... {
1129    ///     (true, _, _) => {} // `intersects_at_least = []`
1130    ///     (_, true, 0..=10) => {} // `intersects_at_least = []`
1131    ///     (_, true, 5..15) => {} // `intersects_at_least = [1]`
1132    /// }
1133    /// ```
1134    /// Here the `(true, true)` case is irrelevant. Since we skip it, we will not detect that row 0
1135    /// intersects rows 1 and 2.
1136    intersects_at_least: DenseBitSet<usize>,
1137    /// Whether the head pattern is a branch (see definition of "branch pattern" at
1138    /// [`BranchPatUsefulness`])
1139    head_is_branch: bool,
1140}
1141
1142impl<'p, Cx: PatCx> MatrixRow<'p, Cx> {
1143    fn new(arm: &MatchArm<'p, Cx>, arm_id: usize) -> Self {
1144        MatrixRow {
1145            pats: PatStack::from_pattern(arm.pat),
1146            parent_row: arm_id,
1147            is_under_guard: arm.has_guard,
1148            useful: false,
1149            intersects_at_least: DenseBitSet::new_empty(0), // Initialized in `Matrix::push`.
1150            // This pattern is a branch because it comes from a match arm.
1151            head_is_branch: true,
1152        }
1153    }
1154
1155    fn len(&self) -> usize {
1156        self.pats.len()
1157    }
1158
1159    fn head(&self) -> PatOrWild<'p, Cx> {
1160        self.pats.head()
1161    }
1162
1163    fn iter(&self) -> impl Iterator<Item = PatOrWild<'p, Cx>> {
1164        self.pats.iter()
1165    }
1166
1167    // Expand the first or-pattern (if any) into its subpatterns. Panics if `self` is empty.
1168    fn expand_or_pat(&self, parent_row: usize) -> impl Iterator<Item = MatrixRow<'p, Cx>> {
1169        let is_or_pat = self.pats.head().is_or_pat();
1170        self.pats.expand_or_pat().map(move |patstack| MatrixRow {
1171            pats: patstack,
1172            parent_row,
1173            is_under_guard: self.is_under_guard,
1174            useful: false,
1175            intersects_at_least: DenseBitSet::new_empty(0), // Initialized in `Matrix::push`.
1176            head_is_branch: is_or_pat,
1177        })
1178    }
1179
1180    /// This computes `specialize(ctor, self)`. See top of the file for explanations.
1181    /// Only call if `ctor.is_covered_by(self.head().ctor())` is true.
1182    fn pop_head_constructor(
1183        &self,
1184        cx: &Cx,
1185        ctor: &Constructor<Cx>,
1186        ctor_arity: usize,
1187        ctor_is_relevant: bool,
1188        parent_row: usize,
1189    ) -> Result<MatrixRow<'p, Cx>, Cx::Error> {
1190        Ok(MatrixRow {
1191            pats: self.pats.pop_head_constructor(cx, ctor, ctor_arity, ctor_is_relevant)?,
1192            parent_row,
1193            is_under_guard: self.is_under_guard,
1194            useful: false,
1195            intersects_at_least: DenseBitSet::new_empty(0), // Initialized in `Matrix::push`.
1196            head_is_branch: false,
1197        })
1198    }
1199}
1200
1201impl<'p, Cx: PatCx> fmt::Debug for MatrixRow<'p, Cx> {
1202    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1203        self.pats.fmt(f)
1204    }
1205}
1206
1207/// A 2D matrix. Represents a list of pattern-tuples under investigation.
1208///
1209/// Invariant: each row must have the same length, and each column must have the same type.
1210///
1211/// Invariant: the first column must not contain or-patterns. This is handled by
1212/// [`Matrix::push`].
1213///
1214/// In fact each column corresponds to a place inside the scrutinee of the match. E.g. after
1215/// specializing `(,)` and `Some` on a pattern of type `(Option<u32>, bool)`, the first column of
1216/// the matrix will correspond to `scrutinee.0.Some.0` and the second column to `scrutinee.1`.
1217#[derive(Clone)]
1218struct Matrix<'p, Cx: PatCx> {
1219    /// Vector of rows. The rows must form a rectangular 2D array. Moreover, all the patterns of
1220    /// each column must have the same type. Each column corresponds to a place within the
1221    /// scrutinee.
1222    rows: Vec<MatrixRow<'p, Cx>>,
1223    /// Track info about each place. Each place corresponds to a column in `rows`, and their types
1224    /// must match.
1225    place_info: SmallVec<[PlaceInfo<Cx>; 2]>,
1226    /// Track whether the virtual wildcard row used to compute exhaustiveness is relevant. See top
1227    /// of the file for details on relevancy.
1228    wildcard_row_is_relevant: bool,
1229}
1230
1231impl<'p, Cx: PatCx> Matrix<'p, Cx> {
1232    /// Pushes a new row to the matrix. Internal method, prefer [`Matrix::new`].
1233    fn push(&mut self, mut row: MatrixRow<'p, Cx>) {
1234        row.intersects_at_least = DenseBitSet::new_empty(self.rows.len());
1235        self.rows.push(row);
1236    }
1237
1238    /// Build a new matrix from an iterator of `MatchArm`s.
1239    fn new(arms: &[MatchArm<'p, Cx>], scrut_ty: Cx::Ty, scrut_validity: PlaceValidity) -> Self {
1240        let place_info = PlaceInfo {
1241            ty: scrut_ty,
1242            private_uninhabited: false,
1243            validity: scrut_validity,
1244            is_scrutinee: true,
1245        };
1246        let mut matrix = Matrix {
1247            rows: Vec::with_capacity(arms.len()),
1248            place_info: smallvec![place_info],
1249            wildcard_row_is_relevant: true,
1250        };
1251        for (arm_id, arm) in arms.iter().enumerate() {
1252            matrix.push(MatrixRow::new(arm, arm_id));
1253        }
1254        matrix
1255    }
1256
1257    fn head_place(&self) -> Option<&PlaceInfo<Cx>> {
1258        self.place_info.first()
1259    }
1260    fn column_count(&self) -> usize {
1261        self.place_info.len()
1262    }
1263
1264    fn rows(
1265        &self,
1266    ) -> impl Iterator<Item = &MatrixRow<'p, Cx>> + Clone + DoubleEndedIterator + ExactSizeIterator
1267    {
1268        self.rows.iter()
1269    }
1270    fn rows_mut(
1271        &mut self,
1272    ) -> impl Iterator<Item = &mut MatrixRow<'p, Cx>> + DoubleEndedIterator + ExactSizeIterator
1273    {
1274        self.rows.iter_mut()
1275    }
1276
1277    /// Iterate over the first pattern of each row.
1278    fn heads(&self) -> impl Iterator<Item = PatOrWild<'p, Cx>> + Clone {
1279        self.rows().map(|r| r.head())
1280    }
1281
1282    /// This computes `specialize(ctor, self)`. See top of the file for explanations.
1283    fn specialize_constructor(
1284        &self,
1285        pcx: &PlaceCtxt<'_, Cx>,
1286        ctor: &Constructor<Cx>,
1287        ctor_is_relevant: bool,
1288    ) -> Result<Matrix<'p, Cx>, Cx::Error> {
1289        if matches!(ctor, Constructor::Or) {
1290            // Specializing with `Or` means expanding rows with or-patterns.
1291            let mut matrix = Matrix {
1292                rows: Vec::new(),
1293                place_info: self.place_info.clone(),
1294                wildcard_row_is_relevant: self.wildcard_row_is_relevant,
1295            };
1296            for (i, row) in self.rows().enumerate() {
1297                for new_row in row.expand_or_pat(i) {
1298                    matrix.push(new_row);
1299                }
1300            }
1301            Ok(matrix)
1302        } else {
1303            let subfield_place_info = self.place_info[0].specialize(pcx.cx, ctor);
1304            let arity = subfield_place_info.len();
1305            let specialized_place_info =
1306                subfield_place_info.chain(self.place_info[1..].iter().cloned()).collect();
1307            let mut matrix = Matrix {
1308                rows: Vec::new(),
1309                place_info: specialized_place_info,
1310                wildcard_row_is_relevant: self.wildcard_row_is_relevant && ctor_is_relevant,
1311            };
1312            for (i, row) in self.rows().enumerate() {
1313                if ctor.is_covered_by(pcx.cx, row.head().ctor())? {
1314                    let new_row =
1315                        row.pop_head_constructor(pcx.cx, ctor, arity, ctor_is_relevant, i)?;
1316                    matrix.push(new_row);
1317                }
1318            }
1319            Ok(matrix)
1320        }
1321    }
1322
1323    /// Recover row usefulness and intersection information from a processed specialized matrix.
1324    /// `specialized` must come from `self.specialize_constructor`.
1325    fn unspecialize(&mut self, specialized: Self) {
1326        for child_row in specialized.rows() {
1327            let parent_row_id = child_row.parent_row;
1328            let parent_row = &mut self.rows[parent_row_id];
1329            // A parent row is useful if any of its children is.
1330            parent_row.useful |= child_row.useful;
1331            for child_intersection in child_row.intersects_at_least.iter() {
1332                // Convert the intersecting ids into ids for the parent matrix.
1333                let parent_intersection = specialized.rows[child_intersection].parent_row;
1334                // Note: self-intersection can happen with or-patterns.
1335                if parent_intersection != parent_row_id {
1336                    parent_row.intersects_at_least.insert(parent_intersection);
1337                }
1338            }
1339        }
1340    }
1341}
1342
1343/// Pretty-printer for matrices of patterns, example:
1344///
1345/// ```text
1346/// + _     + []                +
1347/// + true  + [First]           +
1348/// + true  + [Second(true)]    +
1349/// + false + [_]               +
1350/// + _     + [_, _, tail @ ..] +
1351/// | ✓     | ?                 | // validity
1352/// ```
1353impl<'p, Cx: PatCx> fmt::Debug for Matrix<'p, Cx> {
1354    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1355        write!(f, "\n")?;
1356
1357        let mut pretty_printed_matrix: Vec<Vec<String>> = self
1358            .rows
1359            .iter()
1360            .map(|row| row.iter().map(|pat| format!("{pat:?}")).collect())
1361            .collect();
1362        pretty_printed_matrix
1363            .push(self.place_info.iter().map(|place| format!("{}", place.validity)).collect());
1364
1365        let column_count = self.column_count();
1366        assert!(self.rows.iter().all(|row| row.len() == column_count));
1367        assert!(self.place_info.len() == column_count);
1368        let column_widths: Vec<usize> = (0..column_count)
1369            .map(|col| pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0))
1370            .collect();
1371
1372        for (row_i, row) in pretty_printed_matrix.into_iter().enumerate() {
1373            let is_validity_row = row_i == self.rows.len();
1374            let sep = if is_validity_row { "|" } else { "+" };
1375            write!(f, "{sep}")?;
1376            for (column, pat_str) in row.into_iter().enumerate() {
1377                write!(f, " ")?;
1378                write!(f, "{:1$}", pat_str, column_widths[column])?;
1379                write!(f, " {sep}")?;
1380            }
1381            if is_validity_row {
1382                write!(f, " // validity")?;
1383            }
1384            write!(f, "\n")?;
1385        }
1386        Ok(())
1387    }
1388}
1389
1390/// A witness-tuple of non-exhaustiveness for error reporting, represented as a list of patterns (in
1391/// reverse order of construction).
1392///
1393/// This mirrors `PatStack`: they function similarly, except `PatStack` contains user patterns we
1394/// are inspecting, and `WitnessStack` contains witnesses we are constructing.
1395/// FIXME(Nadrieril): use the same order of patterns for both.
1396///
1397/// A `WitnessStack` should have the same types and length as the `PatStack`s we are inspecting
1398/// (except we store the patterns in reverse order). The same way `PatStack` starts with length 1,
1399/// at the end of the algorithm this will have length 1. In the middle of the algorithm, it can
1400/// contain multiple patterns.
1401///
1402/// For example, if we are constructing a witness for the match against
1403///
1404/// ```compile_fail,E0004
1405/// struct Pair(Option<(u32, u32)>, bool);
1406/// # fn foo(p: Pair) {
1407/// match p {
1408///    Pair(None, _) => {}
1409///    Pair(_, false) => {}
1410/// }
1411/// # }
1412/// ```
1413///
1414/// We'll perform the following steps (among others):
1415/// ```text
1416/// - Start with a matrix representing the match
1417///     `PatStack(vec![Pair(None, _)])`
1418///     `PatStack(vec![Pair(_, false)])`
1419/// - Specialize with `Pair`
1420///     `PatStack(vec![None, _])`
1421///     `PatStack(vec![_, false])`
1422/// - Specialize with `Some`
1423///     `PatStack(vec![_, false])`
1424/// - Specialize with `_`
1425///     `PatStack(vec![false])`
1426/// - Specialize with `true`
1427///     // no patstacks left
1428/// - This is a non-exhaustive match: we have the empty witness stack as a witness.
1429///     `WitnessStack(vec![])`
1430/// - Apply `true`
1431///     `WitnessStack(vec![true])`
1432/// - Apply `_`
1433///     `WitnessStack(vec![true, _])`
1434/// - Apply `Some`
1435///     `WitnessStack(vec![true, Some(_)])`
1436/// - Apply `Pair`
1437///     `WitnessStack(vec![Pair(Some(_), true)])`
1438/// ```
1439///
1440/// The final `Pair(Some(_), true)` is then the resulting witness.
1441///
1442/// See the top of the file for more detailed explanations and examples.
1443#[derive(Debug)]
1444struct WitnessStack<Cx: PatCx>(Vec<WitnessPat<Cx>>);
1445
1446impl<Cx: PatCx> Clone for WitnessStack<Cx> {
1447    fn clone(&self) -> Self {
1448        Self(self.0.clone())
1449    }
1450}
1451
1452impl<Cx: PatCx> WitnessStack<Cx> {
1453    /// Asserts that the witness contains a single pattern, and returns it.
1454    fn single_pattern(self) -> WitnessPat<Cx> {
1455        assert_eq!(self.0.len(), 1);
1456        self.0.into_iter().next().unwrap()
1457    }
1458
1459    /// Reverses specialization by the `Missing` constructor by pushing a whole new pattern.
1460    fn push_pattern(&mut self, pat: WitnessPat<Cx>) {
1461        self.0.push(pat);
1462    }
1463
1464    /// Reverses specialization. Given a witness obtained after specialization, this constructs a
1465    /// new witness valid for before specialization. See the section on `unspecialize` at the top of
1466    /// the file.
1467    ///
1468    /// Examples:
1469    /// ```text
1470    /// ctor: tuple of 2 elements
1471    /// pats: [false, "foo", _, true]
1472    /// result: [(false, "foo"), _, true]
1473    ///
1474    /// ctor: Enum::Variant { a: (bool, &'static str), b: usize}
1475    /// pats: [(false, "foo"), _, true]
1476    /// result: [Enum::Variant { a: (false, "foo"), b: _ }, true]
1477    /// ```
1478    fn apply_constructor(
1479        mut self,
1480        pcx: &PlaceCtxt<'_, Cx>,
1481        ctor: &Constructor<Cx>,
1482    ) -> SmallVec<[Self; 1]> {
1483        let len = self.0.len();
1484        let arity = pcx.ctor_arity(ctor);
1485        let fields: Vec<_> = self.0.drain((len - arity)..).rev().collect();
1486        if matches!(ctor, Constructor::UnionField)
1487            && fields.iter().filter(|p| !matches!(p.ctor(), Constructor::Wildcard)).count() >= 2
1488        {
1489            // Convert a `Union { a: p, b: q }` witness into `Union { a: p }` and `Union { b: q }`.
1490            // First add `Union { .. }` to `self`.
1491            self.0.push(WitnessPat::wild_from_ctor(pcx.cx, ctor.clone(), pcx.ty.clone()));
1492            fields
1493                .into_iter()
1494                .enumerate()
1495                .filter(|(_, p)| !matches!(p.ctor(), Constructor::Wildcard))
1496                .map(|(i, p)| {
1497                    let mut ret = self.clone();
1498                    // Fill the `i`th field of the union with `p`.
1499                    ret.0.last_mut().unwrap().fields[i] = p;
1500                    ret
1501                })
1502                .collect()
1503        } else {
1504            self.0.push(WitnessPat::new(ctor.clone(), fields, pcx.ty.clone()));
1505            smallvec![self]
1506        }
1507    }
1508}
1509
1510/// Represents a set of pattern-tuples that are witnesses of non-exhaustiveness for error
1511/// reporting. This has similar invariants as `Matrix` does.
1512///
1513/// The `WitnessMatrix` returned by [`compute_exhaustiveness_and_usefulness`] obeys the invariant
1514/// that the union of the input `Matrix` and the output `WitnessMatrix` together matches the type
1515/// exhaustively.
1516///
1517/// Just as the `Matrix` starts with a single column, by the end of the algorithm, this has a single
1518/// column, which contains the patterns that are missing for the match to be exhaustive.
1519#[derive(Debug)]
1520struct WitnessMatrix<Cx: PatCx>(Vec<WitnessStack<Cx>>);
1521
1522impl<Cx: PatCx> Clone for WitnessMatrix<Cx> {
1523    fn clone(&self) -> Self {
1524        Self(self.0.clone())
1525    }
1526}
1527
1528impl<Cx: PatCx> WitnessMatrix<Cx> {
1529    /// New matrix with no witnesses.
1530    fn empty() -> Self {
1531        WitnessMatrix(Vec::new())
1532    }
1533    /// New matrix with one `()` witness, i.e. with no columns.
1534    fn unit_witness() -> Self {
1535        WitnessMatrix(vec![WitnessStack(Vec::new())])
1536    }
1537
1538    /// Whether this has any witnesses.
1539    fn is_empty(&self) -> bool {
1540        self.0.is_empty()
1541    }
1542    /// Asserts that there is a single column and returns the patterns in it.
1543    fn single_column(self) -> Vec<WitnessPat<Cx>> {
1544        self.0.into_iter().map(|w| w.single_pattern()).collect()
1545    }
1546
1547    /// Reverses specialization by the `Missing` constructor by pushing a whole new pattern.
1548    fn push_pattern(&mut self, pat: WitnessPat<Cx>) {
1549        for witness in self.0.iter_mut() {
1550            witness.push_pattern(pat.clone())
1551        }
1552    }
1553
1554    /// Reverses specialization by `ctor`. See the section on `unspecialize` at the top of the file.
1555    fn apply_constructor(
1556        &mut self,
1557        pcx: &PlaceCtxt<'_, Cx>,
1558        missing_ctors: &[Constructor<Cx>],
1559        ctor: &Constructor<Cx>,
1560    ) {
1561        // The `Or` constructor indicates that we expanded or-patterns. This doesn't affect
1562        // witnesses.
1563        if self.is_empty() || matches!(ctor, Constructor::Or) {
1564            return;
1565        }
1566        if matches!(ctor, Constructor::Missing) {
1567            // We got the special `Missing` constructor that stands for the constructors not present
1568            // in the match. For each missing constructor `c`, we add a `c(_, _, _)` witness
1569            // appropriately filled with wildcards.
1570            let mut ret = Self::empty();
1571            for ctor in missing_ctors {
1572                let pat = pcx.wild_from_ctor(ctor.clone());
1573                // Clone `self` and add `c(_, _, _)` to each of its witnesses.
1574                let mut wit_matrix = self.clone();
1575                wit_matrix.push_pattern(pat);
1576                ret.extend(wit_matrix);
1577            }
1578            *self = ret;
1579        } else {
1580            // Any other constructor we unspecialize as expected.
1581            for witness in std::mem::take(&mut self.0) {
1582                self.0.extend(witness.apply_constructor(pcx, ctor));
1583            }
1584        }
1585    }
1586
1587    /// Merges the witnesses of two matrices. Their column types must match.
1588    fn extend(&mut self, other: Self) {
1589        self.0.extend(other.0)
1590    }
1591}
1592
1593/// Collect ranges that overlap like `lo..=overlap`/`overlap..=hi`. Must be called during
1594/// exhaustiveness checking, if we find a singleton range after constructor splitting. This reuses
1595/// row intersection information to only detect ranges that truly overlap.
1596///
1597/// If two ranges overlapped, the split set will contain their intersection as a singleton.
1598/// Specialization will then select rows that match the overlap, and exhaustiveness will compute
1599/// which rows have an intersection that includes the overlap. That gives us all the info we need to
1600/// compute overlapping ranges without false positives.
1601///
1602/// We can however get false negatives because exhaustiveness does not explore all cases. See the
1603/// section on relevancy at the top of the file.
1604fn collect_overlapping_range_endpoints<'p, Cx: PatCx>(
1605    cx: &Cx,
1606    overlap_range: IntRange,
1607    matrix: &Matrix<'p, Cx>,
1608    specialized_matrix: &Matrix<'p, Cx>,
1609) {
1610    let overlap = overlap_range.lo;
1611    // Ranges that look like `lo..=overlap`.
1612    let mut prefixes: SmallVec<[_; 1]> = Default::default();
1613    // Ranges that look like `overlap..=hi`.
1614    let mut suffixes: SmallVec<[_; 1]> = Default::default();
1615    // Iterate on patterns that contained `overlap`. We iterate on `specialized_matrix` which
1616    // contains only rows that matched the current `ctor` as well as accurate intersection
1617    // information. It doesn't contain the column that contains the range; that can be found in
1618    // `matrix`.
1619    for (child_row_id, child_row) in specialized_matrix.rows().enumerate() {
1620        let PatOrWild::Pat(pat) = matrix.rows[child_row.parent_row].head() else { continue };
1621        let Constructor::IntRange(this_range) = pat.ctor() else { continue };
1622        // Don't lint when one of the ranges is a singleton.
1623        if this_range.is_singleton() {
1624            continue;
1625        }
1626        if this_range.lo == overlap {
1627            // `this_range` looks like `overlap..=this_range.hi`; it overlaps with any
1628            // ranges that look like `lo..=overlap`.
1629            if !prefixes.is_empty() {
1630                let overlaps_with: Vec<_> = prefixes
1631                    .iter()
1632                    .filter(|&&(other_child_row_id, _)| {
1633                        child_row.intersects_at_least.contains(other_child_row_id)
1634                    })
1635                    .map(|&(_, pat)| pat)
1636                    .collect();
1637                if !overlaps_with.is_empty() {
1638                    cx.lint_overlapping_range_endpoints(pat, overlap_range, &overlaps_with);
1639                }
1640            }
1641            suffixes.push((child_row_id, pat))
1642        } else if Some(this_range.hi) == overlap.plus_one() {
1643            // `this_range` looks like `this_range.lo..=overlap`; it overlaps with any
1644            // ranges that look like `overlap..=hi`.
1645            if !suffixes.is_empty() {
1646                let overlaps_with: Vec<_> = suffixes
1647                    .iter()
1648                    .filter(|&&(other_child_row_id, _)| {
1649                        child_row.intersects_at_least.contains(other_child_row_id)
1650                    })
1651                    .map(|&(_, pat)| pat)
1652                    .collect();
1653                if !overlaps_with.is_empty() {
1654                    cx.lint_overlapping_range_endpoints(pat, overlap_range, &overlaps_with);
1655                }
1656            }
1657            prefixes.push((child_row_id, pat))
1658        }
1659    }
1660}
1661
1662/// Collect ranges that have a singleton gap between them.
1663fn collect_non_contiguous_range_endpoints<'p, Cx: PatCx>(
1664    cx: &Cx,
1665    gap_range: &IntRange,
1666    matrix: &Matrix<'p, Cx>,
1667) {
1668    let gap = gap_range.lo;
1669    // Ranges that look like `lo..gap`.
1670    let mut onebefore: SmallVec<[_; 1]> = Default::default();
1671    // Ranges that start on `gap+1` or singletons `gap+1`.
1672    let mut oneafter: SmallVec<[_; 1]> = Default::default();
1673    // Look through the column for ranges near the gap.
1674    for pat in matrix.heads() {
1675        let PatOrWild::Pat(pat) = pat else { continue };
1676        let Constructor::IntRange(this_range) = pat.ctor() else { continue };
1677        if gap == this_range.hi {
1678            onebefore.push(pat)
1679        } else if gap.plus_one() == Some(this_range.lo) {
1680            oneafter.push(pat)
1681        }
1682    }
1683
1684    for pat_before in onebefore {
1685        cx.lint_non_contiguous_range_endpoints(pat_before, *gap_range, oneafter.as_slice());
1686    }
1687}
1688
1689/// The core of the algorithm.
1690///
1691/// This recursively computes witnesses of the non-exhaustiveness of `matrix` (if any). Also tracks
1692/// usefulness of each row in the matrix (in `row.useful`). We track usefulness of subpatterns in
1693/// `mcx.branch_usefulness`.
1694///
1695/// The input `Matrix` and the output `WitnessMatrix` together match the type exhaustively.
1696///
1697/// The key steps are:
1698/// - specialization, where we dig into the rows that have a specific constructor and call ourselves
1699///     recursively;
1700/// - unspecialization, where we lift the results from the previous step into results for this step
1701///     (using `apply_constructor` and by updating `row.useful` for each parent row).
1702/// This is all explained at the top of the file.
1703#[instrument(level = "debug", skip(mcx), ret)]
1704fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: PatCx>(
1705    mcx: &mut UsefulnessCtxt<'a, 'p, Cx>,
1706    matrix: &mut Matrix<'p, Cx>,
1707) -> Result<WitnessMatrix<Cx>, Cx::Error> {
1708    debug_assert!(matrix.rows().all(|r| r.len() == matrix.column_count()));
1709
1710    if !matrix.wildcard_row_is_relevant && matrix.rows().all(|r| !r.pats.relevant) {
1711        // Here we know that nothing will contribute further to exhaustiveness or usefulness. This
1712        // is purely an optimization: skipping this check doesn't affect correctness. See the top of
1713        // the file for details.
1714        return Ok(WitnessMatrix::empty());
1715    }
1716
1717    let Some(place) = matrix.head_place() else {
1718        mcx.increase_complexity_level(matrix.rows().len())?;
1719        // The base case: there are no columns in the matrix. We are morally pattern-matching on ().
1720        // A row is useful iff it has no (unguarded) rows above it.
1721        let mut useful = true; // Whether the next row is useful.
1722        for (i, row) in matrix.rows_mut().enumerate() {
1723            row.useful = useful;
1724            row.intersects_at_least.insert_range(0..i);
1725            // The next rows stays useful if this one is under a guard.
1726            useful &= row.is_under_guard;
1727        }
1728        return if useful && matrix.wildcard_row_is_relevant {
1729            // The wildcard row is useful; the match is non-exhaustive.
1730            Ok(WitnessMatrix::unit_witness())
1731        } else {
1732            // Either the match is exhaustive, or we choose not to report anything because of
1733            // relevancy. See at the top for details.
1734            Ok(WitnessMatrix::empty())
1735        };
1736    };
1737
1738    // Analyze the constructors present in this column.
1739    let ctors = matrix.heads().map(|p| p.ctor());
1740    let (split_ctors, missing_ctors) = place.split_column_ctors(mcx.tycx, ctors)?;
1741
1742    let ty = &place.ty.clone(); // Clone it out so we can mutate `matrix` later.
1743    let pcx = &PlaceCtxt { cx: mcx.tycx, ty };
1744    let mut ret = WitnessMatrix::empty();
1745    for ctor in split_ctors {
1746        // Dig into rows that match `ctor`.
1747        debug!("specialize({:?})", ctor);
1748        // `ctor` is *irrelevant* if there's another constructor in `split_ctors` that matches
1749        // strictly fewer rows. In that case we can sometimes skip it. See the top of the file for
1750        // details.
1751        let ctor_is_relevant = matches!(ctor, Constructor::Missing)
1752            || missing_ctors.is_empty()
1753            || mcx.tycx.exhaustive_witnesses();
1754        let mut spec_matrix = matrix.specialize_constructor(pcx, &ctor, ctor_is_relevant)?;
1755        let mut witnesses = ensure_sufficient_stack(|| {
1756            compute_exhaustiveness_and_usefulness(mcx, &mut spec_matrix)
1757        })?;
1758
1759        // Transform witnesses for `spec_matrix` into witnesses for `matrix`.
1760        witnesses.apply_constructor(pcx, &missing_ctors, &ctor);
1761        // Accumulate the found witnesses.
1762        ret.extend(witnesses);
1763
1764        // Detect ranges that overlap on their endpoints.
1765        if let Constructor::IntRange(overlap_range) = ctor {
1766            if overlap_range.is_singleton()
1767                && spec_matrix.rows.len() >= 2
1768                && spec_matrix.rows.iter().any(|row| !row.intersects_at_least.is_empty())
1769            {
1770                collect_overlapping_range_endpoints(mcx.tycx, overlap_range, matrix, &spec_matrix);
1771            }
1772        }
1773
1774        matrix.unspecialize(spec_matrix);
1775    }
1776
1777    // Detect singleton gaps between ranges.
1778    if missing_ctors.iter().any(|c| matches!(c, Constructor::IntRange(..))) {
1779        for missing in &missing_ctors {
1780            if let Constructor::IntRange(gap) = missing {
1781                if gap.is_singleton() {
1782                    collect_non_contiguous_range_endpoints(mcx.tycx, gap, matrix);
1783                }
1784            }
1785        }
1786    }
1787
1788    // Record usefulness of the branch patterns.
1789    for row in matrix.rows() {
1790        if row.head_is_branch {
1791            if let PatOrWild::Pat(pat) = row.head() {
1792                mcx.branch_usefulness.entry(pat.uid).or_default().update(row, matrix);
1793            }
1794        }
1795    }
1796
1797    Ok(ret)
1798}
1799
1800/// Indicates why a given pattern is considered redundant.
1801#[derive(Clone, Debug)]
1802pub struct RedundancyExplanation<'p, Cx: PatCx> {
1803    /// All the values matched by this pattern are already matched by the given set of patterns.
1804    /// This list is not guaranteed to be minimal but the contained patterns are at least guaranteed
1805    /// to intersect this pattern.
1806    pub covered_by: Vec<&'p DeconstructedPat<Cx>>,
1807}
1808
1809/// Indicates whether or not a given arm is useful.
1810#[derive(Clone, Debug)]
1811pub enum Usefulness<'p, Cx: PatCx> {
1812    /// The arm is useful. This additionally carries a set of or-pattern branches that have been
1813    /// found to be redundant despite the overall arm being useful. Used only in the presence of
1814    /// or-patterns, otherwise it stays empty.
1815    Useful(Vec<(&'p DeconstructedPat<Cx>, RedundancyExplanation<'p, Cx>)>),
1816    /// The arm is redundant and can be removed without changing the behavior of the match
1817    /// expression.
1818    Redundant(RedundancyExplanation<'p, Cx>),
1819}
1820
1821/// The output of checking a match for exhaustiveness and arm usefulness.
1822pub struct UsefulnessReport<'p, Cx: PatCx> {
1823    /// For each arm of the input, whether that arm is useful after the arms above it.
1824    pub arm_usefulness: Vec<(MatchArm<'p, Cx>, Usefulness<'p, Cx>)>,
1825    /// If the match is exhaustive, this is empty. If not, this contains witnesses for the lack of
1826    /// exhaustiveness.
1827    pub non_exhaustiveness_witnesses: Vec<WitnessPat<Cx>>,
1828    /// For each arm, a set of indices of arms above it that have non-empty intersection, i.e. there
1829    /// is a value matched by both arms. This may miss real intersections.
1830    pub arm_intersections: Vec<DenseBitSet<usize>>,
1831}
1832
1833/// Computes whether a match is exhaustive and which of its arms are useful.
1834#[instrument(skip(tycx, arms), level = "debug")]
1835pub fn compute_match_usefulness<'p, Cx: PatCx>(
1836    tycx: &Cx,
1837    arms: &[MatchArm<'p, Cx>],
1838    scrut_ty: Cx::Ty,
1839    scrut_validity: PlaceValidity,
1840    complexity_limit: usize,
1841) -> Result<UsefulnessReport<'p, Cx>, Cx::Error> {
1842    // The analysis doesn't support deref patterns mixed with normal constructors; error if present.
1843    if tycx.match_may_contain_deref_pats() {
1844        checks::detect_mixed_deref_pat_ctors(tycx, arms)?;
1845    }
1846
1847    let mut cx = UsefulnessCtxt {
1848        tycx,
1849        branch_usefulness: FxHashMap::default(),
1850        complexity_limit,
1851        complexity_level: 0,
1852    };
1853    let mut matrix = Matrix::new(arms, scrut_ty, scrut_validity);
1854    let non_exhaustiveness_witnesses = compute_exhaustiveness_and_usefulness(&mut cx, &mut matrix)?;
1855
1856    let non_exhaustiveness_witnesses: Vec<_> = non_exhaustiveness_witnesses.single_column();
1857    let arm_usefulness: Vec<_> = arms
1858        .iter()
1859        .copied()
1860        .map(|arm| {
1861            debug!(?arm);
1862            let usefulness = cx.branch_usefulness.get(&arm.pat.uid).unwrap();
1863            let usefulness = if let Some(explanation) = usefulness.is_redundant() {
1864                Usefulness::Redundant(explanation)
1865            } else {
1866                let mut redundant_subpats = Vec::new();
1867                arm.pat.walk(&mut |subpat| {
1868                    if let Some(u) = cx.branch_usefulness.get(&subpat.uid) {
1869                        if let Some(explanation) = u.is_redundant() {
1870                            redundant_subpats.push((subpat, explanation));
1871                            false // stop recursing
1872                        } else {
1873                            true // keep recursing
1874                        }
1875                    } else {
1876                        true // keep recursing
1877                    }
1878                });
1879                Usefulness::Useful(redundant_subpats)
1880            };
1881            debug!(?usefulness);
1882            (arm, usefulness)
1883        })
1884        .collect();
1885
1886    let arm_intersections: Vec<_> =
1887        matrix.rows().map(|row| row.intersects_at_least.clone()).collect();
1888
1889    Ok(UsefulnessReport { arm_usefulness, non_exhaustiveness_witnesses, arm_intersections })
1890}