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