]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/hair/pattern/_match.rs
39cc9e049f424bb3e3527af855e864a07c5047ae
[rust.git] / src / librustc_mir / hair / pattern / _match.rs
1 // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 /// This file includes the logic for exhaustiveness and usefulness checking for
12 /// pattern-matching. Specifically, given a list of patterns for a type, we can
13 /// tell whether:
14 /// (a) the patterns cover every possible constructor for the type [exhaustiveness]
15 /// (b) each pattern is necessary [usefulness]
16 ///
17 /// The algorithm implemented here is a modified version of the one described in:
18 /// http://moscova.inria.fr/~maranget/papers/warn/index.html
19 /// However, to save future implementors from reading the original paper, I'm going
20 /// to summarise the algorithm here to hopefully save time and be a little clearer
21 /// (without being so rigorous).
22 ///
23 /// The core of the algorithm revolves about a "usefulness" check. In particular, we
24 /// are trying to compute a predicate `U(P, p_{m + 1})` where `P` is a list of patterns
25 /// of length `m` for a compound (product) type with `n` components (we refer to this as
26 /// a matrix). `U(P, p_{m + 1})` represents whether, given an existing list of patterns
27 /// `p_1 ..= p_m`, adding a new pattern will be "useful" (that is, cover previously-
28 /// uncovered values of the type).
29 ///
30 /// If we have this predicate, then we can easily compute both exhaustiveness of an
31 /// entire set of patterns and the individual usefulness of each one.
32 /// (a) the set of patterns is exhaustive iff `U(P, _)` is false (i.e. adding a wildcard
33 /// match doesn't increase the number of values we're matching)
34 /// (b) a pattern `p_i` is not useful if `U(P[0..=(i-1), p_i)` is false (i.e. adding a
35 /// pattern to those that have come before it doesn't increase the number of values
36 /// we're matching).
37 ///
38 /// For example, say we have the following:
39 /// ```
40 ///     // x: (Option<bool>, Result<()>)
41 ///     match x {
42 ///         (Some(true), _) => {}
43 ///         (None, Err(())) => {}
44 ///         (None, Err(_)) => {}
45 ///     }
46 /// ```
47 /// Here, the matrix `P` is 3 x 2 (rows x columns).
48 /// [
49 ///     [Some(true), _],
50 ///     [None, Err(())],
51 ///     [None, Err(_)],
52 /// ]
53 /// We can tell it's not exhaustive, because `U(P, _)` is true (we're not covering
54 /// `[Some(false), _]`, for instance). In addition, row 3 is not useful, because
55 /// all the values it covers are already covered by row 2.
56 ///
57 /// To compute `U`, we must have two other concepts.
58 ///     1. `S(c, P)` is a "specialised matrix", where `c` is a constructor (like `Some` or
59 ///        `None`). You can think of it as filtering `P` to just the rows whose *first* pattern
60 ///        can cover `c` (and expanding OR-patterns into distinct patterns), and then expanding
61 ///        the constructor into all of its components.
62 ///        The specialisation of a row vector is computed by `specialize`.
63 ///
64 ///        It is computed as follows. For each row `p_i` of P, we have four cases:
65 ///             1.1. `p_(i,1) = c(r_1, .., r_a)`. Then `S(c, P)` has a corresponding row:
66 ///                     r_1, .., r_a, p_(i,2), .., p_(i,n)
67 ///             1.2. `p_(i,1) = c'(r_1, .., r_a')` where `c ≠ c'`. Then `S(c, P)` has no
68 ///                  corresponding row.
69 ///             1.3. `p_(i,1) = _`. Then `S(c, P)` has a corresponding row:
70 ///                     _, .., _, p_(i,2), .., p_(i,n)
71 ///             1.4. `p_(i,1) = r_1 | r_2`. Then `S(c, P)` has corresponding rows inlined from:
72 ///                     S(c, (r_1, p_(i,2), .., p_(i,n)))
73 ///                     S(c, (r_2, p_(i,2), .., p_(i,n)))
74 ///
75 ///     2. `D(P)` is a "default matrix". This is used when we know there are missing
76 ///        constructor cases, but there might be existing wildcard patterns, so to check the
77 ///        usefulness of the matrix, we have to check all its *other* components.
78 ///        The default matrix is computed inline in `is_useful`.
79 ///
80 ///         It is computed as follows. For each row `p_i` of P, we have three cases:
81 ///             1.1. `p_(i,1) = c(r_1, .., r_a)`. Then `D(P)` has no corresponding row.
82 ///             1.2. `p_(i,1) = _`. Then `D(P)` has a corresponding row:
83 ///                     p_(i,2), .., p_(i,n)
84 ///             1.3. `p_(i,1) = r_1 | r_2`. Then `D(P)` has corresponding rows inlined from:
85 ///                     D((r_1, p_(i,2), .., p_(i,n)))
86 ///                     D((r_2, p_(i,2), .., p_(i,n)))
87 ///
88 ///     Note that the OR-patterns are not always used directly in Rust, but are used to derive
89 ///     the exhaustive integer matching rules, so they're written here for posterity.
90 ///
91 /// The algorithm for computing `U`
92 /// -------------------------------
93 /// The algorithm is inductive (on the number of columns: i.e. components of tuple patterns).
94 /// That means we're going to check the components from left-to-right, so the algorithm
95 /// operates principally on the first component of the matrix and new pattern `p_{m + 1}`.
96 /// This algorithm is realised in the `is_useful` function.
97 ///
98 /// Base case. (`n = 0`, i.e. an empty tuple pattern)
99 ///     - If `P` already contains an empty pattern (i.e. if the number of patterns `m > 0`),
100 ///       then `U(P, p_{m + 1})` is false.
101 ///     - Otherwise, `P` must be empty, so `U(P, p_{m + 1})` is true.
102 ///
103 /// Inductive step. (`n > 0`, i.e. whether there's at least one column
104 ///                  [which may then be expanded into further columns later])
105 ///     We're going to match on the new pattern, `p_{m + 1}`.
106 ///         - If `p_{m + 1} == c(r_1, .., r_a)`, then we have a constructor pattern.
107 ///           Thus, the usefulness of `p_{m + 1}` can be reduced to whether it is useful when
108 ///           we ignore all the patterns in `P` that involve other constructors. This is where
109 ///           `S(c, P)` comes in:
110 ///           `U(P, p_{m + 1}) := U(S(c, P), S(c, p_{m + 1}))`
111 ///           This special case is handled in `is_useful_specialized`.
112 ///         - If `p_{m + 1} == _`, then we have two more cases:
113 ///             + All the constructors of the first component of the type exist within
114 ///               all the rows (after having expanded OR-patterns). In this case:
115 ///               `U(P, p_{m + 1}) := ∨(k ϵ constructors) U(S(k, P), S(k, p_{m + 1}))`
116 ///               I.e. the pattern `p_{m + 1}` is only useful when all the constructors are
117 ///               present *if* its later components are useful for the respective constructors
118 ///               covered by `p_{m + 1}` (usually a single constructor, but all in the case of `_`).
119 ///             + Some constructors are not present in the existing rows (after having expanded
120 ///               OR-patterns). However, there might be wildcard patterns (`_`) present. Thus, we
121 ///               are only really concerned with the other patterns leading with wildcards. This is
122 ///               where `D` comes in:
123 ///               `U(P, p_{m + 1}) := U(D(P), p_({m + 1},2), ..,  p_({m + 1},n))`
124 ///         - If `p_{m + 1} == r_1 | r_2`, then the usefulness depends on each separately:
125 ///           `U(P, p_{m + 1}) := U(P, (r_1, p_({m + 1},2), .., p_({m + 1},n)))
126 ///                            || U(P, (r_2, p_({m + 1},2), .., p_({m + 1},n)))`
127 ///
128 /// Modifications to the algorithm
129 /// ------------------------------
130 /// The algorithm in the paper doesn't cover some of the special cases that arise in Rust, for
131 /// example uninhabited types and variable-length slice patterns. These are drawn attention to
132 /// throughout the code below. I'll make a quick note here about how exhaustive integer matching
133 /// is accounted for, though.
134 ///
135 /// Exhaustive integer matching
136 /// ---------------------------
137 /// An integer type can be thought of as a (huge) sum type: 1 | 2 | 3 | ...
138 /// So to support exhaustive integer matching, we can make use of the logic in the paper for
139 /// OR-patterns. However, we obviously can't just treat ranges x..=y as individual sums, because
140 /// they are likely gigantic. So we instead treat ranges as constructors of the integers. This means
141 /// that we have a constructor *of* constructors (the integers themselves). We then need to work
142 /// through all the inductive step rules above, deriving how the ranges would be treated as
143 /// OR-patterns, and making sure that they're treated in the same way even when they're ranges.
144 /// There are really only four special cases here:
145 /// - When we match on a constructor that's actually a range, we have to treat it as if we would
146 ///   an OR-pattern.
147 ///     + It turns out that we can simply extend the case for single-value patterns in
148 ///      `specialize` to either be *equal* to a value constructor, or *contained within* a range
149 ///      constructor.
150 ///     + When the pattern itself is a range, you just want to tell whether any of the values in
151 ///       the pattern range coincide with values in the constructor range, which is precisely
152 ///       intersection.
153 ///   Since when encountering a range pattern for a value constructor, we also use inclusion, it
154 ///   means that whenever the constructor is a value/range and the pattern is also a value/range,
155 ///   we can simply use intersection to test usefulness.
156 /// - When we're testing for usefulness of a pattern and the pattern's first component is a
157 ///   wildcard.
158 ///     + If all the constructors appear in the matrix, we have a slight complication. By default,
159 ///       the behaviour (i.e. a disjunction over specialised matrices for each constructor) is
160 ///       invalid, because we want a disjunction over every *integer* in each range, not just a
161 ///       disjunction over every range. This is a bit more tricky to deal with: essentially we need
162 ///       to form equivalence classes of subranges of the constructor range for which the behaviour
163 ///       of the matrix `P` and new pattern `p_{m + 1}` are the same. This is described in more
164 ///       detail in `split_grouped_constructors`.
165 ///     + If some constructors are missing from the matrix, it turns out we don't need to do
166 ///       anything special (because we know none of the integers are actually wildcards: i.e. we
167 ///       can't span wildcards using ranges).
168
169 use self::Constructor::*;
170 use self::Usefulness::*;
171 use self::WitnessPreference::*;
172
173 use rustc_data_structures::fx::FxHashMap;
174 use rustc_data_structures::indexed_vec::Idx;
175
176 use super::{FieldPattern, Pattern, PatternKind};
177 use super::{PatternFoldable, PatternFolder, compare_const_vals};
178
179 use rustc::hir::def_id::DefId;
180 use rustc::hir::RangeEnd;
181 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
182 use rustc::ty::layout::{Integer, IntegerExt};
183
184 use rustc::mir::Field;
185 use rustc::mir::interpret::ConstValue;
186 use rustc::util::common::ErrorReported;
187
188 use syntax::attr::{SignedInt, UnsignedInt};
189 use syntax_pos::{Span, DUMMY_SP};
190
191 use arena::TypedArena;
192
193 use std::cmp::{self, Ordering, min, max};
194 use std::fmt;
195 use std::iter::{FromIterator, IntoIterator};
196 use std::ops::RangeInclusive;
197
198 pub fn expand_pattern<'a, 'tcx>(cx: &MatchCheckCtxt<'a, 'tcx>, pat: Pattern<'tcx>)
199                                 -> &'a Pattern<'tcx>
200 {
201     cx.pattern_arena.alloc(LiteralExpander.fold_pattern(&pat))
202 }
203
204 struct LiteralExpander;
205 impl<'tcx> PatternFolder<'tcx> for LiteralExpander {
206     fn fold_pattern(&mut self, pat: &Pattern<'tcx>) -> Pattern<'tcx> {
207         match (&pat.ty.sty, &*pat.kind) {
208             (&ty::TyRef(_, rty, _), &PatternKind::Constant { ref value }) => {
209                 Pattern {
210                     ty: pat.ty,
211                     span: pat.span,
212                     kind: box PatternKind::Deref {
213                         subpattern: Pattern {
214                             ty: rty,
215                             span: pat.span,
216                             kind: box PatternKind::Constant { value: value.clone() },
217                         }
218                     }
219                 }
220             }
221             (_, &PatternKind::Binding { subpattern: Some(ref s), .. }) => {
222                 s.fold_with(self)
223             }
224             _ => pat.super_fold_with(self)
225         }
226     }
227 }
228
229 impl<'tcx> Pattern<'tcx> {
230     fn is_wildcard(&self) -> bool {
231         match *self.kind {
232             PatternKind::Binding { subpattern: None, .. } | PatternKind::Wild =>
233                 true,
234             _ => false
235         }
236     }
237 }
238
239 pub struct Matrix<'a, 'tcx: 'a>(Vec<Vec<&'a Pattern<'tcx>>>);
240
241 impl<'a, 'tcx> Matrix<'a, 'tcx> {
242     pub fn empty() -> Self {
243         Matrix(vec![])
244     }
245
246     pub fn push(&mut self, row: Vec<&'a Pattern<'tcx>>) {
247         self.0.push(row)
248     }
249 }
250
251 /// Pretty-printer for matrices of patterns, example:
252 /// ++++++++++++++++++++++++++
253 /// + _     + []             +
254 /// ++++++++++++++++++++++++++
255 /// + true  + [First]        +
256 /// ++++++++++++++++++++++++++
257 /// + true  + [Second(true)] +
258 /// ++++++++++++++++++++++++++
259 /// + false + [_]            +
260 /// ++++++++++++++++++++++++++
261 /// + _     + [_, _, ..tail] +
262 /// ++++++++++++++++++++++++++
263 impl<'a, 'tcx> fmt::Debug for Matrix<'a, 'tcx> {
264     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
265         write!(f, "\n")?;
266
267         let &Matrix(ref m) = self;
268         let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| {
269             row.iter().map(|pat| format!("{:?}", pat)).collect()
270         }).collect();
271
272         let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0);
273         assert!(m.iter().all(|row| row.len() == column_count));
274         let column_widths: Vec<usize> = (0..column_count).map(|col| {
275             pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0)
276         }).collect();
277
278         let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1;
279         let br = "+".repeat(total_width);
280         write!(f, "{}\n", br)?;
281         for row in pretty_printed_matrix {
282             write!(f, "+")?;
283             for (column, pat_str) in row.into_iter().enumerate() {
284                 write!(f, " ")?;
285                 write!(f, "{:1$}", pat_str, column_widths[column])?;
286                 write!(f, " +")?;
287             }
288             write!(f, "\n")?;
289             write!(f, "{}\n", br)?;
290         }
291         Ok(())
292     }
293 }
294
295 impl<'a, 'tcx> FromIterator<Vec<&'a Pattern<'tcx>>> for Matrix<'a, 'tcx> {
296     fn from_iter<T: IntoIterator<Item=Vec<&'a Pattern<'tcx>>>>(iter: T) -> Self
297     {
298         Matrix(iter.into_iter().collect())
299     }
300 }
301
302 pub struct MatchCheckCtxt<'a, 'tcx: 'a> {
303     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
304     /// The module in which the match occurs. This is necessary for
305     /// checking inhabited-ness of types because whether a type is (visibly)
306     /// inhabited can depend on whether it was defined in the current module or
307     /// not. eg. `struct Foo { _private: ! }` cannot be seen to be empty
308     /// outside it's module and should not be matchable with an empty match
309     /// statement.
310     pub module: DefId,
311     pub pattern_arena: &'a TypedArena<Pattern<'tcx>>,
312     pub byte_array_map: FxHashMap<*const Pattern<'tcx>, Vec<&'a Pattern<'tcx>>>,
313 }
314
315 impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> {
316     pub fn create_and_enter<F, R>(
317         tcx: TyCtxt<'a, 'tcx, 'tcx>,
318         module: DefId,
319         f: F) -> R
320         where F: for<'b> FnOnce(MatchCheckCtxt<'b, 'tcx>) -> R
321     {
322         let pattern_arena = TypedArena::new();
323
324         f(MatchCheckCtxt {
325             tcx,
326             module,
327             pattern_arena: &pattern_arena,
328             byte_array_map: FxHashMap::default(),
329         })
330     }
331
332     // convert a byte-string pattern to a list of u8 patterns.
333     fn lower_byte_str_pattern<'p>(&mut self, pat: &'p Pattern<'tcx>) -> Vec<&'p Pattern<'tcx>>
334             where 'a: 'p
335     {
336         let pattern_arena = &*self.pattern_arena;
337         let tcx = self.tcx;
338         self.byte_array_map.entry(pat).or_insert_with(|| {
339             match pat.kind {
340                 box PatternKind::Constant {
341                     value: const_val
342                 } => {
343                     if let Some(ptr) = const_val.to_ptr() {
344                         let is_array_ptr = const_val.ty
345                             .builtin_deref(true)
346                             .and_then(|t| t.ty.builtin_index())
347                             .map_or(false, |t| t == tcx.types.u8);
348                         assert!(is_array_ptr);
349                         let alloc = tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
350                         assert_eq!(ptr.offset.bytes(), 0);
351                         // FIXME: check length
352                         alloc.bytes.iter().map(|b| {
353                             &*pattern_arena.alloc(Pattern {
354                                 ty: tcx.types.u8,
355                                 span: pat.span,
356                                 kind: box PatternKind::Constant {
357                                     value: ty::Const::from_bits(
358                                         tcx,
359                                         *b as u128,
360                                         ty::ParamEnv::empty().and(tcx.types.u8))
361                                 }
362                             })
363                         }).collect()
364                     } else {
365                         bug!("not a byte str: {:?}", const_val)
366                     }
367                 }
368                 _ => span_bug!(pat.span, "unexpected byte array pattern {:?}", pat)
369             }
370         }).clone()
371     }
372
373     fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool {
374         if self.tcx.features().exhaustive_patterns {
375             self.tcx.is_ty_uninhabited_from(self.module, ty)
376         } else {
377             false
378         }
379     }
380
381     fn is_non_exhaustive_enum(&self, ty: Ty<'tcx>) -> bool {
382         match ty.sty {
383             ty::TyAdt(adt_def, ..) => adt_def.is_enum() && adt_def.is_non_exhaustive(),
384             _ => false,
385         }
386     }
387
388     fn is_local(&self, ty: Ty<'tcx>) -> bool {
389         match ty.sty {
390             ty::TyAdt(adt_def, ..) => adt_def.did.is_local(),
391             _ => false,
392         }
393     }
394
395     fn is_variant_uninhabited(&self,
396                               variant: &'tcx ty::VariantDef,
397                               substs: &'tcx ty::subst::Substs<'tcx>)
398                               -> bool
399     {
400         if self.tcx.features().exhaustive_patterns {
401             self.tcx.is_enum_variant_uninhabited_from(self.module, variant, substs)
402         } else {
403             false
404         }
405     }
406 }
407
408 #[derive(Clone, Debug, PartialEq)]
409 pub enum Constructor<'tcx> {
410     /// The constructor of all patterns that don't vary by constructor,
411     /// e.g. struct patterns and fixed-length arrays.
412     Single,
413     /// Enum variants.
414     Variant(DefId),
415     /// Literal values.
416     ConstantValue(&'tcx ty::Const<'tcx>),
417     /// Ranges of literal values (`2...5` and `2..5`).
418     ConstantRange(&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>, RangeEnd),
419     /// Array patterns of length n.
420     Slice(u64),
421 }
422
423 impl<'tcx> Constructor<'tcx> {
424     fn variant_index_for_adt(&self, adt: &'tcx ty::AdtDef) -> usize {
425         match self {
426             &Variant(vid) => adt.variant_index_with_id(vid),
427             &Single => {
428                 assert!(!adt.is_enum());
429                 0
430             }
431             _ => bug!("bad constructor {:?} for adt {:?}", self, adt)
432         }
433     }
434 }
435
436 #[derive(Clone, Debug)]
437 pub enum Usefulness<'tcx> {
438     Useful,
439     UsefulWithWitness(Vec<Witness<'tcx>>),
440     NotUseful
441 }
442
443 impl<'tcx> Usefulness<'tcx> {
444     fn is_useful(&self) -> bool {
445         match *self {
446             NotUseful => false,
447             _ => true
448         }
449     }
450 }
451
452 #[derive(Copy, Clone, Debug)]
453 pub enum WitnessPreference {
454     ConstructWitness,
455     LeaveOutWitness
456 }
457
458 #[derive(Copy, Clone, Debug)]
459 struct PatternContext<'tcx> {
460     ty: Ty<'tcx>,
461     max_slice_length: u64,
462 }
463
464 /// A witness of non-exhaustiveness for error reporting, represented
465 /// as a list of patterns (in reverse order of construction) with
466 /// wildcards inside to represent elements that can take any inhabitant
467 /// of the type as a value.
468 ///
469 /// A witness against a list of patterns should have the same types
470 /// and length as the pattern matched against. Because Rust `match`
471 /// is always against a single pattern, at the end the witness will
472 /// have length 1, but in the middle of the algorithm, it can contain
473 /// multiple patterns.
474 ///
475 /// For example, if we are constructing a witness for the match against
476 /// ```
477 /// struct Pair(Option<(u32, u32)>, bool);
478 ///
479 /// match (p: Pair) {
480 ///    Pair(None, _) => {}
481 ///    Pair(_, false) => {}
482 /// }
483 /// ```
484 ///
485 /// We'll perform the following steps:
486 /// 1. Start with an empty witness
487 ///     `Witness(vec![])`
488 /// 2. Push a witness `Some(_)` against the `None`
489 ///     `Witness(vec![Some(_)])`
490 /// 3. Push a witness `true` against the `false`
491 ///     `Witness(vec![Some(_), true])`
492 /// 4. Apply the `Pair` constructor to the witnesses
493 ///     `Witness(vec![Pair(Some(_), true)])`
494 ///
495 /// The final `Pair(Some(_), true)` is then the resulting witness.
496 #[derive(Clone, Debug)]
497 pub struct Witness<'tcx>(Vec<Pattern<'tcx>>);
498
499 impl<'tcx> Witness<'tcx> {
500     pub fn single_pattern(&self) -> &Pattern<'tcx> {
501         assert_eq!(self.0.len(), 1);
502         &self.0[0]
503     }
504
505     fn push_wild_constructor<'a>(
506         mut self,
507         cx: &MatchCheckCtxt<'a, 'tcx>,
508         ctor: &Constructor<'tcx>,
509         ty: Ty<'tcx>)
510         -> Self
511     {
512         let sub_pattern_tys = constructor_sub_pattern_tys(cx, ctor, ty);
513         self.0.extend(sub_pattern_tys.into_iter().map(|ty| {
514             Pattern {
515                 ty,
516                 span: DUMMY_SP,
517                 kind: box PatternKind::Wild,
518             }
519         }));
520         self.apply_constructor(cx, ctor, ty)
521     }
522
523
524     /// Constructs a partial witness for a pattern given a list of
525     /// patterns expanded by the specialization step.
526     ///
527     /// When a pattern P is discovered to be useful, this function is used bottom-up
528     /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
529     /// of values, V, where each value in that set is not covered by any previously
530     /// used patterns and is covered by the pattern P'. Examples:
531     ///
532     /// left_ty: tuple of 3 elements
533     /// pats: [10, 20, _]           => (10, 20, _)
534     ///
535     /// left_ty: struct X { a: (bool, &'static str), b: usize}
536     /// pats: [(false, "foo"), 42]  => X { a: (false, "foo"), b: 42 }
537     fn apply_constructor<'a>(
538         mut self,
539         cx: &MatchCheckCtxt<'a,'tcx>,
540         ctor: &Constructor<'tcx>,
541         ty: Ty<'tcx>)
542         -> Self
543     {
544         let arity = constructor_arity(cx, ctor, ty);
545         let pat = {
546             let len = self.0.len() as u64;
547             let mut pats = self.0.drain((len - arity) as usize..).rev();
548
549             match ty.sty {
550                 ty::TyAdt(..) |
551                 ty::TyTuple(..) => {
552                     let pats = pats.enumerate().map(|(i, p)| {
553                         FieldPattern {
554                             field: Field::new(i),
555                             pattern: p
556                         }
557                     }).collect();
558
559                     if let ty::TyAdt(adt, substs) = ty.sty {
560                         if adt.is_enum() {
561                             PatternKind::Variant {
562                                 adt_def: adt,
563                                 substs,
564                                 variant_index: ctor.variant_index_for_adt(adt),
565                                 subpatterns: pats
566                             }
567                         } else {
568                             PatternKind::Leaf { subpatterns: pats }
569                         }
570                     } else {
571                         PatternKind::Leaf { subpatterns: pats }
572                     }
573                 }
574
575                 ty::TyRef(..) => {
576                     PatternKind::Deref { subpattern: pats.nth(0).unwrap() }
577                 }
578
579                 ty::TySlice(_) | ty::TyArray(..) => {
580                     PatternKind::Slice {
581                         prefix: pats.collect(),
582                         slice: None,
583                         suffix: vec![]
584                     }
585                 }
586
587                 _ => {
588                     match *ctor {
589                         ConstantValue(value) => PatternKind::Constant { value },
590                         ConstantRange(lo, hi, end) => PatternKind::Range { lo, hi, end },
591                         _ => PatternKind::Wild,
592                     }
593                 }
594             }
595         };
596
597         self.0.push(Pattern {
598             ty,
599             span: DUMMY_SP,
600             kind: Box::new(pat),
601         });
602
603         self
604     }
605 }
606
607 /// This determines the set of all possible constructors of a pattern matching
608 /// values of type `left_ty`. For vectors, this would normally be an infinite set
609 /// but is instead bounded by the maximum fixed length of slice patterns in
610 /// the column of patterns being analyzed.
611 ///
612 /// We make sure to omit constructors that are statically impossible. eg for
613 /// Option<!> we do not include Some(_) in the returned list of constructors.
614 fn all_constructors<'a, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
615                                   pcx: PatternContext<'tcx>)
616                                   -> Vec<Constructor<'tcx>>
617 {
618     debug!("all_constructors({:?})", pcx.ty);
619     let exhaustive_integer_patterns = cx.tcx.features().exhaustive_integer_patterns;
620     let ctors = match pcx.ty.sty {
621         ty::TyBool => {
622             [true, false].iter().map(|&b| {
623                 ConstantValue(ty::Const::from_bool(cx.tcx, b))
624             }).collect()
625         }
626         ty::TyArray(ref sub_ty, len) if len.assert_usize(cx.tcx).is_some() => {
627             let len = len.unwrap_usize(cx.tcx);
628             if len != 0 && cx.is_uninhabited(sub_ty) {
629                 vec![]
630             } else {
631                 vec![Slice(len)]
632             }
633         }
634         // Treat arrays of a constant but unknown length like slices.
635         ty::TyArray(ref sub_ty, _) |
636         ty::TySlice(ref sub_ty) => {
637             if cx.is_uninhabited(sub_ty) {
638                 vec![Slice(0)]
639             } else {
640                 (0..pcx.max_slice_length+1).map(|length| Slice(length)).collect()
641             }
642         }
643         ty::TyAdt(def, substs) if def.is_enum() => {
644             def.variants.iter()
645                 .filter(|v| !cx.is_variant_uninhabited(v, substs))
646                 .map(|v| Variant(v.did))
647                 .collect()
648         }
649         ty::TyChar if exhaustive_integer_patterns => {
650             let endpoint = |c: char| {
651                 let ty = ty::ParamEnv::empty().and(cx.tcx.types.char);
652                 ty::Const::from_bits(cx.tcx, c as u128, ty)
653             };
654             vec![
655                 // The valid Unicode Scalar Value ranges.
656                 ConstantRange(endpoint('\u{0000}'), endpoint('\u{D7FF}'), RangeEnd::Included),
657                 ConstantRange(endpoint('\u{E000}'), endpoint('\u{10FFFF}'), RangeEnd::Included),
658             ]
659         }
660         ty::TyInt(ity) if exhaustive_integer_patterns => {
661             // FIXME(49937): refactor these bit manipulations into interpret.
662             let bits = Integer::from_attr(cx.tcx, SignedInt(ity)).size().bits() as u128;
663             let min = 1u128 << (bits - 1);
664             let max = (1u128 << (bits - 1)) - 1;
665             let ty = ty::ParamEnv::empty().and(pcx.ty);
666             vec![ConstantRange(ty::Const::from_bits(cx.tcx, min as u128, ty),
667                                ty::Const::from_bits(cx.tcx, max as u128, ty),
668                                RangeEnd::Included)]
669         }
670         ty::TyUint(uty) if exhaustive_integer_patterns => {
671             // FIXME(49937): refactor these bit manipulations into interpret.
672             let bits = Integer::from_attr(cx.tcx, UnsignedInt(uty)).size().bits() as u128;
673             let max = !0u128 >> (128 - bits);
674             let ty = ty::ParamEnv::empty().and(pcx.ty);
675             vec![ConstantRange(ty::Const::from_bits(cx.tcx, 0, ty),
676                                ty::Const::from_bits(cx.tcx, max, ty),
677                                RangeEnd::Included)]
678         }
679         _ => {
680             if cx.is_uninhabited(pcx.ty) {
681                 vec![]
682             } else {
683                 vec![Single]
684             }
685         }
686     };
687     ctors
688 }
689
690 fn max_slice_length<'p, 'a: 'p, 'tcx: 'a, I>(
691     cx: &mut MatchCheckCtxt<'a, 'tcx>,
692     patterns: I) -> u64
693     where I: Iterator<Item=&'p Pattern<'tcx>>
694 {
695     // The exhaustiveness-checking paper does not include any details on
696     // checking variable-length slice patterns. However, they are matched
697     // by an infinite collection of fixed-length array patterns.
698     //
699     // Checking the infinite set directly would take an infinite amount
700     // of time. However, it turns out that for each finite set of
701     // patterns `P`, all sufficiently large array lengths are equivalent:
702     //
703     // Each slice `s` with a "sufficiently-large" length `l ≥ L` that applies
704     // to exactly the subset `Pₜ` of `P` can be transformed to a slice
705     // `sₘ` for each sufficiently-large length `m` that applies to exactly
706     // the same subset of `P`.
707     //
708     // Because of that, each witness for reachability-checking from one
709     // of the sufficiently-large lengths can be transformed to an
710     // equally-valid witness from any other length, so we only have
711     // to check slice lengths from the "minimal sufficiently-large length"
712     // and below.
713     //
714     // Note that the fact that there is a *single* `sₘ` for each `m`
715     // not depending on the specific pattern in `P` is important: if
716     // you look at the pair of patterns
717     //     `[true, ..]`
718     //     `[.., false]`
719     // Then any slice of length ≥1 that matches one of these two
720     // patterns can be trivially turned to a slice of any
721     // other length ≥1 that matches them and vice-versa - for
722     // but the slice from length 2 `[false, true]` that matches neither
723     // of these patterns can't be turned to a slice from length 1 that
724     // matches neither of these patterns, so we have to consider
725     // slices from length 2 there.
726     //
727     // Now, to see that that length exists and find it, observe that slice
728     // patterns are either "fixed-length" patterns (`[_, _, _]`) or
729     // "variable-length" patterns (`[_, .., _]`).
730     //
731     // For fixed-length patterns, all slices with lengths *longer* than
732     // the pattern's length have the same outcome (of not matching), so
733     // as long as `L` is greater than the pattern's length we can pick
734     // any `sₘ` from that length and get the same result.
735     //
736     // For variable-length patterns, the situation is more complicated,
737     // because as seen above the precise value of `sₘ` matters.
738     //
739     // However, for each variable-length pattern `p` with a prefix of length
740     // `plₚ` and suffix of length `slₚ`, only the first `plₚ` and the last
741     // `slₚ` elements are examined.
742     //
743     // Therefore, as long as `L` is positive (to avoid concerns about empty
744     // types), all elements after the maximum prefix length and before
745     // the maximum suffix length are not examined by any variable-length
746     // pattern, and therefore can be added/removed without affecting
747     // them - creating equivalent patterns from any sufficiently-large
748     // length.
749     //
750     // Of course, if fixed-length patterns exist, we must be sure
751     // that our length is large enough to miss them all, so
752     // we can pick `L = max(FIXED_LEN+1 ∪ {max(PREFIX_LEN) + max(SUFFIX_LEN)})`
753     //
754     // for example, with the above pair of patterns, all elements
755     // but the first and last can be added/removed, so any
756     // witness of length ≥2 (say, `[false, false, true]`) can be
757     // turned to a witness from any other length ≥2.
758
759     let mut max_prefix_len = 0;
760     let mut max_suffix_len = 0;
761     let mut max_fixed_len = 0;
762
763     for row in patterns {
764         match *row.kind {
765             PatternKind::Constant { value } => {
766                 if let Some(ptr) = value.to_ptr() {
767                     let is_array_ptr = value.ty
768                         .builtin_deref(true)
769                         .and_then(|t| t.ty.builtin_index())
770                         .map_or(false, |t| t == cx.tcx.types.u8);
771                     if is_array_ptr {
772                         let alloc = cx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
773                         max_fixed_len = cmp::max(max_fixed_len, alloc.bytes.len() as u64);
774                     }
775                 }
776             }
777             PatternKind::Slice { ref prefix, slice: None, ref suffix } => {
778                 let fixed_len = prefix.len() as u64 + suffix.len() as u64;
779                 max_fixed_len = cmp::max(max_fixed_len, fixed_len);
780             }
781             PatternKind::Slice { ref prefix, slice: Some(_), ref suffix } => {
782                 max_prefix_len = cmp::max(max_prefix_len, prefix.len() as u64);
783                 max_suffix_len = cmp::max(max_suffix_len, suffix.len() as u64);
784             }
785             _ => {}
786         }
787     }
788
789     cmp::max(max_fixed_len + 1, max_prefix_len + max_suffix_len)
790 }
791
792 /// An inclusive interval, used for precise integer exhaustiveness checking.
793 /// `IntRange`s always store a contiguous range. This means that values are
794 /// encoded such that `0` encodes the minimum value for the integer,
795 /// regardless of the signedness.
796 /// For example, the pattern `-128...127i8` is encoded as `0..=255`.
797 /// This makes comparisons and arithmetic on interval endpoints much more
798 /// straightforward. See `signed_bias` for details.
799 ///
800 /// `IntRange` is never used to encode an empty range or a "range" that wraps
801 /// around the (offset) space: i.e. `range.lo <= range.hi`.
802 struct IntRange<'tcx> {
803     pub range: RangeInclusive<u128>,
804     pub ty: Ty<'tcx>,
805 }
806
807 impl<'tcx> IntRange<'tcx> {
808     fn from_ctor(tcx: TyCtxt<'_, 'tcx, 'tcx>,
809                  ctor: &Constructor<'tcx>)
810                  -> Option<IntRange<'tcx>> {
811         match ctor {
812             ConstantRange(lo, hi, end) => {
813                 assert_eq!(lo.ty, hi.ty);
814                 let ty = lo.ty;
815                 let env_ty = ty::ParamEnv::empty().and(ty);
816                 if let Some(lo) = lo.assert_bits(tcx, env_ty) {
817                     if let Some(hi) = hi.assert_bits(tcx, env_ty) {
818                         // Perform a shift if the underlying types are signed,
819                         // which makes the interval arithmetic simpler.
820                         let bias = IntRange::signed_bias(tcx, ty);
821                         let (lo, hi) = (lo ^ bias, hi ^ bias);
822                         // Make sure the interval is well-formed.
823                         return if lo > hi || lo == hi && *end == RangeEnd::Excluded {
824                             None
825                         } else {
826                             let offset = (*end == RangeEnd::Excluded) as u128;
827                             Some(IntRange { range: lo..=(hi - offset), ty })
828                         };
829                     }
830                 }
831                 None
832             }
833             ConstantValue(val) => {
834                 let ty = val.ty;
835                 if let Some(val) = val.assert_bits(tcx, ty::ParamEnv::empty().and(ty)) {
836                     let bias = IntRange::signed_bias(tcx, ty);
837                     let val = val ^ bias;
838                     Some(IntRange { range: val..=val, ty })
839                 } else {
840                     None
841                 }
842             }
843             Single | Variant(_) | Slice(_) => {
844                 None
845             }
846         }
847     }
848
849     fn from_pat(tcx: TyCtxt<'_, 'tcx, 'tcx>,
850                 pat: &Pattern<'tcx>)
851                 -> Option<IntRange<'tcx>> {
852         Self::from_ctor(tcx, &match pat.kind {
853             box PatternKind::Constant { value } => ConstantValue(value),
854             box PatternKind::Range { lo, hi, end } => ConstantRange(lo, hi, end),
855             _ => return None,
856         })
857     }
858
859     // The return value of `signed_bias` should be XORed with an endpoint to encode/decode it.
860     fn signed_bias(tcx: TyCtxt<'_, 'tcx, 'tcx>, ty: Ty<'tcx>) -> u128 {
861         match ty.sty {
862             ty::TyInt(ity) => {
863                 let bits = Integer::from_attr(tcx, SignedInt(ity)).size().bits() as u128;
864                 1u128 << (bits - 1)
865             }
866             _ => 0
867         }
868     }
869
870     /// Convert a `RangeInclusive` to a `ConstantValue` or inclusive `ConstantRange`.
871     fn range_to_ctor(
872         tcx: TyCtxt<'_, 'tcx, 'tcx>,
873         ty: Ty<'tcx>,
874         r: RangeInclusive<u128>,
875     ) -> Constructor<'tcx> {
876         let bias = IntRange::signed_bias(tcx, ty);
877         let ty = ty::ParamEnv::empty().and(ty);
878         let (lo, hi) = r.into_inner();
879         if lo == hi {
880             ConstantValue(ty::Const::from_bits(tcx, lo ^ bias, ty))
881         } else {
882             ConstantRange(ty::Const::from_bits(tcx, lo ^ bias, ty),
883                           ty::Const::from_bits(tcx, hi ^ bias, ty),
884                           RangeEnd::Included)
885         }
886     }
887
888     /// Return a collection of ranges that spans the values covered by `ranges`, subtracted
889     /// by the values covered by `self`: i.e. `ranges \ self` (in set notation).
890     fn subtract_from(self,
891                      tcx: TyCtxt<'_, 'tcx, 'tcx>,
892                      ranges: Vec<Constructor<'tcx>>)
893                      -> Vec<Constructor<'tcx>> {
894         let ranges = ranges.into_iter().filter_map(|r| {
895             IntRange::from_ctor(tcx, &r).map(|i| i.range)
896         });
897         let mut remaining_ranges = vec![];
898         let ty = self.ty;
899         let (lo, hi) = self.range.into_inner();
900         for subrange in ranges {
901             let (subrange_lo, subrange_hi) = subrange.into_inner();
902             if lo > subrange_hi || subrange_lo > hi  {
903                 // The pattern doesn't intersect with the subrange at all,
904                 // so the subrange remains untouched.
905                 remaining_ranges.push(Self::range_to_ctor(tcx, ty, subrange_lo..=subrange_hi));
906             } else {
907                 if lo > subrange_lo {
908                     // The pattern intersects an upper section of the
909                     // subrange, so a lower section will remain.
910                     remaining_ranges.push(Self::range_to_ctor(tcx, ty, subrange_lo..=(lo - 1)));
911                 }
912                 if hi < subrange_hi {
913                     // The pattern intersects a lower section of the
914                     // subrange, so an upper section will remain.
915                     remaining_ranges.push(Self::range_to_ctor(tcx, ty, (hi + 1)..=subrange_hi));
916                 }
917             }
918         }
919         remaining_ranges
920     }
921
922     fn intersection(&self, other: &Self) -> Option<Self> {
923         let ty = self.ty;
924         let (lo, hi) = (*self.range.start(), *self.range.end());
925         let (other_lo, other_hi) = (*other.range.start(), *other.range.end());
926         if lo <= other_hi && other_lo <= hi {
927             Some(IntRange { range: max(lo, other_lo)..=min(hi, other_hi), ty })
928         } else {
929             None
930         }
931     }
932 }
933
934 // Return a set of constructors equivalent to `all_ctors \ used_ctors`.
935 fn compute_missing_ctors<'a, 'tcx: 'a>(
936     tcx: TyCtxt<'a, 'tcx, 'tcx>,
937     all_ctors: &Vec<Constructor<'tcx>>,
938     used_ctors: &Vec<Constructor<'tcx>>,
939 ) -> Vec<Constructor<'tcx>> {
940     let mut missing_ctors = vec![];
941
942     for req_ctor in all_ctors {
943         let mut refined_ctors = vec![req_ctor.clone()];
944         for used_ctor in used_ctors {
945             if used_ctor == req_ctor {
946                 // If a constructor appears in a `match` arm, we can
947                 // eliminate it straight away.
948                 refined_ctors = vec![]
949             } else if tcx.features().exhaustive_integer_patterns {
950                 if let Some(interval) = IntRange::from_ctor(tcx, used_ctor) {
951                     // Refine the required constructors for the type by subtracting
952                     // the range defined by the current constructor pattern.
953                     refined_ctors = interval.subtract_from(tcx, refined_ctors);
954                 }
955             }
956
957             // If the constructor patterns that have been considered so far
958             // already cover the entire range of values, then we the
959             // constructor is not missing, and we can move on to the next one.
960             if refined_ctors.is_empty() {
961                 break;
962             }
963         }
964         // If a constructor has not been matched, then it is missing.
965         // We add `refined_ctors` instead of `req_ctor`, because then we can
966         // provide more detailed error information about precisely which
967         // ranges have been omitted.
968         missing_ctors.extend(refined_ctors);
969     }
970
971     missing_ctors
972 }
973
974 /// Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
975 /// The algorithm from the paper has been modified to correctly handle empty
976 /// types. The changes are:
977 ///   (0) We don't exit early if the pattern matrix has zero rows. We just
978 ///       continue to recurse over columns.
979 ///   (1) all_constructors will only return constructors that are statically
980 ///       possible. eg. it will only return Ok for Result<T, !>
981 ///
982 /// This finds whether a (row) vector `v` of patterns is 'useful' in relation
983 /// to a set of such vectors `m` - this is defined as there being a set of
984 /// inputs that will match `v` but not any of the sets in `m`.
985 ///
986 /// All the patterns at each column of the `matrix ++ v` matrix must
987 /// have the same type, except that wildcard (PatternKind::Wild) patterns
988 /// with type TyErr are also allowed, even if the "type of the column"
989 /// is not TyErr. That is used to represent private fields, as using their
990 /// real type would assert that they are inhabited.
991 ///
992 /// This is used both for reachability checking (if a pattern isn't useful in
993 /// relation to preceding patterns, it is not reachable) and exhaustiveness
994 /// checking (if a wildcard pattern is useful in relation to a matrix, the
995 /// matrix isn't exhaustive).
996 pub fn is_useful<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
997                                        matrix: &Matrix<'p, 'tcx>,
998                                        v: &[&'p Pattern<'tcx>],
999                                        witness: WitnessPreference)
1000                                        -> Usefulness<'tcx> {
1001     let &Matrix(ref rows) = matrix;
1002     debug!("is_useful({:#?}, {:#?})", matrix, v);
1003
1004     // The base case. We are pattern-matching on () and the return value is
1005     // based on whether our matrix has a row or not.
1006     // NOTE: This could potentially be optimized by checking rows.is_empty()
1007     // first and then, if v is non-empty, the return value is based on whether
1008     // the type of the tuple we're checking is inhabited or not.
1009     if v.is_empty() {
1010         return if rows.is_empty() {
1011             match witness {
1012                 ConstructWitness => UsefulWithWitness(vec![Witness(vec![])]),
1013                 LeaveOutWitness => Useful,
1014             }
1015         } else {
1016             NotUseful
1017         }
1018     };
1019
1020     assert!(rows.iter().all(|r| r.len() == v.len()));
1021
1022     let pcx = PatternContext {
1023         // TyErr is used to represent the type of wildcard patterns matching
1024         // against inaccessible (private) fields of structs, so that we won't
1025         // be able to observe whether the types of the struct's fields are
1026         // inhabited.
1027         //
1028         // If the field is truly inaccessible, then all the patterns
1029         // matching against it must be wildcard patterns, so its type
1030         // does not matter.
1031         //
1032         // However, if we are matching against non-wildcard patterns, we
1033         // need to know the real type of the field so we can specialize
1034         // against it. This primarily occurs through constants - they
1035         // can include contents for fields that are inaccessible at the
1036         // location of the match. In that case, the field's type is
1037         // inhabited - by the constant - so we can just use it.
1038         //
1039         // FIXME: this might lead to "unstable" behavior with macro hygiene
1040         // introducing uninhabited patterns for inaccessible fields. We
1041         // need to figure out how to model that.
1042         ty: rows.iter().map(|r| r[0].ty).find(|ty| !ty.references_error()).unwrap_or(v[0].ty),
1043         max_slice_length: max_slice_length(cx, rows.iter().map(|r| r[0]).chain(Some(v[0])))
1044     };
1045
1046     debug!("is_useful_expand_first_col: pcx={:#?}, expanding {:#?}", pcx, v[0]);
1047
1048     if let Some(constructors) = pat_constructors(cx, v[0], pcx) {
1049         debug!("is_useful - expanding constructors: {:#?}", constructors);
1050         split_grouped_constructors(cx.tcx, constructors, matrix, v, pcx.ty).into_iter().map(|c|
1051             is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness)
1052         ).find(|result| result.is_useful()).unwrap_or(NotUseful)
1053     } else {
1054         debug!("is_useful - expanding wildcard");
1055
1056         let used_ctors: Vec<Constructor> = rows.iter().flat_map(|row| {
1057             pat_constructors(cx, row[0], pcx).unwrap_or(vec![])
1058         }).collect();
1059         debug!("used_ctors = {:#?}", used_ctors);
1060         // `all_ctors` are all the constructors for the given type, which
1061         // should all be represented (or caught with the wild pattern `_`).
1062         let all_ctors = all_constructors(cx, pcx);
1063         debug!("all_ctors = {:#?}", all_ctors);
1064
1065         // `missing_ctors` is the set of constructors from the same type as the
1066         // first column of `matrix` that are matched only by wildcard patterns
1067         // from the first column.
1068         //
1069         // Therefore, if there is some pattern that is unmatched by `matrix`,
1070         // it will still be unmatched if the first constructor is replaced by
1071         // any of the constructors in `missing_ctors`
1072         //
1073         // However, if our scrutinee is *privately* an empty enum, we
1074         // must treat it as though it had an "unknown" constructor (in
1075         // that case, all other patterns obviously can't be variants)
1076         // to avoid exposing its emptyness. See the `match_privately_empty`
1077         // test for details.
1078         //
1079         // FIXME: currently the only way I know of something can
1080         // be a privately-empty enum is when the exhaustive_patterns
1081         // feature flag is not present, so this is only
1082         // needed for that case.
1083
1084         // Find those constructors that are not matched by any non-wildcard patterns in the
1085         // current column.
1086         let missing_ctors = compute_missing_ctors(cx.tcx, &all_ctors, &used_ctors);
1087
1088         let is_privately_empty = all_ctors.is_empty() && !cx.is_uninhabited(pcx.ty);
1089         let is_declared_nonexhaustive = cx.is_non_exhaustive_enum(pcx.ty) && !cx.is_local(pcx.ty);
1090         debug!("missing_ctors={:#?} is_privately_empty={:#?} is_declared_nonexhaustive={:#?}",
1091                missing_ctors, is_privately_empty, is_declared_nonexhaustive);
1092
1093         // For privately empty and non-exhaustive enums, we work as if there were an "extra"
1094         // `_` constructor for the type, so we can never match over all constructors.
1095         let is_non_exhaustive = is_privately_empty || is_declared_nonexhaustive;
1096
1097         if missing_ctors.is_empty() && !is_non_exhaustive {
1098             split_grouped_constructors(cx.tcx, all_ctors, matrix, v, pcx.ty).into_iter().map(|c| {
1099                 is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness)
1100             }).find(|result| result.is_useful()).unwrap_or(NotUseful)
1101         } else {
1102             let matrix = rows.iter().filter_map(|r| {
1103                 if r[0].is_wildcard() {
1104                     Some(r[1..].to_vec())
1105                 } else {
1106                     None
1107                 }
1108             }).collect();
1109             match is_useful(cx, &matrix, &v[1..], witness) {
1110                 UsefulWithWitness(pats) => {
1111                     let cx = &*cx;
1112                     // In this case, there's at least one "free"
1113                     // constructor that is only matched against by
1114                     // wildcard patterns.
1115                     //
1116                     // There are 2 ways we can report a witness here.
1117                     // Commonly, we can report all the "free"
1118                     // constructors as witnesses, e.g. if we have:
1119                     //
1120                     // ```
1121                     //     enum Direction { N, S, E, W }
1122                     //     let Direction::N = ...;
1123                     // ```
1124                     //
1125                     // we can report 3 witnesses: `S`, `E`, and `W`.
1126                     //
1127                     // However, there are 2 cases where we don't want
1128                     // to do this and instead report a single `_` witness:
1129                     //
1130                     // 1) If the user is matching against a non-exhaustive
1131                     // enum, there is no point in enumerating all possible
1132                     // variants, because the user can't actually match
1133                     // against them himself, e.g. in an example like:
1134                     // ```
1135                     //     let err: io::ErrorKind = ...;
1136                     //     match err {
1137                     //         io::ErrorKind::NotFound => {},
1138                     //     }
1139                     // ```
1140                     // we don't want to show every possible IO error,
1141                     // but instead have `_` as the witness (this is
1142                     // actually *required* if the user specified *all*
1143                     // IO errors, but is probably what we want in every
1144                     // case).
1145                     //
1146                     // 2) If the user didn't actually specify a constructor
1147                     // in this arm, e.g. in
1148                     // ```
1149                     //     let x: (Direction, Direction, bool) = ...;
1150                     //     let (_, _, false) = x;
1151                     // ```
1152                     // we don't want to show all 16 possible witnesses
1153                     // `(<direction-1>, <direction-2>, true)` - we are
1154                     // satisfied with `(_, _, true)`. In this case,
1155                     // `used_ctors` is empty.
1156                     let new_witnesses = if is_non_exhaustive || used_ctors.is_empty() {
1157                         // All constructors are unused. Add wild patterns
1158                         // rather than each individual constructor.
1159                         pats.into_iter().map(|mut witness| {
1160                             witness.0.push(Pattern {
1161                                 ty: pcx.ty,
1162                                 span: DUMMY_SP,
1163                                 kind: box PatternKind::Wild,
1164                             });
1165                             witness
1166                         }).collect()
1167                     } else {
1168                         pats.into_iter().flat_map(|witness| {
1169                             missing_ctors.iter().map(move |ctor| {
1170                                 // Extends the witness with a "wild" version of this
1171                                 // constructor, that matches everything that can be built with
1172                                 // it. For example, if `ctor` is a `Constructor::Variant` for
1173                                 // `Option::Some`, this pushes the witness for `Some(_)`.
1174                                 witness.clone().push_wild_constructor(cx, ctor, pcx.ty)
1175                             })
1176                         }).collect()
1177                     };
1178                     UsefulWithWitness(new_witnesses)
1179                 }
1180                 result => result
1181             }
1182         }
1183     }
1184 }
1185
1186 /// A shorthand for the `U(S(c, P), S(c, q))` operation from the paper. I.e. `is_useful` applied
1187 /// to the specialised version of both the pattern matrix `P` and the new pattern `q`.
1188 fn is_useful_specialized<'p, 'a:'p, 'tcx: 'a>(
1189     cx: &mut MatchCheckCtxt<'a, 'tcx>,
1190     &Matrix(ref m): &Matrix<'p, 'tcx>,
1191     v: &[&'p Pattern<'tcx>],
1192     ctor: Constructor<'tcx>,
1193     lty: Ty<'tcx>,
1194     witness: WitnessPreference,
1195 ) -> Usefulness<'tcx> {
1196     debug!("is_useful_specialized({:#?}, {:#?}, {:?})", v, ctor, lty);
1197     let sub_pat_tys = constructor_sub_pattern_tys(cx, &ctor, lty);
1198     let wild_patterns_owned: Vec<_> = sub_pat_tys.iter().map(|ty| {
1199         Pattern {
1200             ty,
1201             span: DUMMY_SP,
1202             kind: box PatternKind::Wild,
1203         }
1204     }).collect();
1205     let wild_patterns: Vec<_> = wild_patterns_owned.iter().collect();
1206     let matrix = Matrix(m.iter().flat_map(|r| {
1207         specialize(cx, &r, &ctor, &wild_patterns)
1208     }).collect());
1209     match specialize(cx, v, &ctor, &wild_patterns) {
1210         Some(v) => match is_useful(cx, &matrix, &v, witness) {
1211             UsefulWithWitness(witnesses) => UsefulWithWitness(
1212                 witnesses.into_iter()
1213                     .map(|witness| witness.apply_constructor(cx, &ctor, lty))
1214                     .collect()
1215             ),
1216             result => result
1217         }
1218         None => NotUseful
1219     }
1220 }
1221
1222 /// Determines the constructors that the given pattern can be specialized to.
1223 ///
1224 /// In most cases, there's only one constructor that a specific pattern
1225 /// represents, such as a specific enum variant or a specific literal value.
1226 /// Slice patterns, however, can match slices of different lengths. For instance,
1227 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
1228 ///
1229 /// Returns `None` in case of a catch-all, which can't be specialized.
1230 fn pat_constructors<'tcx>(cx: &mut MatchCheckCtxt,
1231                           pat: &Pattern<'tcx>,
1232                           pcx: PatternContext)
1233                           -> Option<Vec<Constructor<'tcx>>>
1234 {
1235     match *pat.kind {
1236         PatternKind::Binding { .. } | PatternKind::Wild => None,
1237         PatternKind::Leaf { .. } | PatternKind::Deref { .. } => Some(vec![Single]),
1238         PatternKind::Variant { adt_def, variant_index, .. } => {
1239             Some(vec![Variant(adt_def.variants[variant_index].did)])
1240         }
1241         PatternKind::Constant { value } => Some(vec![ConstantValue(value)]),
1242         PatternKind::Range { lo, hi, end } => Some(vec![ConstantRange(lo, hi, end)]),
1243         PatternKind::Array { .. } => match pcx.ty.sty {
1244             ty::TyArray(_, length) => Some(vec![
1245                 Slice(length.unwrap_usize(cx.tcx))
1246             ]),
1247             _ => span_bug!(pat.span, "bad ty {:?} for array pattern", pcx.ty)
1248         },
1249         PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
1250             let pat_len = prefix.len() as u64 + suffix.len() as u64;
1251             if slice.is_some() {
1252                 Some((pat_len..pcx.max_slice_length+1).map(Slice).collect())
1253             } else {
1254                 Some(vec![Slice(pat_len)])
1255             }
1256         }
1257     }
1258 }
1259
1260 /// This computes the arity of a constructor. The arity of a constructor
1261 /// is how many subpattern patterns of that constructor should be expanded to.
1262 ///
1263 /// For instance, a tuple pattern (_, 42, Some([])) has the arity of 3.
1264 /// A struct pattern's arity is the number of fields it contains, etc.
1265 fn constructor_arity(_cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> u64 {
1266     debug!("constructor_arity({:#?}, {:?})", ctor, ty);
1267     match ty.sty {
1268         ty::TyTuple(ref fs) => fs.len() as u64,
1269         ty::TySlice(..) | ty::TyArray(..) => match *ctor {
1270             Slice(length) => length,
1271             ConstantValue(_) => 0,
1272             _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
1273         },
1274         ty::TyRef(..) => 1,
1275         ty::TyAdt(adt, _) => {
1276             adt.variants[ctor.variant_index_for_adt(adt)].fields.len() as u64
1277         }
1278         _ => 0
1279     }
1280 }
1281
1282 /// This computes the types of the sub patterns that a constructor should be
1283 /// expanded to.
1284 ///
1285 /// For instance, a tuple pattern (43u32, 'a') has sub pattern types [u32, char].
1286 fn constructor_sub_pattern_tys<'a, 'tcx: 'a>(cx: &MatchCheckCtxt<'a, 'tcx>,
1287                                              ctor: &Constructor,
1288                                              ty: Ty<'tcx>) -> Vec<Ty<'tcx>>
1289 {
1290     debug!("constructor_sub_pattern_tys({:#?}, {:?})", ctor, ty);
1291     match ty.sty {
1292         ty::TyTuple(ref fs) => fs.into_iter().map(|t| *t).collect(),
1293         ty::TySlice(ty) | ty::TyArray(ty, _) => match *ctor {
1294             Slice(length) => (0..length).map(|_| ty).collect(),
1295             ConstantValue(_) => vec![],
1296             _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
1297         },
1298         ty::TyRef(_, rty, _) => vec![rty],
1299         ty::TyAdt(adt, substs) => {
1300             if adt.is_box() {
1301                 // Use T as the sub pattern type of Box<T>.
1302                 vec![substs.type_at(0)]
1303             } else {
1304                 adt.variants[ctor.variant_index_for_adt(adt)].fields.iter().map(|field| {
1305                     let is_visible = adt.is_enum()
1306                         || field.vis.is_accessible_from(cx.module, cx.tcx);
1307                     if is_visible {
1308                         field.ty(cx.tcx, substs)
1309                     } else {
1310                         // Treat all non-visible fields as TyErr. They
1311                         // can't appear in any other pattern from
1312                         // this match (because they are private),
1313                         // so their type does not matter - but
1314                         // we don't want to know they are
1315                         // uninhabited.
1316                         cx.tcx.types.err
1317                     }
1318                 }).collect()
1319             }
1320         }
1321         _ => vec![],
1322     }
1323 }
1324
1325 fn slice_pat_covered_by_constructor<'tcx>(
1326     tcx: TyCtxt<'_, 'tcx, '_>,
1327     _span: Span,
1328     ctor: &Constructor,
1329     prefix: &[Pattern<'tcx>],
1330     slice: &Option<Pattern<'tcx>>,
1331     suffix: &[Pattern<'tcx>]
1332 ) -> Result<bool, ErrorReported> {
1333     let data: &[u8] = match *ctor {
1334         ConstantValue(const_val) => {
1335             let val = match const_val.val {
1336                 ConstValue::Unevaluated(..) |
1337                 ConstValue::ByRef(..) => bug!("unexpected ConstValue: {:?}", const_val),
1338                 ConstValue::Scalar(val) | ConstValue::ScalarPair(val, _) => val,
1339             };
1340             if let Ok(ptr) = val.to_ptr() {
1341                 let is_array_ptr = const_val.ty
1342                     .builtin_deref(true)
1343                     .and_then(|t| t.ty.builtin_index())
1344                     .map_or(false, |t| t == tcx.types.u8);
1345                 assert!(is_array_ptr);
1346                 tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id).bytes.as_ref()
1347             } else {
1348                 bug!("unexpected non-ptr ConstantValue")
1349             }
1350         }
1351         _ => bug!()
1352     };
1353
1354     let pat_len = prefix.len() + suffix.len();
1355     if data.len() < pat_len || (slice.is_none() && data.len() > pat_len) {
1356         return Ok(false);
1357     }
1358
1359     for (ch, pat) in
1360         data[..prefix.len()].iter().zip(prefix).chain(
1361             data[data.len()-suffix.len()..].iter().zip(suffix))
1362     {
1363         match pat.kind {
1364             box PatternKind::Constant { value } => {
1365                 let b = value.unwrap_bits(tcx, ty::ParamEnv::empty().and(pat.ty));
1366                 assert_eq!(b as u8 as u128, b);
1367                 if b as u8 != *ch {
1368                     return Ok(false);
1369                 }
1370             }
1371             _ => {}
1372         }
1373     }
1374
1375     Ok(true)
1376 }
1377
1378 // Whether to evaluate a constructor using exhaustive integer matching. This is true if the
1379 // constructor is a range or constant with an integer type.
1380 fn should_treat_range_exhaustively(tcx: TyCtxt<'_, 'tcx, 'tcx>, ctor: &Constructor<'tcx>) -> bool {
1381     if tcx.features().exhaustive_integer_patterns {
1382         if let ConstantValue(value) | ConstantRange(value, _, _) = ctor {
1383             if let ty::TyChar | ty::TyInt(_) | ty::TyUint(_) = value.ty.sty {
1384                 return true;
1385             }
1386         }
1387     }
1388     false
1389 }
1390
1391 /// For exhaustive integer matching, some constructors are grouped within other constructors
1392 /// (namely integer typed values are grouped within ranges). However, when specialising these
1393 /// constructors, we want to be specialising for the underlying constructors (the integers), not
1394 /// the groups (the ranges). Thus we need to split the groups up. Splitting them up naïvely would
1395 /// mean creating a separate constructor for every single value in the range, which is clearly
1396 /// impractical. However, observe that for some ranges of integers, the specialisation will be
1397 /// identical across all values in that range (i.e. there are equivalence classes of ranges of
1398 /// constructors based on their `is_useful_specialised` outcome). These classes are grouped by
1399 /// the patterns that apply to them (both in the matrix `P` and in the new row `p_{m + 1}`). We
1400 /// can split the range whenever the patterns that apply to that range (specifically: the patterns
1401 /// that *intersect* with that range) change.
1402 /// Our solution, therefore, is to split the range constructor into subranges at every single point
1403 /// the group of intersecting patterns changes, which we can compute by converting each pattern to
1404 /// a range and recording its endpoints, then creating subranges between each consecutive pair of
1405 /// endpoints.
1406 /// And voilà! We're testing precisely those ranges that we need to, without any exhaustive matching
1407 /// on actual integers. The nice thing about this is that the number of subranges is linear in the
1408 /// number of rows in the matrix (i.e. the number of cases in the `match` statement), so we don't
1409 /// need to be worried about matching over gargantuan ranges.
1410 fn split_grouped_constructors<'p, 'a: 'p, 'tcx: 'a>(
1411     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1412     ctors: Vec<Constructor<'tcx>>,
1413     &Matrix(ref m): &Matrix<'p, 'tcx>,
1414     p: &[&'p Pattern<'tcx>],
1415     ty: Ty<'tcx>,
1416 ) -> Vec<Constructor<'tcx>> {
1417     let pat = &p[0];
1418
1419     let mut split_ctors = Vec::with_capacity(ctors.len());
1420
1421     for ctor in ctors.into_iter() {
1422         match ctor {
1423             // For now, only ranges may denote groups of "subconstructors", so we only need to
1424             // special-case constant ranges.
1425             ConstantRange(..) if should_treat_range_exhaustively(tcx, &ctor) => {
1426                 // We only care about finding all the subranges within the range of the intersection
1427                 // of the new pattern `p_({m + 1},1)` (here `pat`) and the constructor range.
1428                 // Anything else is irrelevant, because it is guaranteed to result in `NotUseful`,
1429                 // which is the default case anyway, and can be ignored.
1430                 let mut ctor_range = IntRange::from_ctor(tcx, &ctor).unwrap();
1431                 if let Some(pat_range) = IntRange::from_pat(tcx, pat) {
1432                     if let Some(new_range) = ctor_range.intersection(&pat_range) {
1433                         ctor_range = new_range;
1434                     } else {
1435                         // If the intersection between `pat` and the constructor is empty, the
1436                         // entire range is `NotUseful`.
1437                         continue;
1438                     }
1439                 } else {
1440                     match pat.kind {
1441                         box PatternKind::Wild => {
1442                             // A wild pattern matches the entire range of values,
1443                             // so the current values are fine.
1444                         }
1445                         // If the pattern is not a value (i.e. a degenerate range), a range or a
1446                         // wildcard (which stands for the entire range), then it's guaranteed to
1447                         // be `NotUseful`.
1448                         _ => continue,
1449                     }
1450                 }
1451                 // We're going to collect all the endpoints in the new pattern so we can create
1452                 // subranges between them.
1453                 // If there's a single point, we need to identify it as belonging
1454                 // to a length-1 range, so it can be treated as an individual
1455                 // constructor, rather than as an endpoint. To do this, we keep track of which
1456                 // endpoint a point corresponds to. Whenever a point corresponds to both a start
1457                 // and an end, then we create a unit range for it.
1458                 #[derive(PartialEq, Clone, Copy, Debug)]
1459                 enum Endpoint {
1460                     Start,
1461                     End,
1462                     Both,
1463                 };
1464                 let mut points = FxHashMap::default();
1465                 let add_endpoint = |points: &mut FxHashMap<_, _>, x, endpoint| {
1466                     points.entry(x).and_modify(|ex_x| {
1467                         if *ex_x != endpoint {
1468                             *ex_x = Endpoint::Both
1469                         }
1470                     }).or_insert(endpoint);
1471                 };
1472                 let add_endpoints = |points: &mut FxHashMap<_, _>, lo, hi| {
1473                     // Insert the endpoints, taking care to keep track of to
1474                     // which endpoints a point corresponds.
1475                     add_endpoint(points, lo, Endpoint::Start);
1476                     add_endpoint(points, hi, Endpoint::End);
1477                 };
1478                 let (lo, hi) = (*ctor_range.range.start(), *ctor_range.range.end());
1479                 add_endpoints(&mut points, lo, hi);
1480                 // We're going to iterate through every row pattern, adding endpoints in.
1481                 for row in m.iter() {
1482                     if let Some(r) = IntRange::from_pat(tcx, row[0]) {
1483                         // We're only interested in endpoints that lie (at least partially)
1484                         // within the subrange domain.
1485                         if let Some(r) = ctor_range.intersection(&r) {
1486                             let (r_lo, r_hi) = r.range.into_inner();
1487                             add_endpoints(&mut points, r_lo, r_hi);
1488                         }
1489                     }
1490                 }
1491
1492                 // The patterns were iterated in an arbitrary order (i.e. in the order the user
1493                 // wrote them), so we need to make sure our endpoints are sorted.
1494                 let mut points: Vec<(u128, Endpoint)> = points.into_iter().collect();
1495                 points.sort_unstable_by_key(|(x, _)| *x);
1496                 let mut points = points.into_iter();
1497                 let mut a = points.next().unwrap();
1498
1499                 // Iterate through pairs of points, adding the subranges to `split_ctors`.
1500                 // We have to be careful about the orientation of the points as endpoints, to make
1501                 // sure we're enumerating precisely the correct ranges. Too few and the matching is
1502                 // actually incorrect. Too many and our diagnostics are poorer. This involves some
1503                 // case analysis.
1504                 while let Some(b) = points.next() {
1505                     // a < b (strictly)
1506                     if let Endpoint::Both = a.1 {
1507                         split_ctors.push(IntRange::range_to_ctor(tcx, ty, a.0..=a.0));
1508                     }
1509                     let c = match a.1 {
1510                         Endpoint::Start => a.0,
1511                         Endpoint::End | Endpoint::Both => a.0 + 1,
1512                     };
1513                     let d = match b.1 {
1514                         Endpoint::Start | Endpoint::Both => b.0 - 1,
1515                         Endpoint::End => b.0,
1516                     };
1517                     // In some cases, we won't need an intermediate range between two ranges
1518                     // lie immediately adjacent to one another.
1519                     if c <= d {
1520                         split_ctors.push(IntRange::range_to_ctor(tcx, ty, c..=d));
1521                     }
1522
1523                     a = b;
1524                 }
1525             }
1526             // Any other constructor can be used unchanged.
1527             _ => split_ctors.push(ctor),
1528         }
1529     }
1530
1531     split_ctors
1532 }
1533
1534 /// Check whether there exists any shared value in either `ctor` or `pat` by intersecting them.
1535 fn constructor_intersects_pattern<'p, 'a: 'p, 'tcx: 'a>(
1536     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1537     ctor: &Constructor<'tcx>,
1538     pat: &'p Pattern<'tcx>,
1539 ) -> Option<Vec<&'p Pattern<'tcx>>> {
1540     if should_treat_range_exhaustively(tcx, ctor) {
1541         match (IntRange::from_ctor(tcx, ctor), IntRange::from_pat(tcx, pat)) {
1542             (Some(ctor), Some(pat)) => ctor.intersection(&pat).map(|_| vec![]),
1543             _ => None,
1544         }
1545     } else {
1546         // Fallback for non-ranges and ranges that involve floating-point numbers, which are not
1547         // conveniently handled by `IntRange`. For these cases, the constructor may not be a range
1548         // so intersection actually devolves into being covered by the pattern.
1549         match constructor_covered_by_range(tcx, ctor, pat) {
1550             Ok(true) => Some(vec![]),
1551             Ok(false) | Err(ErrorReported) => None,
1552         }
1553     }
1554 }
1555
1556 fn constructor_covered_by_range<'a, 'tcx>(
1557     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1558     ctor: &Constructor<'tcx>,
1559     pat: &Pattern<'tcx>,
1560 ) -> Result<bool, ErrorReported> {
1561     let (from, to, end, ty) = match pat.kind {
1562         box PatternKind::Constant { value } => (value, value, RangeEnd::Included, value.ty),
1563         box PatternKind::Range { lo, hi, end } => (lo, hi, end, lo.ty),
1564         _ => bug!("`constructor_covered_by_range` called with {:?}", pat),
1565     };
1566     trace!("constructor_covered_by_range {:#?}, {:#?}, {:#?}, {}", ctor, from, to, ty);
1567     let cmp_from = |c_from| compare_const_vals(tcx, c_from, from, ty::ParamEnv::empty().and(ty))
1568         .map(|res| res != Ordering::Less);
1569     let cmp_to = |c_to| compare_const_vals(tcx, c_to, to, ty::ParamEnv::empty().and(ty));
1570     macro_rules! some_or_ok {
1571         ($e:expr) => {
1572             match $e {
1573                 Some(to) => to,
1574                 None => return Ok(false), // not char or int
1575             }
1576         };
1577     }
1578     match *ctor {
1579         ConstantValue(value) => {
1580             let to = some_or_ok!(cmp_to(value));
1581             let end = (to == Ordering::Less) ||
1582                       (end == RangeEnd::Included && to == Ordering::Equal);
1583             Ok(some_or_ok!(cmp_from(value)) && end)
1584         },
1585         ConstantRange(from, to, RangeEnd::Included) => {
1586             let to = some_or_ok!(cmp_to(to));
1587             let end = (to == Ordering::Less) ||
1588                       (end == RangeEnd::Included && to == Ordering::Equal);
1589             Ok(some_or_ok!(cmp_from(from)) && end)
1590         },
1591         ConstantRange(from, to, RangeEnd::Excluded) => {
1592             let to = some_or_ok!(cmp_to(to));
1593             let end = (to == Ordering::Less) ||
1594                       (end == RangeEnd::Excluded && to == Ordering::Equal);
1595             Ok(some_or_ok!(cmp_from(from)) && end)
1596         }
1597         Single => Ok(true),
1598         _ => bug!(),
1599     }
1600 }
1601
1602 fn patterns_for_variant<'p, 'a: 'p, 'tcx: 'a>(
1603     subpatterns: &'p [FieldPattern<'tcx>],
1604     wild_patterns: &[&'p Pattern<'tcx>])
1605     -> Vec<&'p Pattern<'tcx>>
1606 {
1607     let mut result = wild_patterns.to_owned();
1608
1609     for subpat in subpatterns {
1610         result[subpat.field.index()] = &subpat.pattern;
1611     }
1612
1613     debug!("patterns_for_variant({:#?}, {:#?}) = {:#?}", subpatterns, wild_patterns, result);
1614     result
1615 }
1616
1617 /// This is the main specialization step. It expands the first pattern in the given row
1618 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
1619 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
1620 ///
1621 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
1622 /// different patterns.
1623 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
1624 /// fields filled with wild patterns.
1625 fn specialize<'p, 'a: 'p, 'tcx: 'a>(
1626     cx: &mut MatchCheckCtxt<'a, 'tcx>,
1627     r: &[&'p Pattern<'tcx>],
1628     constructor: &Constructor<'tcx>,
1629     wild_patterns: &[&'p Pattern<'tcx>],
1630 ) -> Option<Vec<&'p Pattern<'tcx>>> {
1631     let pat = &r[0];
1632
1633     let head: Option<Vec<&Pattern>> = match *pat.kind {
1634         PatternKind::Binding { .. } | PatternKind::Wild => {
1635             Some(wild_patterns.to_owned())
1636         }
1637
1638         PatternKind::Variant { adt_def, variant_index, ref subpatterns, .. } => {
1639             let ref variant = adt_def.variants[variant_index];
1640             if *constructor == Variant(variant.did) {
1641                 Some(patterns_for_variant(subpatterns, wild_patterns))
1642             } else {
1643                 None
1644             }
1645         }
1646
1647         PatternKind::Leaf { ref subpatterns } => {
1648             Some(patterns_for_variant(subpatterns, wild_patterns))
1649         }
1650
1651         PatternKind::Deref { ref subpattern } => {
1652             Some(vec![subpattern])
1653         }
1654
1655         PatternKind::Constant { value } => {
1656             match *constructor {
1657                 Slice(..) => {
1658                     if let Some(ptr) = value.to_ptr() {
1659                         let is_array_ptr = value.ty
1660                             .builtin_deref(true)
1661                             .and_then(|t| t.ty.builtin_index())
1662                             .map_or(false, |t| t == cx.tcx.types.u8);
1663                         assert!(is_array_ptr);
1664                         let data_len = cx.tcx
1665                             .alloc_map
1666                             .lock()
1667                             .unwrap_memory(ptr.alloc_id)
1668                             .bytes
1669                             .len();
1670                         if wild_patterns.len() == data_len {
1671                             Some(cx.lower_byte_str_pattern(pat))
1672                         } else {
1673                             None
1674                         }
1675                     } else {
1676                         span_bug!(pat.span,
1677                         "unexpected const-val {:?} with ctor {:?}", value, constructor)
1678                     }
1679                 }
1680                 _ => {
1681                     // If the constructor is a single value, we add a row to the specialised matrix
1682                     // if the pattern is equal to the constructor. If the constructor is a range of
1683                     // values, we add a row to the specialised matrix if the pattern is contained
1684                     // within the constructor. These two cases (for a single value pattern) can be
1685                     // treated as intersection.
1686                     constructor_intersects_pattern(cx.tcx, constructor, pat)
1687                 }
1688             }
1689         }
1690
1691         PatternKind::Range { .. } => {
1692             // If the constructor is a single value, we add a row to the specialised matrix if the
1693             // pattern contains the constructor. If the constructor is a range of values, we add a
1694             // row to the specialised matrix if there exists any value that lies both within the
1695             // pattern and the constructor. These two cases reduce to intersection.
1696             constructor_intersects_pattern(cx.tcx, constructor, pat)
1697         }
1698
1699         PatternKind::Array { ref prefix, ref slice, ref suffix } |
1700         PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
1701             match *constructor {
1702                 Slice(..) => {
1703                     let pat_len = prefix.len() + suffix.len();
1704                     if let Some(slice_count) = wild_patterns.len().checked_sub(pat_len) {
1705                         if slice_count == 0 || slice.is_some() {
1706                             Some(prefix.iter().chain(
1707                                     wild_patterns.iter().map(|p| *p)
1708                                                  .skip(prefix.len())
1709                                                  .take(slice_count)
1710                                                  .chain(suffix.iter())
1711                             ).collect())
1712                         } else {
1713                             None
1714                         }
1715                     } else {
1716                         None
1717                     }
1718                 }
1719                 ConstantValue(..) => {
1720                     match slice_pat_covered_by_constructor(
1721                         cx.tcx, pat.span, constructor, prefix, slice, suffix
1722                             ) {
1723                         Ok(true) => Some(vec![]),
1724                         Ok(false) => None,
1725                         Err(ErrorReported) => None
1726                     }
1727                 }
1728                 _ => span_bug!(pat.span,
1729                     "unexpected ctor {:?} for slice pat", constructor)
1730             }
1731         }
1732     };
1733     debug!("specialize({:#?}, {:#?}) = {:#?}", r[0], wild_patterns, head);
1734
1735     head.map(|mut head| {
1736         head.extend_from_slice(&r[1 ..]);
1737         head
1738     })
1739 }