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