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