]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/thir/pattern/_match.rs
Rollup merge of #79293 - Havvy:test-eval-order-compound-assign, r=Mark-Simulacrum
[rust.git] / compiler / rustc_mir_build / src / thir / pattern / _match.rs
1 //! Note: tests specific to this file can be found in:
2 //!     - ui/pattern/usefulness
3 //!     - ui/or-patterns
4 //!     - ui/consts/const_in_pattern
5 //!     - ui/rfc-2008-non-exhaustive
6 //!     - ui/half-open-range-patterns
7 //!     - probably many others
8 //! I (Nadrieril) prefer to put new tests in `ui/pattern/usefulness` unless there's a specific
9 //! reason not to, for example if they depend on a particular feature like or_patterns.
10 //!
11 //! This file includes the logic for exhaustiveness and usefulness checking for
12 //! pattern-matching. Specifically, given a list of patterns for a type, we can
13 //! tell whether:
14 //! (a) the patterns cover every possible constructor for the type (exhaustiveness)
15 //! (b) each pattern is necessary (usefulness)
16 //!
17 //! The algorithm implemented here is a modified version of the one described in:
18 //! <http://moscova.inria.fr/~maranget/papers/warn/index.html>
19 //! However, to save future implementors from reading the original paper, we
20 //! summarise the algorithm here to hopefully save time and be a little clearer
21 //! (without being so rigorous).
22 //!
23 //! # Premise
24 //!
25 //! The core of the algorithm revolves about a "usefulness" check. In particular, we
26 //! are trying to compute a predicate `U(P, p)` where `P` is a list of patterns (we refer to this as
27 //! a matrix). `U(P, p)` represents whether, given an existing list of patterns
28 //! `P_1 ..= P_m`, adding a new pattern `p` will be "useful" (that is, cover previously-
29 //! uncovered values of the type).
30 //!
31 //! If we have this predicate, then we can easily compute both exhaustiveness of an
32 //! entire set of patterns and the individual usefulness of each one.
33 //! (a) the set of patterns is exhaustive iff `U(P, _)` is false (i.e., adding a wildcard
34 //! match doesn't increase the number of values we're matching)
35 //! (b) a pattern `P_i` is not useful if `U(P[0..=(i-1), P_i)` is false (i.e., adding a
36 //! pattern to those that have come before it doesn't increase the number of values
37 //! we're matching).
38 //!
39 //! # Core concept
40 //!
41 //! The idea that powers everything that is done in this file is the following: a value is made
42 //! from a constructor applied to some fields. Examples of constructors are `Some`, `None`, `(,)`
43 //! (the 2-tuple constructor), `Foo {..}` (the constructor for a struct `Foo`), and `2` (the
44 //! constructor for the number `2`). Fields are just a (possibly empty) list of values.
45 //!
46 //! Some of the constructors listed above might feel weird: `None` and `2` don't take any
47 //! arguments. This is part of what makes constructors so general: we will consider plain values
48 //! like numbers and string literals to be constructors that take no arguments, also called "0-ary
49 //! constructors"; they are the simplest case of constructors. This allows us to see any value as
50 //! made up from a tree of constructors, each having a given number of children. For example:
51 //! `(None, Ok(0))` is made from 4 different constructors.
52 //!
53 //! This idea can be extended to patterns: a pattern captures a set of possible values, and we can
54 //! describe this set using constructors. For example, `Err(_)` captures all values of the type
55 //! `Result<T, E>` that start with the `Err` constructor (for some choice of `T` and `E`). The
56 //! wildcard `_` captures all values of the given type starting with any of the constructors for
57 //! that type.
58 //!
59 //! We use this to compute whether different patterns might capture a same value. Do the patterns
60 //! `Ok("foo")` and `Err(_)` capture a common value? The answer is no, because the first pattern
61 //! captures only values starting with the `Ok` constructor and the second only values starting
62 //! with the `Err` constructor. Do the patterns `Some(42)` and `Some(1..10)` intersect? They might,
63 //! since they both capture values starting with `Some`. To be certain, we need to dig under the
64 //! `Some` constructor and continue asking the question. This is the main idea behind the
65 //! exhaustiveness algorithm: by looking at patterns constructor-by-constructor, we can efficiently
66 //! figure out if some new pattern might capture a value that hadn't been captured by previous
67 //! patterns.
68 //!
69 //! Constructors are represented by the `Constructor` enum, and its fields by the `Fields` enum.
70 //! Most of the complexity of this file resides in transforming between patterns and
71 //! (`Constructor`, `Fields`) pairs, handling all the special cases correctly.
72 //!
73 //! Caveat: this constructors/fields distinction doesn't quite cover every Rust value. For example
74 //! a value of type `Rc<u64>` doesn't fit this idea very well, nor do various other things.
75 //! However, this idea covers most of the cases that are relevant to exhaustiveness checking.
76 //!
77 //!
78 //! # Algorithm
79 //!
80 //! Recall that `U(P, p)` represents whether, given an existing list of patterns (aka matrix) `P`,
81 //! adding a new pattern `p` will cover previously-uncovered values of the type.
82 //! During the course of the algorithm, the rows of the matrix won't just be individual patterns,
83 //! but rather partially-deconstructed patterns in the form of a list of fields. The paper
84 //! calls those pattern-vectors, and we will call them pattern-stacks. The same holds for the
85 //! new pattern `p`.
86 //!
87 //! For example, say we have the following:
88 //!
89 //! ```
90 //! // x: (Option<bool>, Result<()>)
91 //! match x {
92 //!     (Some(true), _) => {}
93 //!     (None, Err(())) => {}
94 //!     (None, Err(_)) => {}
95 //! }
96 //! ```
97 //!
98 //! Here, the matrix `P` starts as:
99 //!
100 //! ```
101 //! [
102 //!     [(Some(true), _)],
103 //!     [(None, Err(()))],
104 //!     [(None, Err(_))],
105 //! ]
106 //! ```
107 //!
108 //! We can tell it's not exhaustive, because `U(P, _)` is true (we're not covering
109 //! `[(Some(false), _)]`, for instance). In addition, row 3 is not useful, because
110 //! all the values it covers are already covered by row 2.
111 //!
112 //! A list of patterns can be thought of as a stack, because we are mainly interested in the top of
113 //! the stack at any given point, and we can pop or apply constructors to get new pattern-stacks.
114 //! To match the paper, the top of the stack is at the beginning / on the left.
115 //!
116 //! There are two important operations on pattern-stacks necessary to understand the algorithm:
117 //!
118 //! 1. We can pop a given constructor off the top of a stack. This operation is called
119 //!    `specialize`, and is denoted `S(c, p)` where `c` is a constructor (like `Some` or
120 //!    `None`) and `p` a pattern-stack.
121 //!    If the pattern on top of the stack can cover `c`, this removes the constructor and
122 //!    pushes its arguments onto the stack. It also expands OR-patterns into distinct patterns.
123 //!    Otherwise the pattern-stack is discarded.
124 //!    This essentially filters those pattern-stacks whose top covers the constructor `c` and
125 //!    discards the others.
126 //!
127 //!    For example, the first pattern above initially gives a stack `[(Some(true), _)]`. If we
128 //!    pop the tuple constructor, we are left with `[Some(true), _]`, and if we then pop the
129 //!    `Some` constructor we get `[true, _]`. If we had popped `None` instead, we would get
130 //!    nothing back.
131 //!
132 //!    This returns zero or more new pattern-stacks, as follows. We look at the pattern `p_1`
133 //!    on top of the stack, and we have four cases:
134 //!         1.1. `p_1 = c(r_1, .., r_a)`, i.e. the top of the stack has constructor `c`. We
135 //!              push onto the stack the arguments of this constructor, and return the result:
136 //!                 r_1, .., r_a, p_2, .., p_n
137 //!         1.2. `p_1 = c'(r_1, .., r_a')` where `c ≠ c'`. We discard the current stack and
138 //!              return nothing.
139 //!         1.3. `p_1 = _`. We push onto the stack as many wildcards as the constructor `c` has
140 //!              arguments (its arity), and return the resulting stack:
141 //!                 _, .., _, p_2, .., p_n
142 //!         1.4. `p_1 = r_1 | r_2`. We expand the OR-pattern and then recurse on each resulting
143 //!              stack:
144 //!                 S(c, (r_1, p_2, .., p_n))
145 //!                 S(c, (r_2, p_2, .., p_n))
146 //!
147 //! 2. We can pop a wildcard off the top of the stack. This is called `S(_, p)`, where `p` is
148 //!    a pattern-stack. Note: the paper calls this `D(p)`.
149 //!    This is used when we know there are missing constructor cases, but there might be
150 //!    existing wildcard patterns, so to check the usefulness of the matrix, we have to check
151 //!    all its *other* components.
152 //!
153 //!    It is computed as follows. We look at the pattern `p_1` on top of the stack,
154 //!    and we have three cases:
155 //!         2.1. `p_1 = c(r_1, .., r_a)`. We discard the current stack and return nothing.
156 //!         2.2. `p_1 = _`. We return the rest of the stack:
157 //!                 p_2, .., p_n
158 //!         2.3. `p_1 = r_1 | r_2`. We expand the OR-pattern and then recurse on each resulting
159 //!           stack.
160 //!                 S(_, (r_1, p_2, .., p_n))
161 //!                 S(_, (r_2, p_2, .., p_n))
162 //!
163 //! Note that the OR-patterns are not always used directly in Rust, but are used to derive the
164 //! exhaustive integer matching rules, so they're written here for posterity.
165 //!
166 //! Both those operations extend straightforwardly to a list or pattern-stacks, i.e. a matrix, by
167 //! working row-by-row. Popping a constructor ends up keeping only the matrix rows that start with
168 //! the given constructor, and popping a wildcard keeps those rows that start with a wildcard.
169 //!
170 //!
171 //! The algorithm for computing `U`
172 //! -------------------------------
173 //! The algorithm is inductive (on the number of columns: i.e., components of tuple patterns).
174 //! That means we're going to check the components from left-to-right, so the algorithm
175 //! operates principally on the first component of the matrix and new pattern-stack `p`.
176 //! This algorithm is realised in the `is_useful` function.
177 //!
178 //! Base case. (`n = 0`, i.e., an empty tuple pattern)
179 //!     - If `P` already contains an empty pattern (i.e., if the number of patterns `m > 0`),
180 //!       then `U(P, p)` is false.
181 //!     - Otherwise, `P` must be empty, so `U(P, p)` is true.
182 //!
183 //! Inductive step. (`n > 0`, i.e., whether there's at least one column
184 //!                  [which may then be expanded into further columns later])
185 //! We're going to match on the top of the new pattern-stack, `p_1`.
186 //!     - If `p_1 == c(r_1, .., r_a)`, i.e. we have a constructor pattern.
187 //! Then, the usefulness of `p_1` can be reduced to whether it is useful when
188 //! we ignore all the patterns in the first column of `P` that involve other constructors.
189 //! This is where `S(c, P)` comes in:
190 //! `U(P, p) := U(S(c, P), S(c, p))`
191 //!
192 //! For example, if `P` is:
193 //!
194 //! ```
195 //! [
196 //!     [Some(true), _],
197 //!     [None, 0],
198 //! ]
199 //! ```
200 //!
201 //! and `p` is [Some(false), 0], then we don't care about row 2 since we know `p` only
202 //! matches values that row 2 doesn't. For row 1 however, we need to dig into the
203 //! arguments of `Some` to know whether some new value is covered. So we compute
204 //! `U([[true, _]], [false, 0])`.
205 //!
206 //!   - If `p_1 == _`, then we look at the list of constructors that appear in the first
207 //! component of the rows of `P`:
208 //!   + If there are some constructors that aren't present, then we might think that the
209 //! wildcard `_` is useful, since it covers those constructors that weren't covered
210 //! before.
211 //! That's almost correct, but only works if there were no wildcards in those first
212 //! components. So we need to check that `p` is useful with respect to the rows that
213 //! start with a wildcard, if there are any. This is where `S(_, x)` comes in:
214 //! `U(P, p) := U(S(_, P), S(_, p))`
215 //!
216 //! For example, if `P` is:
217 //!
218 //! ```
219 //! [
220 //!     [_, true, _],
221 //!     [None, false, 1],
222 //! ]
223 //! ```
224 //!
225 //! and `p` is [_, false, _], the `Some` constructor doesn't appear in `P`. So if we
226 //! only had row 2, we'd know that `p` is useful. However row 1 starts with a
227 //! wildcard, so we need to check whether `U([[true, _]], [false, 1])`.
228 //!
229 //!   + Otherwise, all possible constructors (for the relevant type) are present. In this
230 //! case we must check whether the wildcard pattern covers any unmatched value. For
231 //! that, we can think of the `_` pattern as a big OR-pattern that covers all
232 //! possible constructors. For `Option`, that would mean `_ = None | Some(_)` for
233 //! example. The wildcard pattern is useful in this case if it is useful when
234 //! specialized to one of the possible constructors. So we compute:
235 //! `U(P, p) := ∃(k ϵ constructors) U(S(k, P), S(k, p))`
236 //!
237 //! For example, if `P` is:
238 //!
239 //! ```
240 //! [
241 //!     [Some(true), _],
242 //!     [None, false],
243 //! ]
244 //! ```
245 //!
246 //! and `p` is [_, false], both `None` and `Some` constructors appear in the first
247 //! components of `P`. We will therefore try popping both constructors in turn: we
248 //! compute `U([[true, _]], [_, false])` for the `Some` constructor, and `U([[false]],
249 //! [false])` for the `None` constructor. The first case returns true, so we know that
250 //! `p` is useful for `P`. Indeed, it matches `[Some(false), _]` that wasn't matched
251 //! before.
252 //!
253 //!   - If `p_1 == r_1 | r_2`, then the usefulness depends on each `r_i` separately:
254 //! `U(P, p) := U(P, (r_1, p_2, .., p_n))
255 //!  || U(P, (r_2, p_2, .., p_n))`
256 //!
257 //! Modifications to the algorithm
258 //! ------------------------------
259 //! The algorithm in the paper doesn't cover some of the special cases that arise in Rust, for
260 //! example uninhabited types and variable-length slice patterns. These are drawn attention to
261 //! throughout the code below. I'll make a quick note here about how exhaustive integer matching is
262 //! accounted for, though.
263 //!
264 //! Exhaustive integer matching
265 //! ---------------------------
266 //! An integer type can be thought of as a (huge) sum type: 1 | 2 | 3 | ...
267 //! So to support exhaustive integer matching, we can make use of the logic in the paper for
268 //! OR-patterns. However, we obviously can't just treat ranges x..=y as individual sums, because
269 //! they are likely gigantic. So we instead treat ranges as constructors of the integers. This means
270 //! that we have a constructor *of* constructors (the integers themselves). We then need to work
271 //! through all the inductive step rules above, deriving how the ranges would be treated as
272 //! OR-patterns, and making sure that they're treated in the same way even when they're ranges.
273 //! There are really only four special cases here:
274 //! - When we match on a constructor that's actually a range, we have to treat it as if we would
275 //!   an OR-pattern.
276 //!     + It turns out that we can simply extend the case for single-value patterns in
277 //!      `specialize` to either be *equal* to a value constructor, or *contained within* a range
278 //!      constructor.
279 //!     + When the pattern itself is a range, you just want to tell whether any of the values in
280 //!       the pattern range coincide with values in the constructor range, which is precisely
281 //!       intersection.
282 //!   Since when encountering a range pattern for a value constructor, we also use inclusion, it
283 //!   means that whenever the constructor is a value/range and the pattern is also a value/range,
284 //!   we can simply use intersection to test usefulness.
285 //! - When we're testing for usefulness of a pattern and the pattern's first component is a
286 //!   wildcard.
287 //!     + If all the constructors appear in the matrix, we have a slight complication. By default,
288 //!       the behaviour (i.e., a disjunction over specialised matrices for each constructor) is
289 //!       invalid, because we want a disjunction over every *integer* in each range, not just a
290 //!       disjunction over every range. This is a bit more tricky to deal with: essentially we need
291 //!       to form equivalence classes of subranges of the constructor range for which the behaviour
292 //!       of the matrix `P` and new pattern `p` are the same. This is described in more
293 //!       detail in `Constructor::split`.
294 //!     + If some constructors are missing from the matrix, it turns out we don't need to do
295 //!       anything special (because we know none of the integers are actually wildcards: i.e., we
296 //!       can't span wildcards using ranges).
297 use self::Constructor::*;
298 use self::SliceKind::*;
299 use self::Usefulness::*;
300 use self::WitnessPreference::*;
301
302 use rustc_data_structures::captures::Captures;
303 use rustc_data_structures::fx::FxHashSet;
304 use rustc_data_structures::sync::OnceCell;
305 use rustc_index::vec::Idx;
306
307 use super::{compare_const_vals, PatternFoldable, PatternFolder};
308 use super::{FieldPat, Pat, PatKind, PatRange};
309
310 use rustc_arena::TypedArena;
311 use rustc_attr::{SignedInt, UnsignedInt};
312 use rustc_hir::def_id::DefId;
313 use rustc_hir::{HirId, RangeEnd};
314 use rustc_middle::mir::interpret::ConstValue;
315 use rustc_middle::mir::Field;
316 use rustc_middle::ty::layout::IntegerExt;
317 use rustc_middle::ty::{self, Const, Ty, TyCtxt};
318 use rustc_session::lint;
319 use rustc_span::{Span, DUMMY_SP};
320 use rustc_target::abi::{Integer, Size, VariantIdx};
321
322 use smallvec::{smallvec, SmallVec};
323 use std::cmp::{self, max, min, Ordering};
324 use std::fmt;
325 use std::iter::{FromIterator, IntoIterator};
326 use std::ops::RangeInclusive;
327
328 crate fn expand_pattern<'tcx>(pat: Pat<'tcx>) -> Pat<'tcx> {
329     LiteralExpander.fold_pattern(&pat)
330 }
331
332 struct LiteralExpander;
333
334 impl<'tcx> PatternFolder<'tcx> for LiteralExpander {
335     fn fold_pattern(&mut self, pat: &Pat<'tcx>) -> Pat<'tcx> {
336         debug!("fold_pattern {:?} {:?} {:?}", pat, pat.ty.kind(), pat.kind);
337         match (pat.ty.kind(), pat.kind.as_ref()) {
338             (_, PatKind::Binding { subpattern: Some(s), .. }) => s.fold_with(self),
339             (_, PatKind::AscribeUserType { subpattern: s, .. }) => s.fold_with(self),
340             (ty::Ref(_, t, _), PatKind::Constant { .. }) if t.is_str() => {
341                 // Treat string literal patterns as deref patterns to a `str` constant, i.e.
342                 // `&CONST`. This expands them like other const patterns. This could have been done
343                 // in `const_to_pat`, but that causes issues with the rest of the matching code.
344                 let mut new_pat = pat.super_fold_with(self);
345                 // Make a fake const pattern of type `str` (instead of `&str`). That the carried
346                 // constant value still knows it is of type `&str`.
347                 new_pat.ty = t;
348                 Pat {
349                     kind: Box::new(PatKind::Deref { subpattern: new_pat }),
350                     span: pat.span,
351                     ty: pat.ty,
352                 }
353             }
354             _ => pat.super_fold_with(self),
355         }
356     }
357 }
358
359 impl<'tcx> Pat<'tcx> {
360     pub(super) fn is_wildcard(&self) -> bool {
361         matches!(*self.kind, PatKind::Binding { subpattern: None, .. } | PatKind::Wild)
362     }
363 }
364
365 /// A row of a matrix. Rows of len 1 are very common, which is why `SmallVec[_; 2]`
366 /// works well.
367 #[derive(Debug, Clone)]
368 struct PatStack<'p, 'tcx> {
369     pats: SmallVec<[&'p Pat<'tcx>; 2]>,
370     /// Cache for the constructor of the head
371     head_ctor: OnceCell<Constructor<'tcx>>,
372 }
373
374 impl<'p, 'tcx> PatStack<'p, 'tcx> {
375     fn from_pattern(pat: &'p Pat<'tcx>) -> Self {
376         Self::from_vec(smallvec![pat])
377     }
378
379     fn from_vec(vec: SmallVec<[&'p Pat<'tcx>; 2]>) -> Self {
380         PatStack { pats: vec, head_ctor: OnceCell::new() }
381     }
382
383     fn is_empty(&self) -> bool {
384         self.pats.is_empty()
385     }
386
387     fn len(&self) -> usize {
388         self.pats.len()
389     }
390
391     fn head(&self) -> &'p Pat<'tcx> {
392         self.pats[0]
393     }
394
395     fn head_ctor<'a>(&'a self, cx: &MatchCheckCtxt<'p, 'tcx>) -> &'a Constructor<'tcx> {
396         self.head_ctor.get_or_init(|| pat_constructor(cx, self.head()))
397     }
398
399     fn iter(&self) -> impl Iterator<Item = &Pat<'tcx>> {
400         self.pats.iter().copied()
401     }
402
403     // If the first pattern is an or-pattern, expand this pattern. Otherwise, return `None`.
404     fn expand_or_pat(&self) -> Option<Vec<Self>> {
405         if self.is_empty() {
406             None
407         } else if let PatKind::Or { pats } = &*self.head().kind {
408             Some(
409                 pats.iter()
410                     .map(|pat| {
411                         let mut new_patstack = PatStack::from_pattern(pat);
412                         new_patstack.pats.extend_from_slice(&self.pats[1..]);
413                         new_patstack
414                     })
415                     .collect(),
416             )
417         } else {
418             None
419         }
420     }
421
422     /// This computes `S(self.head_ctor(), self)`. See top of the file for explanations.
423     ///
424     /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
425     /// fields filled with wild patterns.
426     ///
427     /// This is roughly the inverse of `Constructor::apply`.
428     fn pop_head_constructor(&self, ctor_wild_subpatterns: &Fields<'p, 'tcx>) -> PatStack<'p, 'tcx> {
429         // We pop the head pattern and push the new fields extracted from the arguments of
430         // `self.head()`.
431         let new_fields = ctor_wild_subpatterns.replace_with_pattern_arguments(self.head());
432         new_fields.push_on_patstack(&self.pats[1..])
433     }
434 }
435
436 impl<'p, 'tcx> Default for PatStack<'p, 'tcx> {
437     fn default() -> Self {
438         Self::from_vec(smallvec![])
439     }
440 }
441
442 impl<'p, 'tcx> PartialEq for PatStack<'p, 'tcx> {
443     fn eq(&self, other: &Self) -> bool {
444         self.pats == other.pats
445     }
446 }
447
448 impl<'p, 'tcx> FromIterator<&'p Pat<'tcx>> for PatStack<'p, 'tcx> {
449     fn from_iter<T>(iter: T) -> Self
450     where
451         T: IntoIterator<Item = &'p Pat<'tcx>>,
452     {
453         Self::from_vec(iter.into_iter().collect())
454     }
455 }
456
457 /// A 2D matrix.
458 #[derive(Clone, PartialEq)]
459 struct Matrix<'p, 'tcx> {
460     patterns: Vec<PatStack<'p, 'tcx>>,
461 }
462
463 impl<'p, 'tcx> Matrix<'p, 'tcx> {
464     fn empty() -> Self {
465         Matrix { patterns: vec![] }
466     }
467
468     /// Pushes a new row to the matrix. If the row starts with an or-pattern, this expands it.
469     fn push(&mut self, row: PatStack<'p, 'tcx>) {
470         if let Some(rows) = row.expand_or_pat() {
471             for row in rows {
472                 // We recursively expand the or-patterns of the new rows.
473                 // This is necessary as we might have `0 | (1 | 2)` or e.g., `x @ 0 | x @ (1 | 2)`.
474                 self.push(row)
475             }
476         } else {
477             self.patterns.push(row);
478         }
479     }
480
481     /// Iterate over the first component of each row
482     fn heads<'a>(&'a self) -> impl Iterator<Item = &'a Pat<'tcx>> + Captures<'p> {
483         self.patterns.iter().map(|r| r.head())
484     }
485
486     /// Iterate over the first constructor of each row
487     fn head_ctors<'a>(
488         &'a self,
489         cx: &'a MatchCheckCtxt<'p, 'tcx>,
490     ) -> impl Iterator<Item = &'a Constructor<'tcx>> + Captures<'a> + Captures<'p> {
491         self.patterns.iter().map(move |r| r.head_ctor(cx))
492     }
493
494     /// This computes `S(constructor, self)`. See top of the file for explanations.
495     fn specialize_constructor(
496         &self,
497         pcx: PatCtxt<'_, 'p, 'tcx>,
498         ctor: &Constructor<'tcx>,
499         ctor_wild_subpatterns: &Fields<'p, 'tcx>,
500     ) -> Matrix<'p, 'tcx> {
501         self.patterns
502             .iter()
503             .filter(|r| ctor.is_covered_by(pcx, r.head_ctor(pcx.cx)))
504             .map(|r| r.pop_head_constructor(ctor_wild_subpatterns))
505             .collect()
506     }
507 }
508
509 /// Pretty-printer for matrices of patterns, example:
510 ///
511 /// ```text
512 /// +++++++++++++++++++++++++++++
513 /// + _     + []                +
514 /// +++++++++++++++++++++++++++++
515 /// + true  + [First]           +
516 /// +++++++++++++++++++++++++++++
517 /// + true  + [Second(true)]    +
518 /// +++++++++++++++++++++++++++++
519 /// + false + [_]               +
520 /// +++++++++++++++++++++++++++++
521 /// + _     + [_, _, tail @ ..] +
522 /// +++++++++++++++++++++++++++++
523 /// ```
524 impl<'p, 'tcx> fmt::Debug for Matrix<'p, 'tcx> {
525     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
526         write!(f, "\n")?;
527
528         let Matrix { patterns: m, .. } = self;
529         let pretty_printed_matrix: Vec<Vec<String>> =
530             m.iter().map(|row| row.iter().map(|pat| format!("{:?}", pat)).collect()).collect();
531
532         let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0);
533         assert!(m.iter().all(|row| row.len() == column_count));
534         let column_widths: Vec<usize> = (0..column_count)
535             .map(|col| pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0))
536             .collect();
537
538         let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1;
539         let br = "+".repeat(total_width);
540         write!(f, "{}\n", br)?;
541         for row in pretty_printed_matrix {
542             write!(f, "+")?;
543             for (column, pat_str) in row.into_iter().enumerate() {
544                 write!(f, " ")?;
545                 write!(f, "{:1$}", pat_str, column_widths[column])?;
546                 write!(f, " +")?;
547             }
548             write!(f, "\n")?;
549             write!(f, "{}\n", br)?;
550         }
551         Ok(())
552     }
553 }
554
555 impl<'p, 'tcx> FromIterator<PatStack<'p, 'tcx>> for Matrix<'p, 'tcx> {
556     fn from_iter<T>(iter: T) -> Self
557     where
558         T: IntoIterator<Item = PatStack<'p, 'tcx>>,
559     {
560         let mut matrix = Matrix::empty();
561         for x in iter {
562             // Using `push` ensures we correctly expand or-patterns.
563             matrix.push(x);
564         }
565         matrix
566     }
567 }
568
569 crate struct MatchCheckCtxt<'a, 'tcx> {
570     crate tcx: TyCtxt<'tcx>,
571     /// The module in which the match occurs. This is necessary for
572     /// checking inhabited-ness of types because whether a type is (visibly)
573     /// inhabited can depend on whether it was defined in the current module or
574     /// not. E.g., `struct Foo { _private: ! }` cannot be seen to be empty
575     /// outside it's module and should not be matchable with an empty match
576     /// statement.
577     crate module: DefId,
578     crate param_env: ty::ParamEnv<'tcx>,
579     crate pattern_arena: &'a TypedArena<Pat<'tcx>>,
580 }
581
582 impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> {
583     fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool {
584         if self.tcx.features().exhaustive_patterns {
585             self.tcx.is_ty_uninhabited_from(self.module, ty, self.param_env)
586         } else {
587             false
588         }
589     }
590
591     /// Returns whether the given type is an enum from another crate declared `#[non_exhaustive]`.
592     fn is_foreign_non_exhaustive_enum(&self, ty: Ty<'tcx>) -> bool {
593         match ty.kind() {
594             ty::Adt(def, ..) => {
595                 def.is_enum() && def.is_variant_list_non_exhaustive() && !def.did.is_local()
596             }
597             _ => false,
598         }
599     }
600 }
601
602 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
603 enum SliceKind {
604     /// Patterns of length `n` (`[x, y]`).
605     FixedLen(u64),
606     /// Patterns using the `..` notation (`[x, .., y]`).
607     /// Captures any array constructor of `length >= i + j`.
608     /// In the case where `array_len` is `Some(_)`,
609     /// this indicates that we only care about the first `i` and the last `j` values of the array,
610     /// and everything in between is a wildcard `_`.
611     VarLen(u64, u64),
612 }
613
614 impl SliceKind {
615     fn arity(self) -> u64 {
616         match self {
617             FixedLen(length) => length,
618             VarLen(prefix, suffix) => prefix + suffix,
619         }
620     }
621
622     /// Whether this pattern includes patterns of length `other_len`.
623     fn covers_length(self, other_len: u64) -> bool {
624         match self {
625             FixedLen(len) => len == other_len,
626             VarLen(prefix, suffix) => prefix + suffix <= other_len,
627         }
628     }
629 }
630
631 /// A constructor for array and slice patterns.
632 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
633 struct Slice {
634     /// `None` if the matched value is a slice, `Some(n)` if it is an array of size `n`.
635     array_len: Option<u64>,
636     /// The kind of pattern it is: fixed-length `[x, y]` or variable length `[x, .., y]`.
637     kind: SliceKind,
638 }
639
640 impl Slice {
641     fn new(array_len: Option<u64>, kind: SliceKind) -> Self {
642         let kind = match (array_len, kind) {
643             // If the middle `..` is empty, we effectively have a fixed-length pattern.
644             (Some(len), VarLen(prefix, suffix)) if prefix + suffix >= len => FixedLen(len),
645             _ => kind,
646         };
647         Slice { array_len, kind }
648     }
649
650     fn arity(self) -> u64 {
651         self.kind.arity()
652     }
653
654     /// The exhaustiveness-checking paper does not include any details on
655     /// checking variable-length slice patterns. However, they may be
656     /// matched by an infinite collection of fixed-length array patterns.
657     ///
658     /// Checking the infinite set directly would take an infinite amount
659     /// of time. However, it turns out that for each finite set of
660     /// patterns `P`, all sufficiently large array lengths are equivalent:
661     ///
662     /// Each slice `s` with a "sufficiently-large" length `l ≥ L` that applies
663     /// to exactly the subset `Pₜ` of `P` can be transformed to a slice
664     /// `sₘ` for each sufficiently-large length `m` that applies to exactly
665     /// the same subset of `P`.
666     ///
667     /// Because of that, each witness for reachability-checking of one
668     /// of the sufficiently-large lengths can be transformed to an
669     /// equally-valid witness of any other length, so we only have
670     /// to check slices of the "minimal sufficiently-large length"
671     /// and less.
672     ///
673     /// Note that the fact that there is a *single* `sₘ` for each `m`
674     /// not depending on the specific pattern in `P` is important: if
675     /// you look at the pair of patterns
676     ///     `[true, ..]`
677     ///     `[.., false]`
678     /// Then any slice of length ≥1 that matches one of these two
679     /// patterns can be trivially turned to a slice of any
680     /// other length ≥1 that matches them and vice-versa,
681     /// but the slice of length 2 `[false, true]` that matches neither
682     /// of these patterns can't be turned to a slice from length 1 that
683     /// matches neither of these patterns, so we have to consider
684     /// slices from length 2 there.
685     ///
686     /// Now, to see that that length exists and find it, observe that slice
687     /// patterns are either "fixed-length" patterns (`[_, _, _]`) or
688     /// "variable-length" patterns (`[_, .., _]`).
689     ///
690     /// For fixed-length patterns, all slices with lengths *longer* than
691     /// the pattern's length have the same outcome (of not matching), so
692     /// as long as `L` is greater than the pattern's length we can pick
693     /// any `sₘ` from that length and get the same result.
694     ///
695     /// For variable-length patterns, the situation is more complicated,
696     /// because as seen above the precise value of `sₘ` matters.
697     ///
698     /// However, for each variable-length pattern `p` with a prefix of length
699     /// `plₚ` and suffix of length `slₚ`, only the first `plₚ` and the last
700     /// `slₚ` elements are examined.
701     ///
702     /// Therefore, as long as `L` is positive (to avoid concerns about empty
703     /// types), all elements after the maximum prefix length and before
704     /// the maximum suffix length are not examined by any variable-length
705     /// pattern, and therefore can be added/removed without affecting
706     /// them - creating equivalent patterns from any sufficiently-large
707     /// length.
708     ///
709     /// Of course, if fixed-length patterns exist, we must be sure
710     /// that our length is large enough to miss them all, so
711     /// we can pick `L = max(max(FIXED_LEN)+1, max(PREFIX_LEN) + max(SUFFIX_LEN))`
712     ///
713     /// for example, with the above pair of patterns, all elements
714     /// but the first and last can be added/removed, so any
715     /// witness of length ≥2 (say, `[false, false, true]`) can be
716     /// turned to a witness from any other length ≥2.
717     fn split<'p, 'tcx>(self, pcx: PatCtxt<'_, 'p, 'tcx>) -> SmallVec<[Constructor<'tcx>; 1]> {
718         let (self_prefix, self_suffix) = match self.kind {
719             VarLen(self_prefix, self_suffix) => (self_prefix, self_suffix),
720             _ => return smallvec![Slice(self)],
721         };
722
723         let head_ctors = pcx.matrix.head_ctors(pcx.cx).filter(|c| !c.is_wildcard());
724
725         let mut max_prefix_len = self_prefix;
726         let mut max_suffix_len = self_suffix;
727         let mut max_fixed_len = 0;
728
729         for ctor in head_ctors {
730             if let Slice(slice) = ctor {
731                 match slice.kind {
732                     FixedLen(len) => {
733                         max_fixed_len = cmp::max(max_fixed_len, len);
734                     }
735                     VarLen(prefix, suffix) => {
736                         max_prefix_len = cmp::max(max_prefix_len, prefix);
737                         max_suffix_len = cmp::max(max_suffix_len, suffix);
738                     }
739                 }
740             } else {
741                 bug!("unexpected ctor for slice type: {:?}", ctor);
742             }
743         }
744
745         // For diagnostics, we keep the prefix and suffix lengths separate, so in the case
746         // where `max_fixed_len + 1` is the largest, we adapt `max_prefix_len` accordingly,
747         // so that `L = max_prefix_len + max_suffix_len`.
748         if max_fixed_len + 1 >= max_prefix_len + max_suffix_len {
749             // The subtraction can't overflow thanks to the above check.
750             // The new `max_prefix_len` is also guaranteed to be larger than its previous
751             // value.
752             max_prefix_len = max_fixed_len + 1 - max_suffix_len;
753         }
754
755         let final_slice = VarLen(max_prefix_len, max_suffix_len);
756         let final_slice = Slice::new(self.array_len, final_slice);
757         match self.array_len {
758             Some(_) => smallvec![Slice(final_slice)],
759             None => {
760                 // `self` originally covered the range `(self.arity()..infinity)`. We split that
761                 // range into two: lengths smaller than `final_slice.arity()` are treated
762                 // independently as fixed-lengths slices, and lengths above are captured by
763                 // `final_slice`.
764                 let smaller_lengths = (self.arity()..final_slice.arity()).map(FixedLen);
765                 smaller_lengths
766                     .map(|kind| Slice::new(self.array_len, kind))
767                     .chain(Some(final_slice))
768                     .map(Slice)
769                     .collect()
770             }
771         }
772     }
773
774     /// See `Constructor::is_covered_by`
775     fn is_covered_by(self, other: Self) -> bool {
776         other.kind.covers_length(self.arity())
777     }
778 }
779
780 /// A value can be decomposed into a constructor applied to some fields. This struct represents
781 /// the constructor. See also `Fields`.
782 ///
783 /// `pat_constructor` retrieves the constructor corresponding to a pattern.
784 /// `specialize_constructor` returns the list of fields corresponding to a pattern, given a
785 /// constructor. `Constructor::apply` reconstructs the pattern from a pair of `Constructor` and
786 /// `Fields`.
787 #[derive(Clone, Debug, PartialEq)]
788 enum Constructor<'tcx> {
789     /// The constructor for patterns that have a single constructor, like tuples, struct patterns
790     /// and fixed-length arrays.
791     Single,
792     /// Enum variants.
793     Variant(DefId),
794     /// Ranges of integer literal values (`2`, `2..=5` or `2..5`).
795     IntRange(IntRange<'tcx>),
796     /// Ranges of floating-point literal values (`2.0..=5.2`).
797     FloatRange(&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>, RangeEnd),
798     /// String literals. Strings are not quite the same as `&[u8]` so we treat them separately.
799     Str(&'tcx ty::Const<'tcx>),
800     /// Array and slice patterns.
801     Slice(Slice),
802     /// Constants that must not be matched structurally. They are treated as black
803     /// boxes for the purposes of exhaustiveness: we must not inspect them, and they
804     /// don't count towards making a match exhaustive.
805     Opaque,
806     /// Fake extra constructor for enums that aren't allowed to be matched exhaustively. Also used
807     /// for those types for which we cannot list constructors explicitly, like `f64` and `str`.
808     NonExhaustive,
809     /// Wildcard pattern.
810     Wildcard,
811 }
812
813 impl<'tcx> Constructor<'tcx> {
814     fn is_wildcard(&self) -> bool {
815         matches!(self, Wildcard)
816     }
817
818     fn as_int_range(&self) -> Option<&IntRange<'tcx>> {
819         match self {
820             IntRange(range) => Some(range),
821             _ => None,
822         }
823     }
824
825     fn as_slice(&self) -> Option<Slice> {
826         match self {
827             Slice(slice) => Some(*slice),
828             _ => None,
829         }
830     }
831
832     fn variant_index_for_adt(&self, adt: &'tcx ty::AdtDef) -> VariantIdx {
833         match *self {
834             Variant(id) => adt.variant_index_with_id(id),
835             Single => {
836                 assert!(!adt.is_enum());
837                 VariantIdx::new(0)
838             }
839             _ => bug!("bad constructor {:?} for adt {:?}", self, adt),
840         }
841     }
842
843     /// Some constructors (namely `Wildcard`, `IntRange` and `Slice`) actually stand for a set of actual
844     /// constructors (like variants, integers or fixed-sized slices). When specializing for these
845     /// constructors, we want to be specialising for the actual underlying constructors.
846     /// Naively, we would simply return the list of constructors they correspond to. We instead are
847     /// more clever: if there are constructors that we know will behave the same wrt the current
848     /// matrix, we keep them grouped. For example, all slices of a sufficiently large length
849     /// will either be all useful or all non-useful with a given matrix.
850     ///
851     /// See the branches for details on how the splitting is done.
852     ///
853     /// This function may discard some irrelevant constructors if this preserves behavior and
854     /// diagnostics. Eg. for the `_` case, we ignore the constructors already present in the
855     /// matrix, unless all of them are.
856     ///
857     /// `hir_id` is `None` when we're evaluating the wildcard pattern. In that case we do not want
858     /// to lint for overlapping ranges.
859     fn split<'p>(&self, pcx: PatCtxt<'_, 'p, 'tcx>, hir_id: Option<HirId>) -> SmallVec<[Self; 1]> {
860         debug!("Constructor::split({:#?}, {:#?})", self, pcx.matrix);
861
862         match self {
863             Wildcard => Constructor::split_wildcard(pcx),
864             // Fast-track if the range is trivial. In particular, we don't do the overlapping
865             // ranges check.
866             IntRange(ctor_range)
867                 if ctor_range.treat_exhaustively(pcx.cx.tcx) && !ctor_range.is_singleton() =>
868             {
869                 ctor_range.split(pcx, hir_id)
870             }
871             Slice(slice @ Slice { kind: VarLen(..), .. }) => slice.split(pcx),
872             // Any other constructor can be used unchanged.
873             _ => smallvec![self.clone()],
874         }
875     }
876
877     /// For wildcards, there are two groups of constructors: there are the constructors actually
878     /// present in the matrix (`head_ctors`), and the constructors not present (`missing_ctors`).
879     /// Two constructors that are not in the matrix will either both be caught (by a wildcard), or
880     /// both not be caught. Therefore we can keep the missing constructors grouped together.
881     fn split_wildcard<'p>(pcx: PatCtxt<'_, 'p, 'tcx>) -> SmallVec<[Self; 1]> {
882         // Missing constructors are those that are not matched by any non-wildcard patterns in the
883         // current column. We only fully construct them on-demand, because they're rarely used and
884         // can be big.
885         let missing_ctors = MissingConstructors::new(pcx);
886         if missing_ctors.is_empty(pcx) {
887             // All the constructors are present in the matrix, so we just go through them all.
888             // We must also split them first.
889             missing_ctors.all_ctors
890         } else {
891             // Some constructors are missing, thus we can specialize with the wildcard constructor,
892             // which will stand for those constructors that are missing, and behaves like any of
893             // them.
894             smallvec![Wildcard]
895         }
896     }
897
898     /// Returns whether `self` is covered by `other`, i.e. whether `self` is a subset of `other`.
899     /// For the simple cases, this is simply checking for equality. For the "grouped" constructors,
900     /// this checks for inclusion.
901     fn is_covered_by<'p>(&self, pcx: PatCtxt<'_, 'p, 'tcx>, other: &Self) -> bool {
902         // This must be kept in sync with `is_covered_by_any`.
903         match (self, other) {
904             // Wildcards cover anything
905             (_, Wildcard) => true,
906             // Wildcards are only covered by wildcards
907             (Wildcard, _) => false,
908
909             (Single, Single) => true,
910             (Variant(self_id), Variant(other_id)) => self_id == other_id,
911
912             (IntRange(self_range), IntRange(other_range)) => {
913                 self_range.is_covered_by(pcx, other_range)
914             }
915             (
916                 FloatRange(self_from, self_to, self_end),
917                 FloatRange(other_from, other_to, other_end),
918             ) => {
919                 match (
920                     compare_const_vals(pcx.cx.tcx, self_to, other_to, pcx.cx.param_env, pcx.ty),
921                     compare_const_vals(pcx.cx.tcx, self_from, other_from, pcx.cx.param_env, pcx.ty),
922                 ) {
923                     (Some(to), Some(from)) => {
924                         (from == Ordering::Greater || from == Ordering::Equal)
925                             && (to == Ordering::Less
926                                 || (other_end == self_end && to == Ordering::Equal))
927                     }
928                     _ => false,
929                 }
930             }
931             (Str(self_val), Str(other_val)) => {
932                 // FIXME: there's probably a more direct way of comparing for equality
933                 match compare_const_vals(pcx.cx.tcx, self_val, other_val, pcx.cx.param_env, pcx.ty)
934                 {
935                     Some(comparison) => comparison == Ordering::Equal,
936                     None => false,
937                 }
938             }
939             (Slice(self_slice), Slice(other_slice)) => self_slice.is_covered_by(*other_slice),
940
941             // We are trying to inspect an opaque constant. Thus we skip the row.
942             (Opaque, _) | (_, Opaque) => false,
943             // Only a wildcard pattern can match the special extra constructor.
944             (NonExhaustive, _) => false,
945
946             _ => span_bug!(
947                 pcx.span,
948                 "trying to compare incompatible constructors {:?} and {:?}",
949                 self,
950                 other
951             ),
952         }
953     }
954
955     /// Faster version of `is_covered_by` when applied to many constructors. `used_ctors` is
956     /// assumed to be built from `matrix.head_ctors()` with wildcards filtered out, and `self` is
957     /// assumed to have been split from a wildcard.
958     fn is_covered_by_any<'p>(
959         &self,
960         pcx: PatCtxt<'_, 'p, 'tcx>,
961         used_ctors: &[Constructor<'tcx>],
962     ) -> bool {
963         if used_ctors.is_empty() {
964             return false;
965         }
966
967         // This must be kept in sync with `is_covered_by`.
968         match self {
969             // If `self` is `Single`, `used_ctors` cannot contain anything else than `Single`s.
970             Single => !used_ctors.is_empty(),
971             Variant(_) => used_ctors.iter().any(|c| c == self),
972             IntRange(range) => used_ctors
973                 .iter()
974                 .filter_map(|c| c.as_int_range())
975                 .any(|other| range.is_covered_by(pcx, other)),
976             Slice(slice) => used_ctors
977                 .iter()
978                 .filter_map(|c| c.as_slice())
979                 .any(|other| slice.is_covered_by(other)),
980             // This constructor is never covered by anything else
981             NonExhaustive => false,
982             Str(..) | FloatRange(..) | Opaque | Wildcard => {
983                 bug!("found unexpected ctor in all_ctors: {:?}", self)
984             }
985         }
986     }
987
988     /// Apply a constructor to a list of patterns, yielding a new pattern. `pats`
989     /// must have as many elements as this constructor's arity.
990     ///
991     /// This is roughly the inverse of `specialize_constructor`.
992     ///
993     /// Examples:
994     /// `self`: `Constructor::Single`
995     /// `ty`: `(u32, u32, u32)`
996     /// `pats`: `[10, 20, _]`
997     /// returns `(10, 20, _)`
998     ///
999     /// `self`: `Constructor::Variant(Option::Some)`
1000     /// `ty`: `Option<bool>`
1001     /// `pats`: `[false]`
1002     /// returns `Some(false)`
1003     fn apply<'p>(&self, pcx: PatCtxt<'_, 'p, 'tcx>, fields: Fields<'p, 'tcx>) -> Pat<'tcx> {
1004         let mut subpatterns = fields.all_patterns();
1005
1006         let pat = match self {
1007             Single | Variant(_) => match pcx.ty.kind() {
1008                 ty::Adt(..) | ty::Tuple(..) => {
1009                     let subpatterns = subpatterns
1010                         .enumerate()
1011                         .map(|(i, p)| FieldPat { field: Field::new(i), pattern: p })
1012                         .collect();
1013
1014                     if let ty::Adt(adt, substs) = pcx.ty.kind() {
1015                         if adt.is_enum() {
1016                             PatKind::Variant {
1017                                 adt_def: adt,
1018                                 substs,
1019                                 variant_index: self.variant_index_for_adt(adt),
1020                                 subpatterns,
1021                             }
1022                         } else {
1023                             PatKind::Leaf { subpatterns }
1024                         }
1025                     } else {
1026                         PatKind::Leaf { subpatterns }
1027                     }
1028                 }
1029                 // Note: given the expansion of `&str` patterns done in `expand_pattern`, we should
1030                 // be careful to reconstruct the correct constant pattern here. However a string
1031                 // literal pattern will never be reported as a non-exhaustiveness witness, so we
1032                 // can ignore this issue.
1033                 ty::Ref(..) => PatKind::Deref { subpattern: subpatterns.next().unwrap() },
1034                 ty::Slice(_) | ty::Array(..) => bug!("bad slice pattern {:?} {:?}", self, pcx.ty),
1035                 _ => PatKind::Wild,
1036             },
1037             Slice(slice) => match slice.kind {
1038                 FixedLen(_) => {
1039                     PatKind::Slice { prefix: subpatterns.collect(), slice: None, suffix: vec![] }
1040                 }
1041                 VarLen(prefix, _) => {
1042                     let mut prefix: Vec<_> = subpatterns.by_ref().take(prefix as usize).collect();
1043                     if slice.array_len.is_some() {
1044                         // Improves diagnostics a bit: if the type is a known-size array, instead
1045                         // of reporting `[x, _, .., _, y]`, we prefer to report `[x, .., y]`.
1046                         // This is incorrect if the size is not known, since `[_, ..]` captures
1047                         // arrays of lengths `>= 1` whereas `[..]` captures any length.
1048                         while !prefix.is_empty() && prefix.last().unwrap().is_wildcard() {
1049                             prefix.pop();
1050                         }
1051                     }
1052                     let suffix: Vec<_> = if slice.array_len.is_some() {
1053                         // Same as above.
1054                         subpatterns.skip_while(Pat::is_wildcard).collect()
1055                     } else {
1056                         subpatterns.collect()
1057                     };
1058                     let wild = Pat::wildcard_from_ty(pcx.ty);
1059                     PatKind::Slice { prefix, slice: Some(wild), suffix }
1060                 }
1061             },
1062             &Str(value) => PatKind::Constant { value },
1063             &FloatRange(lo, hi, end) => PatKind::Range(PatRange { lo, hi, end }),
1064             IntRange(range) => return range.to_pat(pcx.cx.tcx),
1065             NonExhaustive => PatKind::Wild,
1066             Opaque => bug!("we should not try to apply an opaque constructor"),
1067             Wildcard => bug!(
1068                 "trying to apply a wildcard constructor; this should have been done in `apply_constructors`"
1069             ),
1070         };
1071
1072         Pat { ty: pcx.ty, span: DUMMY_SP, kind: Box::new(pat) }
1073     }
1074 }
1075
1076 /// Some fields need to be explicitly hidden away in certain cases; see the comment above the
1077 /// `Fields` struct. This struct represents such a potentially-hidden field. When a field is hidden
1078 /// we still keep its type around.
1079 #[derive(Debug, Copy, Clone)]
1080 enum FilteredField<'p, 'tcx> {
1081     Kept(&'p Pat<'tcx>),
1082     Hidden(Ty<'tcx>),
1083 }
1084
1085 impl<'p, 'tcx> FilteredField<'p, 'tcx> {
1086     fn kept(self) -> Option<&'p Pat<'tcx>> {
1087         match self {
1088             FilteredField::Kept(p) => Some(p),
1089             FilteredField::Hidden(_) => None,
1090         }
1091     }
1092
1093     fn to_pattern(self) -> Pat<'tcx> {
1094         match self {
1095             FilteredField::Kept(p) => p.clone(),
1096             FilteredField::Hidden(ty) => Pat::wildcard_from_ty(ty),
1097         }
1098     }
1099 }
1100
1101 /// A value can be decomposed into a constructor applied to some fields. This struct represents
1102 /// those fields, generalized to allow patterns in each field. See also `Constructor`.
1103 ///
1104 /// If a private or `non_exhaustive` field is uninhabited, the code mustn't observe that it is
1105 /// uninhabited. For that, we filter these fields out of the matrix. This is subtle because we
1106 /// still need to have those fields back when going to/from a `Pat`. Most of this is handled
1107 /// automatically in `Fields`, but when constructing or deconstructing `Fields` you need to be
1108 /// careful. As a rule, when going to/from the matrix, use the filtered field list; when going
1109 /// to/from `Pat`, use the full field list.
1110 /// This filtering is uncommon in practice, because uninhabited fields are rarely used, so we avoid
1111 /// it when possible to preserve performance.
1112 #[derive(Debug, Clone)]
1113 enum Fields<'p, 'tcx> {
1114     /// Lists of patterns that don't contain any filtered fields.
1115     /// `Slice` and `Vec` behave the same; the difference is only to avoid allocating and
1116     /// triple-dereferences when possible. Frankly this is premature optimization, I (Nadrieril)
1117     /// have not measured if it really made a difference.
1118     Slice(&'p [Pat<'tcx>]),
1119     Vec(SmallVec<[&'p Pat<'tcx>; 2]>),
1120     /// Patterns where some of the fields need to be hidden. `kept_count` caches the number of
1121     /// non-hidden fields.
1122     Filtered {
1123         fields: SmallVec<[FilteredField<'p, 'tcx>; 2]>,
1124         kept_count: usize,
1125     },
1126 }
1127
1128 impl<'p, 'tcx> Fields<'p, 'tcx> {
1129     fn empty() -> Self {
1130         Fields::Slice(&[])
1131     }
1132
1133     /// Construct a new `Fields` from the given pattern. Must not be used if the pattern is a field
1134     /// of a struct/tuple/variant.
1135     fn from_single_pattern(pat: &'p Pat<'tcx>) -> Self {
1136         Fields::Slice(std::slice::from_ref(pat))
1137     }
1138
1139     /// Convenience; internal use.
1140     fn wildcards_from_tys(
1141         cx: &MatchCheckCtxt<'p, 'tcx>,
1142         tys: impl IntoIterator<Item = Ty<'tcx>>,
1143     ) -> Self {
1144         let wilds = tys.into_iter().map(Pat::wildcard_from_ty);
1145         let pats = cx.pattern_arena.alloc_from_iter(wilds);
1146         Fields::Slice(pats)
1147     }
1148
1149     /// Creates a new list of wildcard fields for a given constructor.
1150     fn wildcards(pcx: PatCtxt<'_, 'p, 'tcx>, constructor: &Constructor<'tcx>) -> Self {
1151         let ty = pcx.ty;
1152         let cx = pcx.cx;
1153         let wildcard_from_ty = |ty| &*cx.pattern_arena.alloc(Pat::wildcard_from_ty(ty));
1154
1155         let ret = match constructor {
1156             Single | Variant(_) => match ty.kind() {
1157                 ty::Tuple(ref fs) => {
1158                     Fields::wildcards_from_tys(cx, fs.into_iter().map(|ty| ty.expect_ty()))
1159                 }
1160                 ty::Ref(_, rty, _) => Fields::from_single_pattern(wildcard_from_ty(rty)),
1161                 ty::Adt(adt, substs) => {
1162                     if adt.is_box() {
1163                         // Use T as the sub pattern type of Box<T>.
1164                         Fields::from_single_pattern(wildcard_from_ty(substs.type_at(0)))
1165                     } else {
1166                         let variant = &adt.variants[constructor.variant_index_for_adt(adt)];
1167                         // Whether we must not match the fields of this variant exhaustively.
1168                         let is_non_exhaustive =
1169                             variant.is_field_list_non_exhaustive() && !adt.did.is_local();
1170                         let field_tys = variant.fields.iter().map(|field| field.ty(cx.tcx, substs));
1171                         // In the following cases, we don't need to filter out any fields. This is
1172                         // the vast majority of real cases, since uninhabited fields are uncommon.
1173                         let has_no_hidden_fields = (adt.is_enum() && !is_non_exhaustive)
1174                             || !field_tys.clone().any(|ty| cx.is_uninhabited(ty));
1175
1176                         if has_no_hidden_fields {
1177                             Fields::wildcards_from_tys(cx, field_tys)
1178                         } else {
1179                             let mut kept_count = 0;
1180                             let fields = variant
1181                                 .fields
1182                                 .iter()
1183                                 .map(|field| {
1184                                     let ty = field.ty(cx.tcx, substs);
1185                                     let is_visible = adt.is_enum()
1186                                         || field.vis.is_accessible_from(cx.module, cx.tcx);
1187                                     let is_uninhabited = cx.is_uninhabited(ty);
1188
1189                                     // In the cases of either a `#[non_exhaustive]` field list
1190                                     // or a non-public field, we hide uninhabited fields in
1191                                     // order not to reveal the uninhabitedness of the whole
1192                                     // variant.
1193                                     if is_uninhabited && (!is_visible || is_non_exhaustive) {
1194                                         FilteredField::Hidden(ty)
1195                                     } else {
1196                                         kept_count += 1;
1197                                         FilteredField::Kept(wildcard_from_ty(ty))
1198                                     }
1199                                 })
1200                                 .collect();
1201                             Fields::Filtered { fields, kept_count }
1202                         }
1203                     }
1204                 }
1205                 _ => bug!("Unexpected type for `Single` constructor: {:?}", ty),
1206             },
1207             Slice(slice) => match *ty.kind() {
1208                 ty::Slice(ty) | ty::Array(ty, _) => {
1209                     let arity = slice.arity();
1210                     Fields::wildcards_from_tys(cx, (0..arity).map(|_| ty))
1211                 }
1212                 _ => bug!("bad slice pattern {:?} {:?}", constructor, ty),
1213             },
1214             Str(..) | FloatRange(..) | IntRange(..) | NonExhaustive | Opaque | Wildcard => {
1215                 Fields::empty()
1216             }
1217         };
1218         debug!("Fields::wildcards({:?}, {:?}) = {:#?}", constructor, ty, ret);
1219         ret
1220     }
1221
1222     /// Returns the number of patterns from the viewpoint of match-checking, i.e. excluding hidden
1223     /// fields. This is what we want in most cases in this file, the only exception being
1224     /// conversion to/from `Pat`.
1225     fn len(&self) -> usize {
1226         match self {
1227             Fields::Slice(pats) => pats.len(),
1228             Fields::Vec(pats) => pats.len(),
1229             Fields::Filtered { kept_count, .. } => *kept_count,
1230         }
1231     }
1232
1233     /// Returns the complete list of patterns, including hidden fields.
1234     fn all_patterns(self) -> impl Iterator<Item = Pat<'tcx>> {
1235         let pats: SmallVec<[_; 2]> = match self {
1236             Fields::Slice(pats) => pats.iter().cloned().collect(),
1237             Fields::Vec(pats) => pats.into_iter().cloned().collect(),
1238             Fields::Filtered { fields, .. } => {
1239                 // We don't skip any fields here.
1240                 fields.into_iter().map(|p| p.to_pattern()).collect()
1241             }
1242         };
1243         pats.into_iter()
1244     }
1245
1246     /// Overrides some of the fields with the provided patterns. Exactly like
1247     /// `replace_fields_indexed`, except that it takes `FieldPat`s as input.
1248     fn replace_with_fieldpats(
1249         &self,
1250         new_pats: impl IntoIterator<Item = &'p FieldPat<'tcx>>,
1251     ) -> Self {
1252         self.replace_fields_indexed(
1253             new_pats.into_iter().map(|pat| (pat.field.index(), &pat.pattern)),
1254         )
1255     }
1256
1257     /// Overrides some of the fields with the provided patterns. This is used when a pattern
1258     /// defines some fields but not all, for example `Foo { field1: Some(_), .. }`: here we start with a
1259     /// `Fields` that is just one wildcard per field of the `Foo` struct, and override the entry
1260     /// corresponding to `field1` with the pattern `Some(_)`. This is also used for slice patterns
1261     /// for the same reason.
1262     fn replace_fields_indexed(
1263         &self,
1264         new_pats: impl IntoIterator<Item = (usize, &'p Pat<'tcx>)>,
1265     ) -> Self {
1266         let mut fields = self.clone();
1267         if let Fields::Slice(pats) = fields {
1268             fields = Fields::Vec(pats.iter().collect());
1269         }
1270
1271         match &mut fields {
1272             Fields::Vec(pats) => {
1273                 for (i, pat) in new_pats {
1274                     pats[i] = pat
1275                 }
1276             }
1277             Fields::Filtered { fields, .. } => {
1278                 for (i, pat) in new_pats {
1279                     if let FilteredField::Kept(p) = &mut fields[i] {
1280                         *p = pat
1281                     }
1282                 }
1283             }
1284             Fields::Slice(_) => unreachable!(),
1285         }
1286         fields
1287     }
1288
1289     /// Replaces contained fields with the given filtered list of patterns, e.g. taken from the
1290     /// matrix. There must be `len()` patterns in `pats`.
1291     fn replace_fields(
1292         &self,
1293         cx: &MatchCheckCtxt<'p, 'tcx>,
1294         pats: impl IntoIterator<Item = Pat<'tcx>>,
1295     ) -> Self {
1296         let pats: &[_] = cx.pattern_arena.alloc_from_iter(pats);
1297
1298         match self {
1299             Fields::Filtered { fields, kept_count } => {
1300                 let mut pats = pats.iter();
1301                 let mut fields = fields.clone();
1302                 for f in &mut fields {
1303                     if let FilteredField::Kept(p) = f {
1304                         // We take one input pattern for each `Kept` field, in order.
1305                         *p = pats.next().unwrap();
1306                     }
1307                 }
1308                 Fields::Filtered { fields, kept_count: *kept_count }
1309             }
1310             _ => Fields::Slice(pats),
1311         }
1312     }
1313
1314     /// Replaces contained fields with the arguments of the given pattern. Only use on a pattern
1315     /// that is compatible with the constructor used to build `self`.
1316     /// This is meant to be used on the result of `Fields::wildcards()`. The idea is that
1317     /// `wildcards` constructs a list of fields where all entries are wildcards, and the pattern
1318     /// provided to this function fills some of the fields with non-wildcards.
1319     /// In the following example `Fields::wildcards` would return `[_, _, _, _]`. If we call
1320     /// `replace_with_pattern_arguments` on it with the pattern, the result will be `[Some(0), _,
1321     /// _, _]`.
1322     /// ```rust
1323     /// let x: [Option<u8>; 4] = foo();
1324     /// match x {
1325     ///     [Some(0), ..] => {}
1326     /// }
1327     /// ```
1328     /// This is guaranteed to preserve the number of patterns in `self`.
1329     fn replace_with_pattern_arguments(&self, pat: &'p Pat<'tcx>) -> Self {
1330         match pat.kind.as_ref() {
1331             PatKind::Deref { subpattern } => {
1332                 assert_eq!(self.len(), 1);
1333                 Fields::from_single_pattern(subpattern)
1334             }
1335             PatKind::Leaf { subpatterns } | PatKind::Variant { subpatterns, .. } => {
1336                 self.replace_with_fieldpats(subpatterns)
1337             }
1338             PatKind::Array { prefix, suffix, .. } | PatKind::Slice { prefix, suffix, .. } => {
1339                 // Number of subpatterns for the constructor
1340                 let ctor_arity = self.len();
1341
1342                 // Replace the prefix and the suffix with the given patterns, leaving wildcards in
1343                 // the middle if there was a subslice pattern `..`.
1344                 let prefix = prefix.iter().enumerate();
1345                 let suffix =
1346                     suffix.iter().enumerate().map(|(i, p)| (ctor_arity - suffix.len() + i, p));
1347                 self.replace_fields_indexed(prefix.chain(suffix))
1348             }
1349             _ => self.clone(),
1350         }
1351     }
1352
1353     fn push_on_patstack(self, stack: &[&'p Pat<'tcx>]) -> PatStack<'p, 'tcx> {
1354         let pats: SmallVec<_> = match self {
1355             Fields::Slice(pats) => pats.iter().chain(stack.iter().copied()).collect(),
1356             Fields::Vec(mut pats) => {
1357                 pats.extend_from_slice(stack);
1358                 pats
1359             }
1360             Fields::Filtered { fields, .. } => {
1361                 // We skip hidden fields here
1362                 fields.into_iter().filter_map(|p| p.kept()).chain(stack.iter().copied()).collect()
1363             }
1364         };
1365         PatStack::from_vec(pats)
1366     }
1367 }
1368
1369 #[derive(Clone, Debug)]
1370 crate enum Usefulness<'tcx> {
1371     /// Carries, for each column in the matrix, a set of sub-branches that have been found to be
1372     /// unreachable. Used only in the presence of or-patterns, otherwise it stays empty.
1373     Useful(Vec<FxHashSet<Span>>),
1374     /// Carries a list of witnesses of non-exhaustiveness.
1375     UsefulWithWitness(Vec<Witness<'tcx>>),
1376     NotUseful,
1377 }
1378
1379 impl<'tcx> Usefulness<'tcx> {
1380     fn new_useful(preference: WitnessPreference) -> Self {
1381         match preference {
1382             ConstructWitness => UsefulWithWitness(vec![Witness(vec![])]),
1383             LeaveOutWitness => Useful(vec![]),
1384         }
1385     }
1386
1387     fn is_useful(&self) -> bool {
1388         !matches!(*self, NotUseful)
1389     }
1390
1391     fn apply_constructor<'p>(
1392         self,
1393         pcx: PatCtxt<'_, 'p, 'tcx>,
1394         ctor: &Constructor<'tcx>,
1395         ctor_wild_subpatterns: &Fields<'p, 'tcx>,
1396     ) -> Self {
1397         match self {
1398             UsefulWithWitness(witnesses) => {
1399                 let new_witnesses = if ctor.is_wildcard() {
1400                     let missing_ctors = MissingConstructors::new(pcx);
1401                     let new_patterns = missing_ctors.report_patterns(pcx);
1402                     witnesses
1403                         .into_iter()
1404                         .flat_map(|witness| {
1405                             new_patterns.iter().map(move |pat| {
1406                                 let mut witness = witness.clone();
1407                                 witness.0.push(pat.clone());
1408                                 witness
1409                             })
1410                         })
1411                         .collect()
1412                 } else {
1413                     witnesses
1414                         .into_iter()
1415                         .map(|witness| witness.apply_constructor(pcx, &ctor, ctor_wild_subpatterns))
1416                         .collect()
1417                 };
1418                 UsefulWithWitness(new_witnesses)
1419             }
1420             Useful(mut unreachables) => {
1421                 if !unreachables.is_empty() {
1422                     // When we apply a constructor, there are `arity` columns of the matrix that
1423                     // corresponded to its arguments. All the unreachables found in these columns
1424                     // will, after `apply`, come from the first column. So we take the union of all
1425                     // the corresponding sets and put them in the first column.
1426                     // Note that `arity` may be 0, in which case we just push a new empty set.
1427                     let len = unreachables.len();
1428                     let arity = ctor_wild_subpatterns.len();
1429                     let mut unioned = FxHashSet::default();
1430                     for set in unreachables.drain((len - arity)..) {
1431                         unioned.extend(set)
1432                     }
1433                     unreachables.push(unioned);
1434                 }
1435                 Useful(unreachables)
1436             }
1437             x => x,
1438         }
1439     }
1440 }
1441
1442 #[derive(Copy, Clone, Debug)]
1443 enum WitnessPreference {
1444     ConstructWitness,
1445     LeaveOutWitness,
1446 }
1447
1448 #[derive(Copy, Clone)]
1449 struct PatCtxt<'a, 'p, 'tcx> {
1450     cx: &'a MatchCheckCtxt<'p, 'tcx>,
1451     /// Current state of the matrix.
1452     matrix: &'a Matrix<'p, 'tcx>,
1453     /// Type of the current column under investigation.
1454     ty: Ty<'tcx>,
1455     /// Span of the current pattern under investigation.
1456     span: Span,
1457     /// Whether the current pattern is the whole pattern as found in a match arm, or if it's a
1458     /// subpattern.
1459     is_top_level: bool,
1460 }
1461
1462 /// A witness of non-exhaustiveness for error reporting, represented
1463 /// as a list of patterns (in reverse order of construction) with
1464 /// wildcards inside to represent elements that can take any inhabitant
1465 /// of the type as a value.
1466 ///
1467 /// A witness against a list of patterns should have the same types
1468 /// and length as the pattern matched against. Because Rust `match`
1469 /// is always against a single pattern, at the end the witness will
1470 /// have length 1, but in the middle of the algorithm, it can contain
1471 /// multiple patterns.
1472 ///
1473 /// For example, if we are constructing a witness for the match against
1474 ///
1475 /// ```
1476 /// struct Pair(Option<(u32, u32)>, bool);
1477 ///
1478 /// match (p: Pair) {
1479 ///    Pair(None, _) => {}
1480 ///    Pair(_, false) => {}
1481 /// }
1482 /// ```
1483 ///
1484 /// We'll perform the following steps:
1485 /// 1. Start with an empty witness
1486 ///     `Witness(vec![])`
1487 /// 2. Push a witness `Some(_)` against the `None`
1488 ///     `Witness(vec![Some(_)])`
1489 /// 3. Push a witness `true` against the `false`
1490 ///     `Witness(vec![Some(_), true])`
1491 /// 4. Apply the `Pair` constructor to the witnesses
1492 ///     `Witness(vec![Pair(Some(_), true)])`
1493 ///
1494 /// The final `Pair(Some(_), true)` is then the resulting witness.
1495 #[derive(Clone, Debug)]
1496 crate struct Witness<'tcx>(Vec<Pat<'tcx>>);
1497
1498 impl<'tcx> Witness<'tcx> {
1499     /// Asserts that the witness contains a single pattern, and returns it.
1500     fn single_pattern(self) -> Pat<'tcx> {
1501         assert_eq!(self.0.len(), 1);
1502         self.0.into_iter().next().unwrap()
1503     }
1504
1505     /// Constructs a partial witness for a pattern given a list of
1506     /// patterns expanded by the specialization step.
1507     ///
1508     /// When a pattern P is discovered to be useful, this function is used bottom-up
1509     /// to reconstruct a complete witness, e.g., a pattern P' that covers a subset
1510     /// of values, V, where each value in that set is not covered by any previously
1511     /// used patterns and is covered by the pattern P'. Examples:
1512     ///
1513     /// left_ty: tuple of 3 elements
1514     /// pats: [10, 20, _]           => (10, 20, _)
1515     ///
1516     /// left_ty: struct X { a: (bool, &'static str), b: usize}
1517     /// pats: [(false, "foo"), 42]  => X { a: (false, "foo"), b: 42 }
1518     fn apply_constructor<'p>(
1519         mut self,
1520         pcx: PatCtxt<'_, 'p, 'tcx>,
1521         ctor: &Constructor<'tcx>,
1522         ctor_wild_subpatterns: &Fields<'p, 'tcx>,
1523     ) -> Self {
1524         let pat = {
1525             let len = self.0.len();
1526             let arity = ctor_wild_subpatterns.len();
1527             let pats = self.0.drain((len - arity)..).rev();
1528             let fields = ctor_wild_subpatterns.replace_fields(pcx.cx, pats);
1529             ctor.apply(pcx, fields)
1530         };
1531
1532         self.0.push(pat);
1533
1534         self
1535     }
1536 }
1537
1538 /// This determines the set of all possible constructors of a pattern matching
1539 /// values of type `left_ty`. For vectors, this would normally be an infinite set
1540 /// but is instead bounded by the maximum fixed length of slice patterns in
1541 /// the column of patterns being analyzed.
1542 ///
1543 /// We make sure to omit constructors that are statically impossible. E.g., for
1544 /// `Option<!>`, we do not include `Some(_)` in the returned list of constructors.
1545 /// Invariant: this returns an empty `Vec` if and only if the type is uninhabited (as determined by
1546 /// `cx.is_uninhabited()`).
1547 fn all_constructors<'p, 'tcx>(pcx: PatCtxt<'_, 'p, 'tcx>) -> Vec<Constructor<'tcx>> {
1548     debug!("all_constructors({:?})", pcx.ty);
1549     let cx = pcx.cx;
1550     let make_range = |start, end| {
1551         IntRange(
1552             // `unwrap()` is ok because we know the type is an integer.
1553             IntRange::from_range(cx.tcx, start, end, pcx.ty, &RangeEnd::Included, pcx.span)
1554                 .unwrap(),
1555         )
1556     };
1557     match pcx.ty.kind() {
1558         ty::Bool => vec![make_range(0, 1)],
1559         ty::Array(sub_ty, len) if len.try_eval_usize(cx.tcx, cx.param_env).is_some() => {
1560             let len = len.eval_usize(cx.tcx, cx.param_env);
1561             if len != 0 && cx.is_uninhabited(sub_ty) {
1562                 vec![]
1563             } else {
1564                 vec![Slice(Slice::new(Some(len), VarLen(0, 0)))]
1565             }
1566         }
1567         // Treat arrays of a constant but unknown length like slices.
1568         ty::Array(sub_ty, _) | ty::Slice(sub_ty) => {
1569             let kind = if cx.is_uninhabited(sub_ty) { FixedLen(0) } else { VarLen(0, 0) };
1570             vec![Slice(Slice::new(None, kind))]
1571         }
1572         ty::Adt(def, substs) if def.is_enum() => {
1573             // If the enum is declared as `#[non_exhaustive]`, we treat it as if it had an
1574             // additional "unknown" constructor.
1575             // There is no point in enumerating all possible variants, because the user can't
1576             // actually match against them all themselves. So we always return only the fictitious
1577             // constructor.
1578             // E.g., in an example like:
1579             //
1580             // ```
1581             //     let err: io::ErrorKind = ...;
1582             //     match err {
1583             //         io::ErrorKind::NotFound => {},
1584             //     }
1585             // ```
1586             //
1587             // we don't want to show every possible IO error, but instead have only `_` as the
1588             // witness.
1589             let is_declared_nonexhaustive = cx.is_foreign_non_exhaustive_enum(pcx.ty);
1590
1591             // If `exhaustive_patterns` is disabled and our scrutinee is an empty enum, we treat it
1592             // as though it had an "unknown" constructor to avoid exposing its emptiness. The
1593             // exception is if the pattern is at the top level, because we want empty matches to be
1594             // considered exhaustive.
1595             let is_secretly_empty = def.variants.is_empty()
1596                 && !cx.tcx.features().exhaustive_patterns
1597                 && !pcx.is_top_level;
1598
1599             if is_secretly_empty || is_declared_nonexhaustive {
1600                 vec![NonExhaustive]
1601             } else if cx.tcx.features().exhaustive_patterns {
1602                 // If `exhaustive_patterns` is enabled, we exclude variants known to be
1603                 // uninhabited.
1604                 def.variants
1605                     .iter()
1606                     .filter(|v| {
1607                         !v.uninhabited_from(cx.tcx, substs, def.adt_kind(), cx.param_env)
1608                             .contains(cx.tcx, cx.module)
1609                     })
1610                     .map(|v| Variant(v.def_id))
1611                     .collect()
1612             } else {
1613                 def.variants.iter().map(|v| Variant(v.def_id)).collect()
1614             }
1615         }
1616         ty::Char => {
1617             vec![
1618                 // The valid Unicode Scalar Value ranges.
1619                 make_range('\u{0000}' as u128, '\u{D7FF}' as u128),
1620                 make_range('\u{E000}' as u128, '\u{10FFFF}' as u128),
1621             ]
1622         }
1623         ty::Int(_) | ty::Uint(_)
1624             if pcx.ty.is_ptr_sized_integral()
1625                 && !cx.tcx.features().precise_pointer_size_matching =>
1626         {
1627             // `usize`/`isize` are not allowed to be matched exhaustively unless the
1628             // `precise_pointer_size_matching` feature is enabled. So we treat those types like
1629             // `#[non_exhaustive]` enums by returning a special unmatcheable constructor.
1630             vec![NonExhaustive]
1631         }
1632         &ty::Int(ity) => {
1633             let bits = Integer::from_attr(&cx.tcx, SignedInt(ity)).size().bits() as u128;
1634             let min = 1u128 << (bits - 1);
1635             let max = min - 1;
1636             vec![make_range(min, max)]
1637         }
1638         &ty::Uint(uty) => {
1639             let size = Integer::from_attr(&cx.tcx, UnsignedInt(uty)).size();
1640             let max = size.truncate(u128::MAX);
1641             vec![make_range(0, max)]
1642         }
1643         // If `exhaustive_patterns` is disabled and our scrutinee is the never type, we cannot
1644         // expose its emptiness. The exception is if the pattern is at the top level, because we
1645         // want empty matches to be considered exhaustive.
1646         ty::Never if !cx.tcx.features().exhaustive_patterns && !pcx.is_top_level => {
1647             vec![NonExhaustive]
1648         }
1649         ty::Never => vec![],
1650         _ if cx.is_uninhabited(pcx.ty) => vec![],
1651         ty::Adt(..) | ty::Tuple(..) | ty::Ref(..) => vec![Single],
1652         // This type is one for which we cannot list constructors, like `str` or `f64`.
1653         _ => vec![NonExhaustive],
1654     }
1655 }
1656
1657 /// An inclusive interval, used for precise integer exhaustiveness checking.
1658 /// `IntRange`s always store a contiguous range. This means that values are
1659 /// encoded such that `0` encodes the minimum value for the integer,
1660 /// regardless of the signedness.
1661 /// For example, the pattern `-128..=127i8` is encoded as `0..=255`.
1662 /// This makes comparisons and arithmetic on interval endpoints much more
1663 /// straightforward. See `signed_bias` for details.
1664 ///
1665 /// `IntRange` is never used to encode an empty range or a "range" that wraps
1666 /// around the (offset) space: i.e., `range.lo <= range.hi`.
1667 #[derive(Clone, Debug)]
1668 struct IntRange<'tcx> {
1669     range: RangeInclusive<u128>,
1670     ty: Ty<'tcx>,
1671     span: Span,
1672 }
1673
1674 impl<'tcx> IntRange<'tcx> {
1675     #[inline]
1676     fn is_integral(ty: Ty<'_>) -> bool {
1677         matches!(ty.kind(), ty::Char | ty::Int(_) | ty::Uint(_) | ty::Bool)
1678     }
1679
1680     fn is_singleton(&self) -> bool {
1681         self.range.start() == self.range.end()
1682     }
1683
1684     fn boundaries(&self) -> (u128, u128) {
1685         (*self.range.start(), *self.range.end())
1686     }
1687
1688     /// Don't treat `usize`/`isize` exhaustively unless the `precise_pointer_size_matching` feature
1689     /// is enabled.
1690     fn treat_exhaustively(&self, tcx: TyCtxt<'tcx>) -> bool {
1691         !self.ty.is_ptr_sized_integral() || tcx.features().precise_pointer_size_matching
1692     }
1693
1694     #[inline]
1695     fn integral_size_and_signed_bias(tcx: TyCtxt<'tcx>, ty: Ty<'_>) -> Option<(Size, u128)> {
1696         match *ty.kind() {
1697             ty::Bool => Some((Size::from_bytes(1), 0)),
1698             ty::Char => Some((Size::from_bytes(4), 0)),
1699             ty::Int(ity) => {
1700                 let size = Integer::from_attr(&tcx, SignedInt(ity)).size();
1701                 Some((size, 1u128 << (size.bits() as u128 - 1)))
1702             }
1703             ty::Uint(uty) => Some((Integer::from_attr(&tcx, UnsignedInt(uty)).size(), 0)),
1704             _ => None,
1705         }
1706     }
1707
1708     #[inline]
1709     fn from_const(
1710         tcx: TyCtxt<'tcx>,
1711         param_env: ty::ParamEnv<'tcx>,
1712         value: &Const<'tcx>,
1713         span: Span,
1714     ) -> Option<IntRange<'tcx>> {
1715         if let Some((target_size, bias)) = Self::integral_size_and_signed_bias(tcx, value.ty) {
1716             let ty = value.ty;
1717             let val = (|| {
1718                 if let ty::ConstKind::Value(ConstValue::Scalar(scalar)) = value.val {
1719                     // For this specific pattern we can skip a lot of effort and go
1720                     // straight to the result, after doing a bit of checking. (We
1721                     // could remove this branch and just fall through, which
1722                     // is more general but much slower.)
1723                     if let Ok(bits) = scalar.to_bits_or_ptr(target_size, &tcx) {
1724                         return Some(bits);
1725                     }
1726                 }
1727                 // This is a more general form of the previous case.
1728                 value.try_eval_bits(tcx, param_env, ty)
1729             })()?;
1730             let val = val ^ bias;
1731             Some(IntRange { range: val..=val, ty, span })
1732         } else {
1733             None
1734         }
1735     }
1736
1737     #[inline]
1738     fn from_range(
1739         tcx: TyCtxt<'tcx>,
1740         lo: u128,
1741         hi: u128,
1742         ty: Ty<'tcx>,
1743         end: &RangeEnd,
1744         span: Span,
1745     ) -> Option<IntRange<'tcx>> {
1746         if Self::is_integral(ty) {
1747             // Perform a shift if the underlying types are signed,
1748             // which makes the interval arithmetic simpler.
1749             let bias = IntRange::signed_bias(tcx, ty);
1750             let (lo, hi) = (lo ^ bias, hi ^ bias);
1751             let offset = (*end == RangeEnd::Excluded) as u128;
1752             if lo > hi || (lo == hi && *end == RangeEnd::Excluded) {
1753                 // This should have been caught earlier by E0030.
1754                 bug!("malformed range pattern: {}..={}", lo, (hi - offset));
1755             }
1756             Some(IntRange { range: lo..=(hi - offset), ty, span })
1757         } else {
1758             None
1759         }
1760     }
1761
1762     // The return value of `signed_bias` should be XORed with an endpoint to encode/decode it.
1763     fn signed_bias(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> u128 {
1764         match *ty.kind() {
1765             ty::Int(ity) => {
1766                 let bits = Integer::from_attr(&tcx, SignedInt(ity)).size().bits() as u128;
1767                 1u128 << (bits - 1)
1768             }
1769             _ => 0,
1770         }
1771     }
1772
1773     fn is_subrange(&self, other: &Self) -> bool {
1774         other.range.start() <= self.range.start() && self.range.end() <= other.range.end()
1775     }
1776
1777     fn intersection(&self, tcx: TyCtxt<'tcx>, other: &Self) -> Option<Self> {
1778         let ty = self.ty;
1779         let (lo, hi) = self.boundaries();
1780         let (other_lo, other_hi) = other.boundaries();
1781         if self.treat_exhaustively(tcx) {
1782             if lo <= other_hi && other_lo <= hi {
1783                 let span = other.span;
1784                 Some(IntRange { range: max(lo, other_lo)..=min(hi, other_hi), ty, span })
1785             } else {
1786                 None
1787             }
1788         } else {
1789             // If the range should not be treated exhaustively, fallback to checking for inclusion.
1790             if self.is_subrange(other) { Some(self.clone()) } else { None }
1791         }
1792     }
1793
1794     fn suspicious_intersection(&self, other: &Self) -> bool {
1795         // `false` in the following cases:
1796         // 1     ----      // 1  ----------   // 1 ----        // 1       ----
1797         // 2  ----------   // 2     ----      // 2       ----  // 2 ----
1798         //
1799         // The following are currently `false`, but could be `true` in the future (#64007):
1800         // 1 ---------       // 1     ---------
1801         // 2     ----------  // 2 ----------
1802         //
1803         // `true` in the following cases:
1804         // 1 -------          // 1       -------
1805         // 2       --------   // 2 -------
1806         let (lo, hi) = self.boundaries();
1807         let (other_lo, other_hi) = other.boundaries();
1808         lo == other_hi || hi == other_lo
1809     }
1810
1811     fn to_pat(&self, tcx: TyCtxt<'tcx>) -> Pat<'tcx> {
1812         let (lo, hi) = self.boundaries();
1813
1814         let bias = IntRange::signed_bias(tcx, self.ty);
1815         let (lo, hi) = (lo ^ bias, hi ^ bias);
1816
1817         let ty = ty::ParamEnv::empty().and(self.ty);
1818         let lo_const = ty::Const::from_bits(tcx, lo, ty);
1819         let hi_const = ty::Const::from_bits(tcx, hi, ty);
1820
1821         let kind = if lo == hi {
1822             PatKind::Constant { value: lo_const }
1823         } else {
1824             PatKind::Range(PatRange { lo: lo_const, hi: hi_const, end: RangeEnd::Included })
1825         };
1826
1827         // This is a brand new pattern, so we don't reuse `self.span`.
1828         Pat { ty: self.ty, span: DUMMY_SP, kind: Box::new(kind) }
1829     }
1830
1831     /// For exhaustive integer matching, some constructors are grouped within other constructors
1832     /// (namely integer typed values are grouped within ranges). However, when specialising these
1833     /// constructors, we want to be specialising for the underlying constructors (the integers), not
1834     /// the groups (the ranges). Thus we need to split the groups up. Splitting them up naïvely would
1835     /// mean creating a separate constructor for every single value in the range, which is clearly
1836     /// impractical. However, observe that for some ranges of integers, the specialisation will be
1837     /// identical across all values in that range (i.e., there are equivalence classes of ranges of
1838     /// constructors based on their `U(S(c, P), S(c, p))` outcome). These classes are grouped by
1839     /// the patterns that apply to them (in the matrix `P`). We can split the range whenever the
1840     /// patterns that apply to that range (specifically: the patterns that *intersect* with that range)
1841     /// change.
1842     /// Our solution, therefore, is to split the range constructor into subranges at every single point
1843     /// the group of intersecting patterns changes (using the method described below).
1844     /// And voilà! We're testing precisely those ranges that we need to, without any exhaustive matching
1845     /// on actual integers. The nice thing about this is that the number of subranges is linear in the
1846     /// number of rows in the matrix (i.e., the number of cases in the `match` statement), so we don't
1847     /// need to be worried about matching over gargantuan ranges.
1848     ///
1849     /// Essentially, given the first column of a matrix representing ranges, looking like the following:
1850     ///
1851     /// |------|  |----------| |-------|    ||
1852     ///    |-------| |-------|            |----| ||
1853     ///       |---------|
1854     ///
1855     /// We split the ranges up into equivalence classes so the ranges are no longer overlapping:
1856     ///
1857     /// |--|--|||-||||--||---|||-------|  |-|||| ||
1858     ///
1859     /// The logic for determining how to split the ranges is fairly straightforward: we calculate
1860     /// boundaries for each interval range, sort them, then create constructors for each new interval
1861     /// between every pair of boundary points. (This essentially sums up to performing the intuitive
1862     /// merging operation depicted above.)
1863     fn split<'p>(
1864         &self,
1865         pcx: PatCtxt<'_, 'p, 'tcx>,
1866         hir_id: Option<HirId>,
1867     ) -> SmallVec<[Constructor<'tcx>; 1]> {
1868         let ty = pcx.ty;
1869
1870         /// Represents a border between 2 integers. Because the intervals spanning borders
1871         /// must be able to cover every integer, we need to be able to represent
1872         /// 2^128 + 1 such borders.
1873         #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
1874         enum Border {
1875             JustBefore(u128),
1876             AfterMax,
1877         }
1878
1879         // A function for extracting the borders of an integer interval.
1880         fn range_borders(r: IntRange<'_>) -> impl Iterator<Item = Border> {
1881             let (lo, hi) = r.range.into_inner();
1882             let from = Border::JustBefore(lo);
1883             let to = match hi.checked_add(1) {
1884                 Some(m) => Border::JustBefore(m),
1885                 None => Border::AfterMax,
1886             };
1887             vec![from, to].into_iter()
1888         }
1889
1890         // Collect the span and range of all the intersecting ranges to lint on likely
1891         // incorrect range patterns. (#63987)
1892         let mut overlaps = vec![];
1893         let row_len = pcx.matrix.patterns.get(0).map(|r| r.len()).unwrap_or(0);
1894         // `borders` is the set of borders between equivalence classes: each equivalence
1895         // class lies between 2 borders.
1896         let row_borders = pcx
1897             .matrix
1898             .head_ctors(pcx.cx)
1899             .filter_map(|ctor| ctor.as_int_range())
1900             .filter_map(|range| {
1901                 let intersection = self.intersection(pcx.cx.tcx, &range);
1902                 let should_lint = self.suspicious_intersection(&range);
1903                 if let (Some(range), 1, true) = (&intersection, row_len, should_lint) {
1904                     // FIXME: for now, only check for overlapping ranges on simple range
1905                     // patterns. Otherwise with the current logic the following is detected
1906                     // as overlapping:
1907                     //   match (10u8, true) {
1908                     //    (0 ..= 125, false) => {}
1909                     //    (126 ..= 255, false) => {}
1910                     //    (0 ..= 255, true) => {}
1911                     //  }
1912                     overlaps.push(range.clone());
1913                 }
1914                 intersection
1915             })
1916             .flat_map(range_borders);
1917         let self_borders = range_borders(self.clone());
1918         let mut borders: Vec<_> = row_borders.chain(self_borders).collect();
1919         borders.sort_unstable();
1920
1921         self.lint_overlapping_patterns(pcx.cx.tcx, hir_id, ty, overlaps);
1922
1923         // We're going to iterate through every adjacent pair of borders, making sure that
1924         // each represents an interval of nonnegative length, and convert each such
1925         // interval into a constructor.
1926         borders
1927             .array_windows()
1928             .filter_map(|&pair| match pair {
1929                 [Border::JustBefore(n), Border::JustBefore(m)] => {
1930                     if n < m {
1931                         Some(n..=(m - 1))
1932                     } else {
1933                         None
1934                     }
1935                 }
1936                 [Border::JustBefore(n), Border::AfterMax] => Some(n..=u128::MAX),
1937                 [Border::AfterMax, _] => None,
1938             })
1939             .map(|range| IntRange { range, ty, span: pcx.span })
1940             .map(IntRange)
1941             .collect()
1942     }
1943
1944     fn lint_overlapping_patterns(
1945         &self,
1946         tcx: TyCtxt<'tcx>,
1947         hir_id: Option<HirId>,
1948         ty: Ty<'tcx>,
1949         overlaps: Vec<IntRange<'tcx>>,
1950     ) {
1951         if let (true, Some(hir_id)) = (!overlaps.is_empty(), hir_id) {
1952             tcx.struct_span_lint_hir(
1953                 lint::builtin::OVERLAPPING_PATTERNS,
1954                 hir_id,
1955                 self.span,
1956                 |lint| {
1957                     let mut err = lint.build("multiple patterns covering the same range");
1958                     err.span_label(self.span, "overlapping patterns");
1959                     for int_range in overlaps {
1960                         // Use the real type for user display of the ranges:
1961                         err.span_label(
1962                             int_range.span,
1963                             &format!(
1964                                 "this range overlaps on `{}`",
1965                                 IntRange { range: int_range.range, ty, span: DUMMY_SP }.to_pat(tcx),
1966                             ),
1967                         );
1968                     }
1969                     err.emit();
1970                 },
1971             );
1972         }
1973     }
1974
1975     /// See `Constructor::is_covered_by`
1976     fn is_covered_by<'p>(&self, pcx: PatCtxt<'_, 'p, 'tcx>, other: &Self) -> bool {
1977         if self.intersection(pcx.cx.tcx, other).is_some() {
1978             // Constructor splitting should ensure that all intersections we encounter are actually
1979             // inclusions.
1980             assert!(self.is_subrange(other));
1981             true
1982         } else {
1983             false
1984         }
1985     }
1986 }
1987
1988 /// Ignore spans when comparing, they don't carry semantic information as they are only for lints.
1989 impl<'tcx> std::cmp::PartialEq for IntRange<'tcx> {
1990     fn eq(&self, other: &Self) -> bool {
1991         self.range == other.range && self.ty == other.ty
1992     }
1993 }
1994
1995 // A struct to compute a set of constructors equivalent to `all_ctors \ used_ctors`.
1996 #[derive(Debug)]
1997 struct MissingConstructors<'tcx> {
1998     all_ctors: SmallVec<[Constructor<'tcx>; 1]>,
1999     used_ctors: Vec<Constructor<'tcx>>,
2000 }
2001
2002 impl<'tcx> MissingConstructors<'tcx> {
2003     fn new<'p>(pcx: PatCtxt<'_, 'p, 'tcx>) -> Self {
2004         let used_ctors: Vec<Constructor<'_>> =
2005             pcx.matrix.head_ctors(pcx.cx).cloned().filter(|c| !c.is_wildcard()).collect();
2006         // Since `all_ctors` never contains wildcards, this won't recurse further.
2007         let all_ctors =
2008             all_constructors(pcx).into_iter().flat_map(|ctor| ctor.split(pcx, None)).collect();
2009
2010         MissingConstructors { all_ctors, used_ctors }
2011     }
2012
2013     fn is_empty<'p>(&self, pcx: PatCtxt<'_, 'p, 'tcx>) -> bool {
2014         self.iter(pcx).next().is_none()
2015     }
2016
2017     /// Iterate over all_ctors \ used_ctors
2018     fn iter<'a, 'p>(
2019         &'a self,
2020         pcx: PatCtxt<'a, 'p, 'tcx>,
2021     ) -> impl Iterator<Item = &'a Constructor<'tcx>> + Captures<'p> {
2022         self.all_ctors.iter().filter(move |ctor| !ctor.is_covered_by_any(pcx, &self.used_ctors))
2023     }
2024
2025     /// List the patterns corresponding to the missing constructors. In some cases, instead of
2026     /// listing all constructors of a given type, we prefer to simply report a wildcard.
2027     fn report_patterns<'p>(&self, pcx: PatCtxt<'_, 'p, 'tcx>) -> SmallVec<[Pat<'tcx>; 1]> {
2028         // There are 2 ways we can report a witness here.
2029         // Commonly, we can report all the "free"
2030         // constructors as witnesses, e.g., if we have:
2031         //
2032         // ```
2033         //     enum Direction { N, S, E, W }
2034         //     let Direction::N = ...;
2035         // ```
2036         //
2037         // we can report 3 witnesses: `S`, `E`, and `W`.
2038         //
2039         // However, there is a case where we don't want
2040         // to do this and instead report a single `_` witness:
2041         // if the user didn't actually specify a constructor
2042         // in this arm, e.g., in
2043         //
2044         // ```
2045         //     let x: (Direction, Direction, bool) = ...;
2046         //     let (_, _, false) = x;
2047         // ```
2048         //
2049         // we don't want to show all 16 possible witnesses
2050         // `(<direction-1>, <direction-2>, true)` - we are
2051         // satisfied with `(_, _, true)`. In this case,
2052         // `used_ctors` is empty.
2053         // The exception is: if we are at the top-level, for example in an empty match, we
2054         // sometimes prefer reporting the list of constructors instead of just `_`.
2055         let report_when_all_missing = pcx.is_top_level && !IntRange::is_integral(pcx.ty);
2056         if self.used_ctors.is_empty() && !report_when_all_missing {
2057             // All constructors are unused. Report only a wildcard
2058             // rather than each individual constructor.
2059             smallvec![Pat::wildcard_from_ty(pcx.ty)]
2060         } else {
2061             // Construct for each missing constructor a "wild" version of this
2062             // constructor, that matches everything that can be built with
2063             // it. For example, if `ctor` is a `Constructor::Variant` for
2064             // `Option::Some`, we get the pattern `Some(_)`.
2065             self.iter(pcx)
2066                 .map(|missing_ctor| {
2067                     let fields = Fields::wildcards(pcx, &missing_ctor);
2068                     missing_ctor.apply(pcx, fields)
2069                 })
2070                 .collect()
2071         }
2072     }
2073 }
2074
2075 /// Algorithm from <http://moscova.inria.fr/~maranget/papers/warn/index.html>.
2076 /// The algorithm from the paper has been modified to correctly handle empty
2077 /// types. The changes are:
2078 ///   (0) We don't exit early if the pattern matrix has zero rows. We just
2079 ///       continue to recurse over columns.
2080 ///   (1) all_constructors will only return constructors that are statically
2081 ///       possible. E.g., it will only return `Ok` for `Result<T, !>`.
2082 ///
2083 /// This finds whether a (row) vector `v` of patterns is 'useful' in relation
2084 /// to a set of such vectors `m` - this is defined as there being a set of
2085 /// inputs that will match `v` but not any of the sets in `m`.
2086 ///
2087 /// All the patterns at each column of the `matrix ++ v` matrix must have the same type.
2088 ///
2089 /// This is used both for reachability checking (if a pattern isn't useful in
2090 /// relation to preceding patterns, it is not reachable) and exhaustiveness
2091 /// checking (if a wildcard pattern is useful in relation to a matrix, the
2092 /// matrix isn't exhaustive).
2093 ///
2094 /// `is_under_guard` is used to inform if the pattern has a guard. If it
2095 /// has one it must not be inserted into the matrix. This shouldn't be
2096 /// relied on for soundness.
2097 fn is_useful<'p, 'tcx>(
2098     cx: &MatchCheckCtxt<'p, 'tcx>,
2099     matrix: &Matrix<'p, 'tcx>,
2100     v: &PatStack<'p, 'tcx>,
2101     witness_preference: WitnessPreference,
2102     hir_id: HirId,
2103     is_under_guard: bool,
2104     is_top_level: bool,
2105 ) -> Usefulness<'tcx> {
2106     let Matrix { patterns: rows, .. } = matrix;
2107     debug!("is_useful({:#?}, {:#?})", matrix, v);
2108
2109     // The base case. We are pattern-matching on () and the return value is
2110     // based on whether our matrix has a row or not.
2111     // NOTE: This could potentially be optimized by checking rows.is_empty()
2112     // first and then, if v is non-empty, the return value is based on whether
2113     // the type of the tuple we're checking is inhabited or not.
2114     if v.is_empty() {
2115         return if rows.is_empty() {
2116             Usefulness::new_useful(witness_preference)
2117         } else {
2118             NotUseful
2119         };
2120     };
2121
2122     assert!(rows.iter().all(|r| r.len() == v.len()));
2123
2124     // If the first pattern is an or-pattern, expand it.
2125     if let Some(vs) = v.expand_or_pat() {
2126         // We expand the or pattern, trying each of its branches in turn and keeping careful track
2127         // of possible unreachable sub-branches.
2128         //
2129         // If two branches have detected some unreachable sub-branches, we need to be careful. If
2130         // they were detected in columns that are not the current one, we want to keep only the
2131         // sub-branches that were unreachable in _all_ branches. Eg. in the following, the last
2132         // `true` is unreachable in the second branch of the first or-pattern, but not otherwise.
2133         // Therefore we don't want to lint that it is unreachable.
2134         //
2135         // ```
2136         // match (true, true) {
2137         //     (true, true) => {}
2138         //     (false | true, false | true) => {}
2139         // }
2140         // ```
2141         // If however the sub-branches come from the current column, they come from the inside of
2142         // the current or-pattern, and we want to keep them all. Eg. in the following, we _do_ want
2143         // to lint that the last `false` is unreachable.
2144         // ```
2145         // match None {
2146         //     Some(false) => {}
2147         //     None | Some(true | false) => {}
2148         // }
2149         // ```
2150
2151         let mut matrix = matrix.clone();
2152         // We keep track of sub-branches separately depending on whether they come from this column
2153         // or from others.
2154         let mut unreachables_this_column: FxHashSet<Span> = FxHashSet::default();
2155         let mut unreachables_other_columns: Vec<FxHashSet<Span>> = Vec::default();
2156         // Whether at least one branch is reachable.
2157         let mut any_is_useful = false;
2158
2159         for v in vs {
2160             let res = is_useful(cx, &matrix, &v, witness_preference, hir_id, is_under_guard, false);
2161             match res {
2162                 Useful(unreachables) => {
2163                     if let Some((this_column, other_columns)) = unreachables.split_last() {
2164                         // We keep the union of unreachables found in the first column.
2165                         unreachables_this_column.extend(this_column);
2166                         // We keep the intersection of unreachables found in other columns.
2167                         if unreachables_other_columns.is_empty() {
2168                             unreachables_other_columns = other_columns.to_vec();
2169                         } else {
2170                             unreachables_other_columns = unreachables_other_columns
2171                                 .into_iter()
2172                                 .zip(other_columns)
2173                                 .map(|(x, y)| x.intersection(&y).copied().collect())
2174                                 .collect();
2175                         }
2176                     }
2177                     any_is_useful = true;
2178                 }
2179                 NotUseful => {
2180                     unreachables_this_column.insert(v.head().span);
2181                 }
2182                 UsefulWithWitness(_) => bug!(
2183                     "encountered or-pat in the expansion of `_` during exhaustiveness checking"
2184                 ),
2185             }
2186
2187             // If pattern has a guard don't add it to the matrix.
2188             if !is_under_guard {
2189                 // We push the already-seen patterns into the matrix in order to detect redundant
2190                 // branches like `Some(_) | Some(0)`.
2191                 matrix.push(v);
2192             }
2193         }
2194
2195         return if any_is_useful {
2196             let mut unreachables = if unreachables_other_columns.is_empty() {
2197                 let n_columns = v.len();
2198                 (0..n_columns - 1).map(|_| FxHashSet::default()).collect()
2199             } else {
2200                 unreachables_other_columns
2201             };
2202             unreachables.push(unreachables_this_column);
2203             Useful(unreachables)
2204         } else {
2205             NotUseful
2206         };
2207     }
2208
2209     // FIXME(Nadrieril): Hack to work around type normalization issues (see #72476).
2210     let ty = matrix.heads().next().map(|r| r.ty).unwrap_or(v.head().ty);
2211     let pcx = PatCtxt { cx, matrix, ty, span: v.head().span, is_top_level };
2212
2213     debug!("is_useful_expand_first_col: ty={:#?}, expanding {:#?}", pcx.ty, v.head());
2214
2215     let ret = v
2216         .head_ctor(cx)
2217         .split(pcx, Some(hir_id))
2218         .into_iter()
2219         .map(|ctor| {
2220             // We cache the result of `Fields::wildcards` because it is used a lot.
2221             let ctor_wild_subpatterns = Fields::wildcards(pcx, &ctor);
2222             let matrix = pcx.matrix.specialize_constructor(pcx, &ctor, &ctor_wild_subpatterns);
2223             let v = v.pop_head_constructor(&ctor_wild_subpatterns);
2224             let usefulness =
2225                 is_useful(pcx.cx, &matrix, &v, witness_preference, hir_id, is_under_guard, false);
2226             usefulness.apply_constructor(pcx, &ctor, &ctor_wild_subpatterns)
2227         })
2228         .find(|result| result.is_useful())
2229         .unwrap_or(NotUseful);
2230     debug!("is_useful::returns({:#?}, {:#?}) = {:?}", matrix, v, ret);
2231     ret
2232 }
2233
2234 /// Determines the constructor that the given pattern can be specialized to.
2235 /// Returns `None` in case of a catch-all, which can't be specialized.
2236 fn pat_constructor<'p, 'tcx>(
2237     cx: &MatchCheckCtxt<'p, 'tcx>,
2238     pat: &'p Pat<'tcx>,
2239 ) -> Constructor<'tcx> {
2240     match pat.kind.as_ref() {
2241         PatKind::AscribeUserType { .. } => bug!(), // Handled by `expand_pattern`
2242         PatKind::Binding { .. } | PatKind::Wild => Wildcard,
2243         PatKind::Leaf { .. } | PatKind::Deref { .. } => Single,
2244         &PatKind::Variant { adt_def, variant_index, .. } => {
2245             Variant(adt_def.variants[variant_index].def_id)
2246         }
2247         PatKind::Constant { value } => {
2248             if let Some(int_range) = IntRange::from_const(cx.tcx, cx.param_env, value, pat.span) {
2249                 IntRange(int_range)
2250             } else {
2251                 match pat.ty.kind() {
2252                     ty::Float(_) => FloatRange(value, value, RangeEnd::Included),
2253                     // In `expand_pattern`, we convert string literals to `&CONST` patterns with
2254                     // `CONST` a pattern of type `str`. In truth this contains a constant of type
2255                     // `&str`.
2256                     ty::Str => Str(value),
2257                     // All constants that can be structurally matched have already been expanded
2258                     // into the corresponding `Pat`s by `const_to_pat`. Constants that remain are
2259                     // opaque.
2260                     _ => Opaque,
2261                 }
2262             }
2263         }
2264         &PatKind::Range(PatRange { lo, hi, end }) => {
2265             let ty = lo.ty;
2266             if let Some(int_range) = IntRange::from_range(
2267                 cx.tcx,
2268                 lo.eval_bits(cx.tcx, cx.param_env, lo.ty),
2269                 hi.eval_bits(cx.tcx, cx.param_env, hi.ty),
2270                 ty,
2271                 &end,
2272                 pat.span,
2273             ) {
2274                 IntRange(int_range)
2275             } else {
2276                 FloatRange(lo, hi, end)
2277             }
2278         }
2279         PatKind::Array { prefix, slice, suffix } | PatKind::Slice { prefix, slice, suffix } => {
2280             let array_len = match pat.ty.kind() {
2281                 ty::Array(_, length) => Some(length.eval_usize(cx.tcx, cx.param_env)),
2282                 ty::Slice(_) => None,
2283                 _ => span_bug!(pat.span, "bad ty {:?} for slice pattern", pat.ty),
2284             };
2285             let prefix = prefix.len() as u64;
2286             let suffix = suffix.len() as u64;
2287             let kind =
2288                 if slice.is_some() { VarLen(prefix, suffix) } else { FixedLen(prefix + suffix) };
2289             Slice(Slice::new(array_len, kind))
2290         }
2291         PatKind::Or { .. } => bug!("Or-pattern should have been expanded earlier on."),
2292     }
2293 }
2294
2295 /// The arm of a match expression.
2296 #[derive(Clone, Copy)]
2297 crate struct MatchArm<'p, 'tcx> {
2298     /// The pattern must have been lowered through `MatchVisitor::lower_pattern`.
2299     crate pat: &'p super::Pat<'tcx>,
2300     crate hir_id: HirId,
2301     crate has_guard: bool,
2302 }
2303
2304 /// The output of checking a match for exhaustiveness and arm reachability.
2305 crate struct UsefulnessReport<'p, 'tcx> {
2306     /// For each arm of the input, whether that arm is reachable after the arms above it.
2307     crate arm_usefulness: Vec<(MatchArm<'p, 'tcx>, Usefulness<'tcx>)>,
2308     /// If the match is exhaustive, this is empty. If not, this contains witnesses for the lack of
2309     /// exhaustiveness.
2310     crate non_exhaustiveness_witnesses: Vec<super::Pat<'tcx>>,
2311 }
2312
2313 /// The entrypoint for the usefulness algorithm. Computes whether a match is exhaustive and which
2314 /// of its arms are reachable.
2315 ///
2316 /// Note: the input patterns must have been lowered through `MatchVisitor::lower_pattern`.
2317 crate fn compute_match_usefulness<'p, 'tcx>(
2318     cx: &MatchCheckCtxt<'p, 'tcx>,
2319     arms: &[MatchArm<'p, 'tcx>],
2320     scrut_hir_id: HirId,
2321     scrut_ty: Ty<'tcx>,
2322 ) -> UsefulnessReport<'p, 'tcx> {
2323     let mut matrix = Matrix::empty();
2324     let arm_usefulness: Vec<_> = arms
2325         .iter()
2326         .copied()
2327         .map(|arm| {
2328             let v = PatStack::from_pattern(arm.pat);
2329             let usefulness =
2330                 is_useful(cx, &matrix, &v, LeaveOutWitness, arm.hir_id, arm.has_guard, true);
2331             if !arm.has_guard {
2332                 matrix.push(v);
2333             }
2334             (arm, usefulness)
2335         })
2336         .collect();
2337
2338     let wild_pattern = cx.pattern_arena.alloc(super::Pat::wildcard_from_ty(scrut_ty));
2339     let v = PatStack::from_pattern(wild_pattern);
2340     let usefulness = is_useful(cx, &matrix, &v, ConstructWitness, scrut_hir_id, false, true);
2341     let non_exhaustiveness_witnesses = match usefulness {
2342         NotUseful => vec![], // Wildcard pattern isn't useful, so the match is exhaustive.
2343         UsefulWithWitness(pats) => {
2344             if pats.is_empty() {
2345                 bug!("Exhaustiveness check returned no witnesses")
2346             } else {
2347                 pats.into_iter().map(|w| w.single_pattern()).collect()
2348             }
2349         }
2350         Useful(_) => bug!(),
2351     };
2352     UsefulnessReport { arm_usefulness, non_exhaustiveness_witnesses }
2353 }