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 matcheable 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 matcheable 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//!   - probably many others
706//!
707//! I (Nadrieril) prefer to put new tests in `ui/pattern/usefulness` unless there's a specific
708//! reason not to, for example if they crucially depend on a particular feature like `or_patterns`.
709
710use std::fmt;
711
712#[cfg(feature = "rustc")]
713use rustc_data_structures::stack::ensure_sufficient_stack;
714use rustc_hash::{FxHashMap, FxHashSet};
715use rustc_index::bit_set::DenseBitSet;
716use smallvec::{SmallVec, smallvec};
717use tracing::{debug, instrument};
718
719use self::PlaceValidity::*;
720use crate::constructor::{Constructor, ConstructorSet, IntRange};
721use crate::pat::{DeconstructedPat, PatId, PatOrWild, WitnessPat};
722use crate::{Captures, MatchArm, PatCx, PrivateUninhabitedField};
723#[cfg(not(feature = "rustc"))]
724pub fn ensure_sufficient_stack<R>(f: impl FnOnce() -> R) -> R {
725    f()
726}
727
728/// A pattern is a "branch" if it is the immediate child of an or-pattern, or if it is the whole
729/// pattern of a match arm. These are the patterns that can be meaningfully considered "redundant",
730/// since e.g. `0` in `(0, 1)` cannot be redundant on its own.
731///
732/// We track for each branch pattern whether it is useful, and if not why.
733struct BranchPatUsefulness<'p, Cx: PatCx> {
734    /// Whether this pattern is useful.
735    useful: bool,
736    /// A set of patterns that:
737    /// - come before this one in the match;
738    /// - intersect this one;
739    /// - at the end of the algorithm, if `!self.useful`, their union covers this pattern.
740    covered_by: FxHashSet<&'p DeconstructedPat<Cx>>,
741}
742
743impl<'p, Cx: PatCx> BranchPatUsefulness<'p, Cx> {
744    /// Update `self` with the usefulness information found in `row`.
745    fn update(&mut self, row: &MatrixRow<'p, Cx>, matrix: &Matrix<'p, Cx>) {
746        self.useful |= row.useful;
747        // This deserves an explanation: `intersects_at_least` does not contain all intersections
748        // because we skip irrelevant values (see the docs for `intersects_at_least` for an
749        // example). Yet we claim this suffices to build a covering set.
750        //
751        // Let `p` be our pattern. Assume it is found not useful. For a value `v`, if the value was
752        // relevant then we explored that value and found that there was another pattern `q` before
753        // `p` that matches it too. We therefore recorded an intersection with `q`. If `v` was
754        // irrelevant, we know there's another value `v2` that matches strictly fewer rows (while
755        // still matching our row) and is relevant. Since `p` is not useful, there must have been a
756        // `q` before `p` that matches `v2`, and we recorded that intersection. Since `v2` matches
757        // strictly fewer rows than `v`, `q` also matches `v`. In either case, we recorded in
758        // `intersects_at_least` a pattern that matches `v`. Hence using `intersects_at_least` is
759        // sufficient to build a covering set.
760        for row_id in row.intersects_at_least.iter() {
761            let row = &matrix.rows[row_id];
762            if row.useful && !row.is_under_guard {
763                if let PatOrWild::Pat(intersecting) = row.head() {
764                    self.covered_by.insert(intersecting);
765                }
766            }
767        }
768    }
769
770    /// Check whether this pattern is redundant, and if so explain why.
771    fn is_redundant(&self) -> Option<RedundancyExplanation<'p, Cx>> {
772        if self.useful {
773            None
774        } else {
775            // We avoid instability by sorting by `uid`. The order of `uid`s only depends on the
776            // pattern structure.
777            #[cfg_attr(feature = "rustc", allow(rustc::potential_query_instability))]
778            let mut covered_by: Vec<_> = self.covered_by.iter().copied().collect();
779            covered_by.sort_by_key(|pat| pat.uid); // sort to avoid instability
780            Some(RedundancyExplanation { covered_by })
781        }
782    }
783}
784
785impl<'p, Cx: PatCx> Default for BranchPatUsefulness<'p, Cx> {
786    fn default() -> Self {
787        Self { useful: Default::default(), covered_by: Default::default() }
788    }
789}
790
791/// Context that provides information for usefulness checking.
792struct UsefulnessCtxt<'a, 'p, Cx: PatCx> {
793    /// The context for type information.
794    tycx: &'a Cx,
795    /// Track information about the usefulness of branch patterns (see definition of "branch
796    /// pattern" at [`BranchPatUsefulness`]).
797    branch_usefulness: FxHashMap<PatId, BranchPatUsefulness<'p, Cx>>,
798    complexity_limit: Option<usize>,
799    complexity_level: usize,
800}
801
802impl<'a, 'p, Cx: PatCx> UsefulnessCtxt<'a, 'p, Cx> {
803    fn increase_complexity_level(&mut self, complexity_add: usize) -> Result<(), Cx::Error> {
804        self.complexity_level += complexity_add;
805        if self
806            .complexity_limit
807            .is_some_and(|complexity_limit| complexity_limit < self.complexity_level)
808        {
809            return self.tycx.complexity_exceeded();
810        }
811        Ok(())
812    }
813}
814
815/// Context that provides information local to a place under investigation.
816struct PlaceCtxt<'a, Cx: PatCx> {
817    cx: &'a Cx,
818    /// Type of the place under investigation.
819    ty: &'a Cx::Ty,
820}
821
822impl<'a, Cx: PatCx> Copy for PlaceCtxt<'a, Cx> {}
823impl<'a, Cx: PatCx> Clone for PlaceCtxt<'a, Cx> {
824    fn clone(&self) -> Self {
825        Self { cx: self.cx, ty: self.ty }
826    }
827}
828
829impl<'a, Cx: PatCx> fmt::Debug for PlaceCtxt<'a, Cx> {
830    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
831        fmt.debug_struct("PlaceCtxt").field("ty", self.ty).finish()
832    }
833}
834
835impl<'a, Cx: PatCx> PlaceCtxt<'a, Cx> {
836    fn ctor_arity(&self, ctor: &Constructor<Cx>) -> usize {
837        self.cx.ctor_arity(ctor, self.ty)
838    }
839    fn wild_from_ctor(&self, ctor: Constructor<Cx>) -> WitnessPat<Cx> {
840        WitnessPat::wild_from_ctor(self.cx, ctor, self.ty.clone())
841    }
842}
843
844/// Track whether a given place (aka column) is known to contain a valid value or not.
845#[derive(Debug, Copy, Clone, PartialEq, Eq)]
846pub enum PlaceValidity {
847    ValidOnly,
848    MaybeInvalid,
849}
850
851impl PlaceValidity {
852    pub fn from_bool(is_valid_only: bool) -> Self {
853        if is_valid_only { ValidOnly } else { MaybeInvalid }
854    }
855
856    fn is_known_valid(self) -> bool {
857        matches!(self, ValidOnly)
858    }
859
860    /// If the place has validity given by `self` and we read that the value at the place has
861    /// constructor `ctor`, this computes what we can assume about the validity of the constructor
862    /// fields.
863    ///
864    /// Pending further opsem decisions, the current behavior is: validity is preserved, except
865    /// inside `&` and union fields where validity is reset to `MaybeInvalid`.
866    fn specialize<Cx: PatCx>(self, ctor: &Constructor<Cx>) -> Self {
867        // We preserve validity except when we go inside a reference or a union field.
868        if matches!(ctor, Constructor::Ref | Constructor::UnionField) {
869            // Validity of `x: &T` does not imply validity of `*x: T`.
870            MaybeInvalid
871        } else {
872            self
873        }
874    }
875}
876
877impl fmt::Display for PlaceValidity {
878    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
879        let s = match self {
880            ValidOnly => "✓",
881            MaybeInvalid => "?",
882        };
883        write!(f, "{s}")
884    }
885}
886
887/// Data about a place under investigation. Its methods contain a lot of the logic used to analyze
888/// the constructors in the matrix.
889struct PlaceInfo<Cx: PatCx> {
890    /// The type of the place.
891    ty: Cx::Ty,
892    /// Whether the place is a private uninhabited field. If so we skip this field during analysis
893    /// so that we don't observe its emptiness.
894    private_uninhabited: bool,
895    /// Whether the place is known to contain valid data.
896    validity: PlaceValidity,
897    /// Whether the place is the scrutinee itself or a subplace of it.
898    is_scrutinee: bool,
899}
900
901impl<Cx: PatCx> PlaceInfo<Cx> {
902    /// Given a constructor for the current place, we return one `PlaceInfo` for each field of the
903    /// constructor.
904    fn specialize<'a>(
905        &'a self,
906        cx: &'a Cx,
907        ctor: &'a Constructor<Cx>,
908    ) -> impl Iterator<Item = Self> + ExactSizeIterator + Captures<'a> {
909        let ctor_sub_tys = cx.ctor_sub_tys(ctor, &self.ty);
910        let ctor_sub_validity = self.validity.specialize(ctor);
911        ctor_sub_tys.map(move |(ty, PrivateUninhabitedField(private_uninhabited))| PlaceInfo {
912            ty,
913            private_uninhabited,
914            validity: ctor_sub_validity,
915            is_scrutinee: false,
916        })
917    }
918
919    /// This analyzes a column of constructors corresponding to the current place. It returns a pair
920    /// `(split_ctors, missing_ctors)`.
921    ///
922    /// `split_ctors` is a splitted list of constructors that cover the whole type. This will be
923    /// used to specialize the matrix.
924    ///
925    /// `missing_ctors` is a list of the constructors not found in the column, for reporting
926    /// purposes.
927    fn split_column_ctors<'a>(
928        &self,
929        cx: &Cx,
930        ctors: impl Iterator<Item = &'a Constructor<Cx>> + Clone,
931    ) -> Result<(SmallVec<[Constructor<Cx>; 1]>, Vec<Constructor<Cx>>), Cx::Error>
932    where
933        Cx: 'a,
934    {
935        debug!(?self.ty);
936        if self.private_uninhabited {
937            // Skip the whole column
938            return Ok((smallvec![Constructor::PrivateUninhabited], vec![]));
939        }
940
941        if ctors.clone().any(|c| matches!(c, Constructor::Or)) {
942            // If any constructor is `Or`, we expand or-patterns.
943            return Ok((smallvec![Constructor::Or], vec![]));
944        }
945
946        let ctors_for_ty = cx.ctors_for_ty(&self.ty)?;
947        debug!(?ctors_for_ty);
948
949        // We treat match scrutinees of type `!` or `EmptyEnum` differently.
950        let is_toplevel_exception =
951            self.is_scrutinee && matches!(ctors_for_ty, ConstructorSet::NoConstructors);
952        // Whether empty patterns are counted as useful or not. We only warn an empty arm unreachable if
953        // it is guaranteed unreachable by the opsem (i.e. if the place is `known_valid`).
954        // We don't want to warn empty patterns as unreachable by default just yet. We will in a
955        // later version of rust or under a different lint name, see
956        // https://github.com/rust-lang/rust/pull/129103.
957        let empty_arms_are_unreachable = self.validity.is_known_valid()
958            && (is_toplevel_exception || cx.is_exhaustive_patterns_feature_on());
959        // Whether empty patterns can be omitted for exhaustiveness. We ignore place validity in the
960        // toplevel exception and `exhaustive_patterns` cases for backwards compatibility.
961        let can_omit_empty_arms = self.validity.is_known_valid()
962            || is_toplevel_exception
963            || cx.is_exhaustive_patterns_feature_on();
964
965        // Analyze the constructors present in this column.
966        let mut split_set = ctors_for_ty.split(ctors);
967        debug!(?split_set);
968        let all_missing = split_set.present.is_empty();
969
970        // Build the set of constructors we will specialize with. It must cover the whole type, so
971        // we add `Missing` to represent the missing ones. This is explained under "Constructor
972        // Splitting" at the top of this file.
973        let mut split_ctors = split_set.present;
974        if !(split_set.missing.is_empty()
975            && (split_set.missing_empty.is_empty() || empty_arms_are_unreachable))
976        {
977            split_ctors.push(Constructor::Missing);
978        }
979
980        // Which empty constructors are considered missing. We ensure that
981        // `!missing_ctors.is_empty() => split_ctors.contains(Missing)`. The converse usually holds
982        // except when `!self.validity.is_known_valid()`.
983        let mut missing_ctors = split_set.missing;
984        if !can_omit_empty_arms {
985            missing_ctors.append(&mut split_set.missing_empty);
986        }
987
988        // Whether we should report "Enum::A and Enum::C are missing" or "_ is missing". At the top
989        // level we prefer to list all constructors.
990        let report_individual_missing_ctors = self.is_scrutinee || !all_missing;
991        if !missing_ctors.is_empty() && !report_individual_missing_ctors {
992            // Report `_` as missing.
993            missing_ctors = vec![Constructor::Wildcard];
994        } else if missing_ctors.iter().any(|c| c.is_non_exhaustive()) {
995            // We need to report a `_` anyway, so listing other constructors would be redundant.
996            // `NonExhaustive` is displayed as `_` just like `Wildcard`, but it will be picked
997            // up by diagnostics to add a note about why `_` is required here.
998            missing_ctors = vec![Constructor::NonExhaustive];
999        }
1000
1001        Ok((split_ctors, missing_ctors))
1002    }
1003}
1004
1005impl<Cx: PatCx> Clone for PlaceInfo<Cx> {
1006    fn clone(&self) -> Self {
1007        Self {
1008            ty: self.ty.clone(),
1009            private_uninhabited: self.private_uninhabited,
1010            validity: self.validity,
1011            is_scrutinee: self.is_scrutinee,
1012        }
1013    }
1014}
1015
1016/// Represents a pattern-tuple under investigation.
1017// The three lifetimes are:
1018// - 'p coming from the input
1019// - Cx global compilation context
1020struct PatStack<'p, Cx: PatCx> {
1021    // Rows of len 1 are very common, which is why `SmallVec[_; 2]` works well.
1022    pats: SmallVec<[PatOrWild<'p, Cx>; 2]>,
1023    /// Sometimes we know that as far as this row is concerned, the current case is already handled
1024    /// by a different, more general, case. When the case is irrelevant for all rows this allows us
1025    /// to skip a case entirely. This is purely an optimization. See at the top for details.
1026    relevant: bool,
1027}
1028
1029impl<'p, Cx: PatCx> Clone for PatStack<'p, Cx> {
1030    fn clone(&self) -> Self {
1031        Self { pats: self.pats.clone(), relevant: self.relevant }
1032    }
1033}
1034
1035impl<'p, Cx: PatCx> PatStack<'p, Cx> {
1036    fn from_pattern(pat: &'p DeconstructedPat<Cx>) -> Self {
1037        PatStack { pats: smallvec![PatOrWild::Pat(pat)], relevant: true }
1038    }
1039
1040    fn len(&self) -> usize {
1041        self.pats.len()
1042    }
1043
1044    fn head(&self) -> PatOrWild<'p, Cx> {
1045        self.pats[0]
1046    }
1047
1048    fn iter(&self) -> impl Iterator<Item = PatOrWild<'p, Cx>> + Captures<'_> {
1049        self.pats.iter().copied()
1050    }
1051
1052    // Expand the first or-pattern into its subpatterns. Only useful if the pattern is an
1053    // or-pattern. Panics if `self` is empty.
1054    fn expand_or_pat(&self) -> impl Iterator<Item = PatStack<'p, Cx>> + Captures<'_> {
1055        self.head().expand_or_pat().into_iter().map(move |pat| {
1056            let mut new = self.clone();
1057            new.pats[0] = pat;
1058            new
1059        })
1060    }
1061
1062    /// This computes `specialize(ctor, self)`. See top of the file for explanations.
1063    /// Only call if `ctor.is_covered_by(self.head().ctor())` is true.
1064    fn pop_head_constructor(
1065        &self,
1066        cx: &Cx,
1067        ctor: &Constructor<Cx>,
1068        ctor_arity: usize,
1069        ctor_is_relevant: bool,
1070    ) -> Result<PatStack<'p, Cx>, Cx::Error> {
1071        let head_pat = self.head();
1072        if head_pat.as_pat().is_some_and(|pat| pat.arity() > ctor_arity) {
1073            // Arity can be smaller in case of variable-length slices, but mustn't be larger.
1074            return Err(cx.bug(format_args!(
1075                "uncaught type error: pattern {:?} has inconsistent arity (expected arity <= {ctor_arity})",
1076                head_pat.as_pat().unwrap()
1077            )));
1078        }
1079        // We pop the head pattern and push the new fields extracted from the arguments of
1080        // `self.head()`.
1081        let mut new_pats = head_pat.specialize(ctor, ctor_arity);
1082        new_pats.extend_from_slice(&self.pats[1..]);
1083        // `ctor` is relevant for this row if it is the actual constructor of this row, or if the
1084        // row has a wildcard and `ctor` is relevant for wildcards.
1085        let ctor_is_relevant =
1086            !matches!(self.head().ctor(), Constructor::Wildcard) || ctor_is_relevant;
1087        Ok(PatStack { pats: new_pats, relevant: self.relevant && ctor_is_relevant })
1088    }
1089}
1090
1091impl<'p, Cx: PatCx> fmt::Debug for PatStack<'p, Cx> {
1092    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1093        // We pretty-print similarly to the `Debug` impl of `Matrix`.
1094        write!(f, "+")?;
1095        for pat in self.iter() {
1096            write!(f, " {pat:?} +")?;
1097        }
1098        Ok(())
1099    }
1100}
1101
1102/// A row of the matrix.
1103#[derive(Clone)]
1104struct MatrixRow<'p, Cx: PatCx> {
1105    // The patterns in the row.
1106    pats: PatStack<'p, Cx>,
1107    /// Whether the original arm had a guard. This is inherited when specializing.
1108    is_under_guard: bool,
1109    /// When we specialize, we remember which row of the original matrix produced a given row of the
1110    /// specialized matrix. When we unspecialize, we use this to propagate usefulness back up the
1111    /// callstack. On creation, this stores the index of the original match arm.
1112    parent_row: usize,
1113    /// False when the matrix is just built. This is set to `true` by
1114    /// [`compute_exhaustiveness_and_usefulness`] if the arm is found to be useful.
1115    /// This is reset to `false` when specializing.
1116    useful: bool,
1117    /// Tracks some rows above this one that have an intersection with this one, i.e. such that
1118    /// there is a value that matches both rows.
1119    /// Because of relevancy we may miss some intersections. The intersections we do find are
1120    /// correct. In other words, this is an underapproximation of the real set of intersections.
1121    ///
1122    /// For example:
1123    /// ```rust,ignore(illustrative)
1124    /// match ... {
1125    ///     (true, _, _) => {} // `intersects_at_least = []`
1126    ///     (_, true, 0..=10) => {} // `intersects_at_least = []`
1127    ///     (_, true, 5..15) => {} // `intersects_at_least = [1]`
1128    /// }
1129    /// ```
1130    /// Here the `(true, true)` case is irrelevant. Since we skip it, we will not detect that row 0
1131    /// intersects rows 1 and 2.
1132    intersects_at_least: DenseBitSet<usize>,
1133    /// Whether the head pattern is a branch (see definition of "branch pattern" at
1134    /// [`BranchPatUsefulness`])
1135    head_is_branch: bool,
1136}
1137
1138impl<'p, Cx: PatCx> MatrixRow<'p, Cx> {
1139    fn new(arm: &MatchArm<'p, Cx>, arm_id: usize) -> Self {
1140        MatrixRow {
1141            pats: PatStack::from_pattern(arm.pat),
1142            parent_row: arm_id,
1143            is_under_guard: arm.has_guard,
1144            useful: false,
1145            intersects_at_least: DenseBitSet::new_empty(0), // Initialized in `Matrix::push`.
1146            // This pattern is a branch because it comes from a match arm.
1147            head_is_branch: true,
1148        }
1149    }
1150
1151    fn len(&self) -> usize {
1152        self.pats.len()
1153    }
1154
1155    fn head(&self) -> PatOrWild<'p, Cx> {
1156        self.pats.head()
1157    }
1158
1159    fn iter(&self) -> impl Iterator<Item = PatOrWild<'p, Cx>> + Captures<'_> {
1160        self.pats.iter()
1161    }
1162
1163    // Expand the first or-pattern (if any) into its subpatterns. Panics if `self` is empty.
1164    fn expand_or_pat(
1165        &self,
1166        parent_row: usize,
1167    ) -> impl Iterator<Item = MatrixRow<'p, Cx>> + Captures<'_> {
1168        let is_or_pat = self.pats.head().is_or_pat();
1169        self.pats.expand_or_pat().map(move |patstack| MatrixRow {
1170            pats: patstack,
1171            parent_row,
1172            is_under_guard: self.is_under_guard,
1173            useful: false,
1174            intersects_at_least: DenseBitSet::new_empty(0), // Initialized in `Matrix::push`.
1175            head_is_branch: is_or_pat,
1176        })
1177    }
1178
1179    /// This computes `specialize(ctor, self)`. See top of the file for explanations.
1180    /// Only call if `ctor.is_covered_by(self.head().ctor())` is true.
1181    fn pop_head_constructor(
1182        &self,
1183        cx: &Cx,
1184        ctor: &Constructor<Cx>,
1185        ctor_arity: usize,
1186        ctor_is_relevant: bool,
1187        parent_row: usize,
1188    ) -> Result<MatrixRow<'p, Cx>, Cx::Error> {
1189        Ok(MatrixRow {
1190            pats: self.pats.pop_head_constructor(cx, ctor, ctor_arity, ctor_is_relevant)?,
1191            parent_row,
1192            is_under_guard: self.is_under_guard,
1193            useful: false,
1194            intersects_at_least: DenseBitSet::new_empty(0), // Initialized in `Matrix::push`.
1195            head_is_branch: false,
1196        })
1197    }
1198}
1199
1200impl<'p, Cx: PatCx> fmt::Debug for MatrixRow<'p, Cx> {
1201    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1202        self.pats.fmt(f)
1203    }
1204}
1205
1206/// A 2D matrix. Represents a list of pattern-tuples under investigation.
1207///
1208/// Invariant: each row must have the same length, and each column must have the same type.
1209///
1210/// Invariant: the first column must not contain or-patterns. This is handled by
1211/// [`Matrix::push`].
1212///
1213/// In fact each column corresponds to a place inside the scrutinee of the match. E.g. after
1214/// specializing `(,)` and `Some` on a pattern of type `(Option<u32>, bool)`, the first column of
1215/// the matrix will correspond to `scrutinee.0.Some.0` and the second column to `scrutinee.1`.
1216#[derive(Clone)]
1217struct Matrix<'p, Cx: PatCx> {
1218    /// Vector of rows. The rows must form a rectangular 2D array. Moreover, all the patterns of
1219    /// each column must have the same type. Each column corresponds to a place within the
1220    /// scrutinee.
1221    rows: Vec<MatrixRow<'p, Cx>>,
1222    /// Track info about each place. Each place corresponds to a column in `rows`, and their types
1223    /// must match.
1224    place_info: SmallVec<[PlaceInfo<Cx>; 2]>,
1225    /// Track whether the virtual wildcard row used to compute exhaustiveness is relevant. See top
1226    /// of the file for details on relevancy.
1227    wildcard_row_is_relevant: bool,
1228}
1229
1230impl<'p, Cx: PatCx> Matrix<'p, Cx> {
1231    /// Pushes a new row to the matrix. Internal method, prefer [`Matrix::new`].
1232    fn push(&mut self, mut row: MatrixRow<'p, Cx>) {
1233        row.intersects_at_least = DenseBitSet::new_empty(self.rows.len());
1234        self.rows.push(row);
1235    }
1236
1237    /// Build a new matrix from an iterator of `MatchArm`s.
1238    fn new(arms: &[MatchArm<'p, Cx>], scrut_ty: Cx::Ty, scrut_validity: PlaceValidity) -> Self {
1239        let place_info = PlaceInfo {
1240            ty: scrut_ty,
1241            private_uninhabited: false,
1242            validity: scrut_validity,
1243            is_scrutinee: true,
1244        };
1245        let mut matrix = Matrix {
1246            rows: Vec::with_capacity(arms.len()),
1247            place_info: smallvec![place_info],
1248            wildcard_row_is_relevant: true,
1249        };
1250        for (arm_id, arm) in arms.iter().enumerate() {
1251            matrix.push(MatrixRow::new(arm, arm_id));
1252        }
1253        matrix
1254    }
1255
1256    fn head_place(&self) -> Option<&PlaceInfo<Cx>> {
1257        self.place_info.first()
1258    }
1259    fn column_count(&self) -> usize {
1260        self.place_info.len()
1261    }
1262
1263    fn rows(
1264        &self,
1265    ) -> impl Iterator<Item = &MatrixRow<'p, Cx>> + Clone + DoubleEndedIterator + ExactSizeIterator
1266    {
1267        self.rows.iter()
1268    }
1269    fn rows_mut(
1270        &mut self,
1271    ) -> impl Iterator<Item = &mut MatrixRow<'p, Cx>> + DoubleEndedIterator + ExactSizeIterator
1272    {
1273        self.rows.iter_mut()
1274    }
1275
1276    /// Iterate over the first pattern of each row.
1277    fn heads(&self) -> impl Iterator<Item = PatOrWild<'p, Cx>> + Clone + Captures<'_> {
1278        self.rows().map(|r| r.head())
1279    }
1280
1281    /// This computes `specialize(ctor, self)`. See top of the file for explanations.
1282    fn specialize_constructor(
1283        &self,
1284        pcx: &PlaceCtxt<'_, Cx>,
1285        ctor: &Constructor<Cx>,
1286        ctor_is_relevant: bool,
1287    ) -> Result<Matrix<'p, Cx>, Cx::Error> {
1288        if matches!(ctor, Constructor::Or) {
1289            // Specializing with `Or` means expanding rows with or-patterns.
1290            let mut matrix = Matrix {
1291                rows: Vec::new(),
1292                place_info: self.place_info.clone(),
1293                wildcard_row_is_relevant: self.wildcard_row_is_relevant,
1294            };
1295            for (i, row) in self.rows().enumerate() {
1296                for new_row in row.expand_or_pat(i) {
1297                    matrix.push(new_row);
1298                }
1299            }
1300            Ok(matrix)
1301        } else {
1302            let subfield_place_info = self.place_info[0].specialize(pcx.cx, ctor);
1303            let arity = subfield_place_info.len();
1304            let specialized_place_info =
1305                subfield_place_info.chain(self.place_info[1..].iter().cloned()).collect();
1306            let mut matrix = Matrix {
1307                rows: Vec::new(),
1308                place_info: specialized_place_info,
1309                wildcard_row_is_relevant: self.wildcard_row_is_relevant && ctor_is_relevant,
1310            };
1311            for (i, row) in self.rows().enumerate() {
1312                if ctor.is_covered_by(pcx.cx, row.head().ctor())? {
1313                    let new_row =
1314                        row.pop_head_constructor(pcx.cx, ctor, arity, ctor_is_relevant, i)?;
1315                    matrix.push(new_row);
1316                }
1317            }
1318            Ok(matrix)
1319        }
1320    }
1321
1322    /// Recover row usefulness and intersection information from a processed specialized matrix.
1323    /// `specialized` must come from `self.specialize_constructor`.
1324    fn unspecialize(&mut self, specialized: Self) {
1325        for child_row in specialized.rows() {
1326            let parent_row_id = child_row.parent_row;
1327            let parent_row = &mut self.rows[parent_row_id];
1328            // A parent row is useful if any of its children is.
1329            parent_row.useful |= child_row.useful;
1330            for child_intersection in child_row.intersects_at_least.iter() {
1331                // Convert the intersecting ids into ids for the parent matrix.
1332                let parent_intersection = specialized.rows[child_intersection].parent_row;
1333                // Note: self-intersection can happen with or-patterns.
1334                if parent_intersection != parent_row_id {
1335                    parent_row.intersects_at_least.insert(parent_intersection);
1336                }
1337            }
1338        }
1339    }
1340}
1341
1342/// Pretty-printer for matrices of patterns, example:
1343///
1344/// ```text
1345/// + _     + []                +
1346/// + true  + [First]           +
1347/// + true  + [Second(true)]    +
1348/// + false + [_]               +
1349/// + _     + [_, _, tail @ ..] +
1350/// | ✓     | ?                 | // validity
1351/// ```
1352impl<'p, Cx: PatCx> fmt::Debug for Matrix<'p, Cx> {
1353    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1354        write!(f, "\n")?;
1355
1356        let mut pretty_printed_matrix: Vec<Vec<String>> = self
1357            .rows
1358            .iter()
1359            .map(|row| row.iter().map(|pat| format!("{pat:?}")).collect())
1360            .collect();
1361        pretty_printed_matrix
1362            .push(self.place_info.iter().map(|place| format!("{}", place.validity)).collect());
1363
1364        let column_count = self.column_count();
1365        assert!(self.rows.iter().all(|row| row.len() == column_count));
1366        assert!(self.place_info.len() == column_count);
1367        let column_widths: Vec<usize> = (0..column_count)
1368            .map(|col| pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0))
1369            .collect();
1370
1371        for (row_i, row) in pretty_printed_matrix.into_iter().enumerate() {
1372            let is_validity_row = row_i == self.rows.len();
1373            let sep = if is_validity_row { "|" } else { "+" };
1374            write!(f, "{sep}")?;
1375            for (column, pat_str) in row.into_iter().enumerate() {
1376                write!(f, " ")?;
1377                write!(f, "{:1$}", pat_str, column_widths[column])?;
1378                write!(f, " {sep}")?;
1379            }
1380            if is_validity_row {
1381                write!(f, " // validity")?;
1382            }
1383            write!(f, "\n")?;
1384        }
1385        Ok(())
1386    }
1387}
1388
1389/// A witness-tuple of non-exhaustiveness for error reporting, represented as a list of patterns (in
1390/// reverse order of construction).
1391///
1392/// This mirrors `PatStack`: they function similarly, except `PatStack` contains user patterns we
1393/// are inspecting, and `WitnessStack` contains witnesses we are constructing.
1394/// FIXME(Nadrieril): use the same order of patterns for both.
1395///
1396/// A `WitnessStack` should have the same types and length as the `PatStack`s we are inspecting
1397/// (except we store the patterns in reverse order). The same way `PatStack` starts with length 1,
1398/// at the end of the algorithm this will have length 1. In the middle of the algorithm, it can
1399/// contain multiple patterns.
1400///
1401/// For example, if we are constructing a witness for the match against
1402///
1403/// ```compile_fail,E0004
1404/// struct Pair(Option<(u32, u32)>, bool);
1405/// # fn foo(p: Pair) {
1406/// match p {
1407///    Pair(None, _) => {}
1408///    Pair(_, false) => {}
1409/// }
1410/// # }
1411/// ```
1412///
1413/// We'll perform the following steps (among others):
1414/// ```text
1415/// - Start with a matrix representing the match
1416///     `PatStack(vec![Pair(None, _)])`
1417///     `PatStack(vec![Pair(_, false)])`
1418/// - Specialize with `Pair`
1419///     `PatStack(vec![None, _])`
1420///     `PatStack(vec![_, false])`
1421/// - Specialize with `Some`
1422///     `PatStack(vec![_, false])`
1423/// - Specialize with `_`
1424///     `PatStack(vec![false])`
1425/// - Specialize with `true`
1426///     // no patstacks left
1427/// - This is a non-exhaustive match: we have the empty witness stack as a witness.
1428///     `WitnessStack(vec![])`
1429/// - Apply `true`
1430///     `WitnessStack(vec![true])`
1431/// - Apply `_`
1432///     `WitnessStack(vec![true, _])`
1433/// - Apply `Some`
1434///     `WitnessStack(vec![true, Some(_)])`
1435/// - Apply `Pair`
1436///     `WitnessStack(vec![Pair(Some(_), true)])`
1437/// ```
1438///
1439/// The final `Pair(Some(_), true)` is then the resulting witness.
1440///
1441/// See the top of the file for more detailed explanations and examples.
1442#[derive(Debug)]
1443struct WitnessStack<Cx: PatCx>(Vec<WitnessPat<Cx>>);
1444
1445impl<Cx: PatCx> Clone for WitnessStack<Cx> {
1446    fn clone(&self) -> Self {
1447        Self(self.0.clone())
1448    }
1449}
1450
1451impl<Cx: PatCx> WitnessStack<Cx> {
1452    /// Asserts that the witness contains a single pattern, and returns it.
1453    fn single_pattern(self) -> WitnessPat<Cx> {
1454        assert_eq!(self.0.len(), 1);
1455        self.0.into_iter().next().unwrap()
1456    }
1457
1458    /// Reverses specialization by the `Missing` constructor by pushing a whole new pattern.
1459    fn push_pattern(&mut self, pat: WitnessPat<Cx>) {
1460        self.0.push(pat);
1461    }
1462
1463    /// Reverses specialization. Given a witness obtained after specialization, this constructs a
1464    /// new witness valid for before specialization. See the section on `unspecialize` at the top of
1465    /// the file.
1466    ///
1467    /// Examples:
1468    /// ```text
1469    /// ctor: tuple of 2 elements
1470    /// pats: [false, "foo", _, true]
1471    /// result: [(false, "foo"), _, true]
1472    ///
1473    /// ctor: Enum::Variant { a: (bool, &'static str), b: usize}
1474    /// pats: [(false, "foo"), _, true]
1475    /// result: [Enum::Variant { a: (false, "foo"), b: _ }, true]
1476    /// ```
1477    fn apply_constructor(
1478        mut self,
1479        pcx: &PlaceCtxt<'_, Cx>,
1480        ctor: &Constructor<Cx>,
1481    ) -> SmallVec<[Self; 1]> {
1482        let len = self.0.len();
1483        let arity = pcx.ctor_arity(ctor);
1484        let fields: Vec<_> = self.0.drain((len - arity)..).rev().collect();
1485        if matches!(ctor, Constructor::UnionField)
1486            && fields.iter().filter(|p| !matches!(p.ctor(), Constructor::Wildcard)).count() >= 2
1487        {
1488            // Convert a `Union { a: p, b: q }` witness into `Union { a: p }` and `Union { b: q }`.
1489            // First add `Union { .. }` to `self`.
1490            self.0.push(WitnessPat::wild_from_ctor(pcx.cx, ctor.clone(), pcx.ty.clone()));
1491            fields
1492                .into_iter()
1493                .enumerate()
1494                .filter(|(_, p)| !matches!(p.ctor(), Constructor::Wildcard))
1495                .map(|(i, p)| {
1496                    let mut ret = self.clone();
1497                    // Fill the `i`th field of the union with `p`.
1498                    ret.0.last_mut().unwrap().fields[i] = p;
1499                    ret
1500                })
1501                .collect()
1502        } else {
1503            self.0.push(WitnessPat::new(ctor.clone(), fields, pcx.ty.clone()));
1504            smallvec![self]
1505        }
1506    }
1507}
1508
1509/// Represents a set of pattern-tuples that are witnesses of non-exhaustiveness for error
1510/// reporting. This has similar invariants as `Matrix` does.
1511///
1512/// The `WitnessMatrix` returned by [`compute_exhaustiveness_and_usefulness`] obeys the invariant
1513/// that the union of the input `Matrix` and the output `WitnessMatrix` together matches the type
1514/// exhaustively.
1515///
1516/// Just as the `Matrix` starts with a single column, by the end of the algorithm, this has a single
1517/// column, which contains the patterns that are missing for the match to be exhaustive.
1518#[derive(Debug)]
1519struct WitnessMatrix<Cx: PatCx>(Vec<WitnessStack<Cx>>);
1520
1521impl<Cx: PatCx> Clone for WitnessMatrix<Cx> {
1522    fn clone(&self) -> Self {
1523        Self(self.0.clone())
1524    }
1525}
1526
1527impl<Cx: PatCx> WitnessMatrix<Cx> {
1528    /// New matrix with no witnesses.
1529    fn empty() -> Self {
1530        WitnessMatrix(Vec::new())
1531    }
1532    /// New matrix with one `()` witness, i.e. with no columns.
1533    fn unit_witness() -> Self {
1534        WitnessMatrix(vec![WitnessStack(Vec::new())])
1535    }
1536
1537    /// Whether this has any witnesses.
1538    fn is_empty(&self) -> bool {
1539        self.0.is_empty()
1540    }
1541    /// Asserts that there is a single column and returns the patterns in it.
1542    fn single_column(self) -> Vec<WitnessPat<Cx>> {
1543        self.0.into_iter().map(|w| w.single_pattern()).collect()
1544    }
1545
1546    /// Reverses specialization by the `Missing` constructor by pushing a whole new pattern.
1547    fn push_pattern(&mut self, pat: WitnessPat<Cx>) {
1548        for witness in self.0.iter_mut() {
1549            witness.push_pattern(pat.clone())
1550        }
1551    }
1552
1553    /// Reverses specialization by `ctor`. See the section on `unspecialize` at the top of the file.
1554    fn apply_constructor(
1555        &mut self,
1556        pcx: &PlaceCtxt<'_, Cx>,
1557        missing_ctors: &[Constructor<Cx>],
1558        ctor: &Constructor<Cx>,
1559    ) {
1560        // The `Or` constructor indicates that we expanded or-patterns. This doesn't affect
1561        // witnesses.
1562        if self.is_empty() || matches!(ctor, Constructor::Or) {
1563            return;
1564        }
1565        if matches!(ctor, Constructor::Missing) {
1566            // We got the special `Missing` constructor that stands for the constructors not present
1567            // in the match. For each missing constructor `c`, we add a `c(_, _, _)` witness
1568            // appropriately filled with wildcards.
1569            let mut ret = Self::empty();
1570            for ctor in missing_ctors {
1571                let pat = pcx.wild_from_ctor(ctor.clone());
1572                // Clone `self` and add `c(_, _, _)` to each of its witnesses.
1573                let mut wit_matrix = self.clone();
1574                wit_matrix.push_pattern(pat);
1575                ret.extend(wit_matrix);
1576            }
1577            *self = ret;
1578        } else {
1579            // Any other constructor we unspecialize as expected.
1580            for witness in std::mem::take(&mut self.0) {
1581                self.0.extend(witness.apply_constructor(pcx, ctor));
1582            }
1583        }
1584    }
1585
1586    /// Merges the witnesses of two matrices. Their column types must match.
1587    fn extend(&mut self, other: Self) {
1588        self.0.extend(other.0)
1589    }
1590}
1591
1592/// Collect ranges that overlap like `lo..=overlap`/`overlap..=hi`. Must be called during
1593/// exhaustiveness checking, if we find a singleton range after constructor splitting. This reuses
1594/// row intersection information to only detect ranges that truly overlap.
1595///
1596/// If two ranges overlapped, the split set will contain their intersection as a singleton.
1597/// Specialization will then select rows that match the overlap, and exhaustiveness will compute
1598/// which rows have an intersection that includes the overlap. That gives us all the info we need to
1599/// compute overlapping ranges without false positives.
1600///
1601/// We can however get false negatives because exhaustiveness does not explore all cases. See the
1602/// section on relevancy at the top of the file.
1603fn collect_overlapping_range_endpoints<'p, Cx: PatCx>(
1604    cx: &Cx,
1605    overlap_range: IntRange,
1606    matrix: &Matrix<'p, Cx>,
1607    specialized_matrix: &Matrix<'p, Cx>,
1608) {
1609    let overlap = overlap_range.lo;
1610    // Ranges that look like `lo..=overlap`.
1611    let mut prefixes: SmallVec<[_; 1]> = Default::default();
1612    // Ranges that look like `overlap..=hi`.
1613    let mut suffixes: SmallVec<[_; 1]> = Default::default();
1614    // Iterate on patterns that contained `overlap`. We iterate on `specialized_matrix` which
1615    // contains only rows that matched the current `ctor` as well as accurate intersection
1616    // information. It doesn't contain the column that contains the range; that can be found in
1617    // `matrix`.
1618    for (child_row_id, child_row) in specialized_matrix.rows().enumerate() {
1619        let PatOrWild::Pat(pat) = matrix.rows[child_row.parent_row].head() else { continue };
1620        let Constructor::IntRange(this_range) = pat.ctor() else { continue };
1621        // Don't lint when one of the ranges is a singleton.
1622        if this_range.is_singleton() {
1623            continue;
1624        }
1625        if this_range.lo == overlap {
1626            // `this_range` looks like `overlap..=this_range.hi`; it overlaps with any
1627            // ranges that look like `lo..=overlap`.
1628            if !prefixes.is_empty() {
1629                let overlaps_with: Vec<_> = prefixes
1630                    .iter()
1631                    .filter(|&&(other_child_row_id, _)| {
1632                        child_row.intersects_at_least.contains(other_child_row_id)
1633                    })
1634                    .map(|&(_, pat)| pat)
1635                    .collect();
1636                if !overlaps_with.is_empty() {
1637                    cx.lint_overlapping_range_endpoints(pat, overlap_range, &overlaps_with);
1638                }
1639            }
1640            suffixes.push((child_row_id, pat))
1641        } else if Some(this_range.hi) == overlap.plus_one() {
1642            // `this_range` looks like `this_range.lo..=overlap`; it overlaps with any
1643            // ranges that look like `overlap..=hi`.
1644            if !suffixes.is_empty() {
1645                let overlaps_with: Vec<_> = suffixes
1646                    .iter()
1647                    .filter(|&&(other_child_row_id, _)| {
1648                        child_row.intersects_at_least.contains(other_child_row_id)
1649                    })
1650                    .map(|&(_, pat)| pat)
1651                    .collect();
1652                if !overlaps_with.is_empty() {
1653                    cx.lint_overlapping_range_endpoints(pat, overlap_range, &overlaps_with);
1654                }
1655            }
1656            prefixes.push((child_row_id, pat))
1657        }
1658    }
1659}
1660
1661/// Collect ranges that have a singleton gap between them.
1662fn collect_non_contiguous_range_endpoints<'p, Cx: PatCx>(
1663    cx: &Cx,
1664    gap_range: &IntRange,
1665    matrix: &Matrix<'p, Cx>,
1666) {
1667    let gap = gap_range.lo;
1668    // Ranges that look like `lo..gap`.
1669    let mut onebefore: SmallVec<[_; 1]> = Default::default();
1670    // Ranges that start on `gap+1` or singletons `gap+1`.
1671    let mut oneafter: SmallVec<[_; 1]> = Default::default();
1672    // Look through the column for ranges near the gap.
1673    for pat in matrix.heads() {
1674        let PatOrWild::Pat(pat) = pat else { continue };
1675        let Constructor::IntRange(this_range) = pat.ctor() else { continue };
1676        if gap == this_range.hi {
1677            onebefore.push(pat)
1678        } else if gap.plus_one() == Some(this_range.lo) {
1679            oneafter.push(pat)
1680        }
1681    }
1682
1683    for pat_before in onebefore {
1684        cx.lint_non_contiguous_range_endpoints(pat_before, *gap_range, oneafter.as_slice());
1685    }
1686}
1687
1688/// The core of the algorithm.
1689///
1690/// This recursively computes witnesses of the non-exhaustiveness of `matrix` (if any). Also tracks
1691/// usefulness of each row in the matrix (in `row.useful`). We track usefulness of subpatterns in
1692/// `mcx.branch_usefulness`.
1693///
1694/// The input `Matrix` and the output `WitnessMatrix` together match the type exhaustively.
1695///
1696/// The key steps are:
1697/// - specialization, where we dig into the rows that have a specific constructor and call ourselves
1698///     recursively;
1699/// - unspecialization, where we lift the results from the previous step into results for this step
1700///     (using `apply_constructor` and by updating `row.useful` for each parent row).
1701/// This is all explained at the top of the file.
1702#[instrument(level = "debug", skip(mcx), ret)]
1703fn compute_exhaustiveness_and_usefulness<'a, 'p, Cx: PatCx>(
1704    mcx: &mut UsefulnessCtxt<'a, 'p, Cx>,
1705    matrix: &mut Matrix<'p, Cx>,
1706) -> Result<WitnessMatrix<Cx>, Cx::Error> {
1707    debug_assert!(matrix.rows().all(|r| r.len() == matrix.column_count()));
1708
1709    if !matrix.wildcard_row_is_relevant && matrix.rows().all(|r| !r.pats.relevant) {
1710        // Here we know that nothing will contribute further to exhaustiveness or usefulness. This
1711        // is purely an optimization: skipping this check doesn't affect correctness. See the top of
1712        // the file for details.
1713        return Ok(WitnessMatrix::empty());
1714    }
1715
1716    let Some(place) = matrix.head_place() else {
1717        mcx.increase_complexity_level(matrix.rows().len())?;
1718        // The base case: there are no columns in the matrix. We are morally pattern-matching on ().
1719        // A row is useful iff it has no (unguarded) rows above it.
1720        let mut useful = true; // Whether the next row is useful.
1721        for (i, row) in matrix.rows_mut().enumerate() {
1722            row.useful = useful;
1723            row.intersects_at_least.insert_range(0..i);
1724            // The next rows stays useful if this one is under a guard.
1725            useful &= row.is_under_guard;
1726        }
1727        return if useful && matrix.wildcard_row_is_relevant {
1728            // The wildcard row is useful; the match is non-exhaustive.
1729            Ok(WitnessMatrix::unit_witness())
1730        } else {
1731            // Either the match is exhaustive, or we choose not to report anything because of
1732            // relevancy. See at the top for details.
1733            Ok(WitnessMatrix::empty())
1734        };
1735    };
1736
1737    // Analyze the constructors present in this column.
1738    let ctors = matrix.heads().map(|p| p.ctor());
1739    let (split_ctors, missing_ctors) = place.split_column_ctors(mcx.tycx, ctors)?;
1740
1741    let ty = &place.ty.clone(); // Clone it out so we can mutate `matrix` later.
1742    let pcx = &PlaceCtxt { cx: mcx.tycx, ty };
1743    let mut ret = WitnessMatrix::empty();
1744    for ctor in split_ctors {
1745        // Dig into rows that match `ctor`.
1746        debug!("specialize({:?})", ctor);
1747        // `ctor` is *irrelevant* if there's another constructor in `split_ctors` that matches
1748        // strictly fewer rows. In that case we can sometimes skip it. See the top of the file for
1749        // details.
1750        let ctor_is_relevant = matches!(ctor, Constructor::Missing) || missing_ctors.is_empty();
1751        let mut spec_matrix = matrix.specialize_constructor(pcx, &ctor, ctor_is_relevant)?;
1752        let mut witnesses = ensure_sufficient_stack(|| {
1753            compute_exhaustiveness_and_usefulness(mcx, &mut spec_matrix)
1754        })?;
1755
1756        // Transform witnesses for `spec_matrix` into witnesses for `matrix`.
1757        witnesses.apply_constructor(pcx, &missing_ctors, &ctor);
1758        // Accumulate the found witnesses.
1759        ret.extend(witnesses);
1760
1761        // Detect ranges that overlap on their endpoints.
1762        if let Constructor::IntRange(overlap_range) = ctor {
1763            if overlap_range.is_singleton()
1764                && spec_matrix.rows.len() >= 2
1765                && spec_matrix.rows.iter().any(|row| !row.intersects_at_least.is_empty())
1766            {
1767                collect_overlapping_range_endpoints(mcx.tycx, overlap_range, matrix, &spec_matrix);
1768            }
1769        }
1770
1771        matrix.unspecialize(spec_matrix);
1772    }
1773
1774    // Detect singleton gaps between ranges.
1775    if missing_ctors.iter().any(|c| matches!(c, Constructor::IntRange(..))) {
1776        for missing in &missing_ctors {
1777            if let Constructor::IntRange(gap) = missing {
1778                if gap.is_singleton() {
1779                    collect_non_contiguous_range_endpoints(mcx.tycx, gap, matrix);
1780                }
1781            }
1782        }
1783    }
1784
1785    // Record usefulness of the branch patterns.
1786    for row in matrix.rows() {
1787        if row.head_is_branch {
1788            if let PatOrWild::Pat(pat) = row.head() {
1789                mcx.branch_usefulness.entry(pat.uid).or_default().update(row, matrix);
1790            }
1791        }
1792    }
1793
1794    Ok(ret)
1795}
1796
1797/// Indicates why a given pattern is considered redundant.
1798#[derive(Clone, Debug)]
1799pub struct RedundancyExplanation<'p, Cx: PatCx> {
1800    /// All the values matched by this pattern are already matched by the given set of patterns.
1801    /// This list is not guaranteed to be minimal but the contained patterns are at least guaranteed
1802    /// to intersect this pattern.
1803    pub covered_by: Vec<&'p DeconstructedPat<Cx>>,
1804}
1805
1806/// Indicates whether or not a given arm is useful.
1807#[derive(Clone, Debug)]
1808pub enum Usefulness<'p, Cx: PatCx> {
1809    /// The arm is useful. This additionally carries a set of or-pattern branches that have been
1810    /// found to be redundant despite the overall arm being useful. Used only in the presence of
1811    /// or-patterns, otherwise it stays empty.
1812    Useful(Vec<(&'p DeconstructedPat<Cx>, RedundancyExplanation<'p, Cx>)>),
1813    /// The arm is redundant and can be removed without changing the behavior of the match
1814    /// expression.
1815    Redundant(RedundancyExplanation<'p, Cx>),
1816}
1817
1818/// The output of checking a match for exhaustiveness and arm usefulness.
1819pub struct UsefulnessReport<'p, Cx: PatCx> {
1820    /// For each arm of the input, whether that arm is useful after the arms above it.
1821    pub arm_usefulness: Vec<(MatchArm<'p, Cx>, Usefulness<'p, Cx>)>,
1822    /// If the match is exhaustive, this is empty. If not, this contains witnesses for the lack of
1823    /// exhaustiveness.
1824    pub non_exhaustiveness_witnesses: Vec<WitnessPat<Cx>>,
1825    /// For each arm, a set of indices of arms above it that have non-empty intersection, i.e. there
1826    /// is a value matched by both arms. This may miss real intersections.
1827    pub arm_intersections: Vec<DenseBitSet<usize>>,
1828}
1829
1830/// Computes whether a match is exhaustive and which of its arms are useful.
1831#[instrument(skip(tycx, arms), level = "debug")]
1832pub fn compute_match_usefulness<'p, Cx: PatCx>(
1833    tycx: &Cx,
1834    arms: &[MatchArm<'p, Cx>],
1835    scrut_ty: Cx::Ty,
1836    scrut_validity: PlaceValidity,
1837    complexity_limit: Option<usize>,
1838) -> Result<UsefulnessReport<'p, Cx>, Cx::Error> {
1839    let mut cx = UsefulnessCtxt {
1840        tycx,
1841        branch_usefulness: FxHashMap::default(),
1842        complexity_limit,
1843        complexity_level: 0,
1844    };
1845    let mut matrix = Matrix::new(arms, scrut_ty, scrut_validity);
1846    let non_exhaustiveness_witnesses = compute_exhaustiveness_and_usefulness(&mut cx, &mut matrix)?;
1847
1848    let non_exhaustiveness_witnesses: Vec<_> = non_exhaustiveness_witnesses.single_column();
1849    let arm_usefulness: Vec<_> = arms
1850        .iter()
1851        .copied()
1852        .map(|arm| {
1853            debug!(?arm);
1854            let usefulness = cx.branch_usefulness.get(&arm.pat.uid).unwrap();
1855            let usefulness = if let Some(explanation) = usefulness.is_redundant() {
1856                Usefulness::Redundant(explanation)
1857            } else {
1858                let mut redundant_subpats = Vec::new();
1859                arm.pat.walk(&mut |subpat| {
1860                    if let Some(u) = cx.branch_usefulness.get(&subpat.uid) {
1861                        if let Some(explanation) = u.is_redundant() {
1862                            redundant_subpats.push((subpat, explanation));
1863                            false // stop recursing
1864                        } else {
1865                            true // keep recursing
1866                        }
1867                    } else {
1868                        true // keep recursing
1869                    }
1870                });
1871                Usefulness::Useful(redundant_subpats)
1872            };
1873            debug!(?usefulness);
1874            (arm, usefulness)
1875        })
1876        .collect();
1877
1878    let arm_intersections: Vec<_> =
1879        matrix.rows().map(|row| row.intersects_at_least.clone()).collect();
1880
1881    Ok(UsefulnessReport { arm_usefulness, non_exhaustiveness_witnesses, arm_intersections })
1882}