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