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