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