]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/hair/pattern/_match.rs
Implement interval checking
[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 use self::Constructor::*;
12 use self::Usefulness::*;
13 use self::WitnessPreference::*;
14
15 use rustc_data_structures::fx::FxHashMap;
16 use rustc_data_structures::indexed_vec::Idx;
17
18 use super::{FieldPattern, Pattern, PatternKind};
19 use super::{PatternFoldable, PatternFolder, compare_const_vals};
20
21 use rustc::hir::def_id::DefId;
22 use rustc::hir::RangeEnd;
23 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
24
25 use rustc::mir::Field;
26 use rustc::mir::interpret::ConstValue;
27 use rustc::util::common::ErrorReported;
28
29 use syntax_pos::{Span, DUMMY_SP};
30
31 use arena::TypedArena;
32
33 use std::cmp::{self, Ordering};
34 use std::fmt;
35 use std::iter::{FromIterator, IntoIterator};
36
37 pub fn expand_pattern<'a, 'tcx>(cx: &MatchCheckCtxt<'a, 'tcx>, pat: Pattern<'tcx>)
38                                 -> &'a Pattern<'tcx>
39 {
40     cx.pattern_arena.alloc(LiteralExpander.fold_pattern(&pat))
41 }
42
43 struct LiteralExpander;
44 impl<'tcx> PatternFolder<'tcx> for LiteralExpander {
45     fn fold_pattern(&mut self, pat: &Pattern<'tcx>) -> Pattern<'tcx> {
46         match (&pat.ty.sty, &*pat.kind) {
47             (&ty::TyRef(_, rty, _), &PatternKind::Constant { ref value }) => {
48                 Pattern {
49                     ty: pat.ty,
50                     span: pat.span,
51                     kind: box PatternKind::Deref {
52                         subpattern: Pattern {
53                             ty: rty,
54                             span: pat.span,
55                             kind: box PatternKind::Constant { value: value.clone() },
56                         }
57                     }
58                 }
59             }
60             (_, &PatternKind::Binding { subpattern: Some(ref s), .. }) => {
61                 s.fold_with(self)
62             }
63             _ => pat.super_fold_with(self)
64         }
65     }
66 }
67
68 impl<'tcx> Pattern<'tcx> {
69     fn is_wildcard(&self) -> bool {
70         match *self.kind {
71             PatternKind::Binding { subpattern: None, .. } | PatternKind::Wild =>
72                 true,
73             _ => false
74         }
75     }
76 }
77
78 pub struct Matrix<'a, 'tcx: 'a>(Vec<Vec<&'a Pattern<'tcx>>>);
79
80 impl<'a, 'tcx> Matrix<'a, 'tcx> {
81     pub fn empty() -> Self {
82         Matrix(vec![])
83     }
84
85     pub fn push(&mut self, row: Vec<&'a Pattern<'tcx>>) {
86         self.0.push(row)
87     }
88 }
89
90 /// Pretty-printer for matrices of patterns, example:
91 /// ++++++++++++++++++++++++++
92 /// + _     + []             +
93 /// ++++++++++++++++++++++++++
94 /// + true  + [First]        +
95 /// ++++++++++++++++++++++++++
96 /// + true  + [Second(true)] +
97 /// ++++++++++++++++++++++++++
98 /// + false + [_]            +
99 /// ++++++++++++++++++++++++++
100 /// + _     + [_, _, ..tail] +
101 /// ++++++++++++++++++++++++++
102 impl<'a, 'tcx> fmt::Debug for Matrix<'a, 'tcx> {
103     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
104         write!(f, "\n")?;
105
106         let &Matrix(ref m) = self;
107         let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| {
108             row.iter().map(|pat| format!("{:?}", pat)).collect()
109         }).collect();
110
111         let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0);
112         assert!(m.iter().all(|row| row.len() == column_count));
113         let column_widths: Vec<usize> = (0..column_count).map(|col| {
114             pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0)
115         }).collect();
116
117         let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1;
118         let br = "+".repeat(total_width);
119         write!(f, "{}\n", br)?;
120         for row in pretty_printed_matrix {
121             write!(f, "+")?;
122             for (column, pat_str) in row.into_iter().enumerate() {
123                 write!(f, " ")?;
124                 write!(f, "{:1$}", pat_str, column_widths[column])?;
125                 write!(f, " +")?;
126             }
127             write!(f, "\n")?;
128             write!(f, "{}\n", br)?;
129         }
130         Ok(())
131     }
132 }
133
134 impl<'a, 'tcx> FromIterator<Vec<&'a Pattern<'tcx>>> for Matrix<'a, 'tcx> {
135     fn from_iter<T: IntoIterator<Item=Vec<&'a Pattern<'tcx>>>>(iter: T) -> Self
136     {
137         Matrix(iter.into_iter().collect())
138     }
139 }
140
141 //NOTE: appears to be the only place other then InferCtxt to contain a ParamEnv
142 pub struct MatchCheckCtxt<'a, 'tcx: 'a> {
143     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
144     /// The module in which the match occurs. This is necessary for
145     /// checking inhabited-ness of types because whether a type is (visibly)
146     /// inhabited can depend on whether it was defined in the current module or
147     /// not. eg. `struct Foo { _private: ! }` cannot be seen to be empty
148     /// outside it's module and should not be matchable with an empty match
149     /// statement.
150     pub module: DefId,
151     pub pattern_arena: &'a TypedArena<Pattern<'tcx>>,
152     pub byte_array_map: FxHashMap<*const Pattern<'tcx>, Vec<&'a Pattern<'tcx>>>,
153 }
154
155 impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> {
156     pub fn create_and_enter<F, R>(
157         tcx: TyCtxt<'a, 'tcx, 'tcx>,
158         module: DefId,
159         f: F) -> R
160         where F: for<'b> FnOnce(MatchCheckCtxt<'b, 'tcx>) -> R
161     {
162         let pattern_arena = TypedArena::new();
163
164         f(MatchCheckCtxt {
165             tcx,
166             module,
167             pattern_arena: &pattern_arena,
168             byte_array_map: FxHashMap(),
169         })
170     }
171
172     // convert a byte-string pattern to a list of u8 patterns.
173     fn lower_byte_str_pattern<'p>(&mut self, pat: &'p Pattern<'tcx>) -> Vec<&'p Pattern<'tcx>>
174             where 'a: 'p
175     {
176         let pattern_arena = &*self.pattern_arena;
177         let tcx = self.tcx;
178         self.byte_array_map.entry(pat).or_insert_with(|| {
179             match pat.kind {
180                 box PatternKind::Constant {
181                     value: const_val
182                 } => {
183                     if let Some(ptr) = const_val.to_ptr() {
184                         let is_array_ptr = const_val.ty
185                             .builtin_deref(true)
186                             .and_then(|t| t.ty.builtin_index())
187                             .map_or(false, |t| t == tcx.types.u8);
188                         assert!(is_array_ptr);
189                         let alloc = tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
190                         assert_eq!(ptr.offset.bytes(), 0);
191                         // FIXME: check length
192                         alloc.bytes.iter().map(|b| {
193                             &*pattern_arena.alloc(Pattern {
194                                 ty: tcx.types.u8,
195                                 span: pat.span,
196                                 kind: box PatternKind::Constant {
197                                     value: ty::Const::from_bits(
198                                         tcx,
199                                         *b as u128,
200                                         ty::ParamEnv::empty().and(tcx.types.u8))
201                                 }
202                             })
203                         }).collect()
204                     } else {
205                         bug!("not a byte str: {:?}", const_val)
206                     }
207                 }
208                 _ => span_bug!(pat.span, "unexpected byte array pattern {:?}", pat)
209             }
210         }).clone()
211     }
212
213     fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool {
214         if self.tcx.features().exhaustive_patterns {
215             self.tcx.is_ty_uninhabited_from(self.module, ty)
216         } else {
217             false
218         }
219     }
220
221     fn is_non_exhaustive_enum(&self, ty: Ty<'tcx>) -> bool {
222         match ty.sty {
223             ty::TyAdt(adt_def, ..) => adt_def.is_enum() && adt_def.is_non_exhaustive(),
224             _ => false,
225         }
226     }
227
228     fn is_local(&self, ty: Ty<'tcx>) -> bool {
229         match ty.sty {
230             ty::TyAdt(adt_def, ..) => adt_def.did.is_local(),
231             _ => false,
232         }
233     }
234
235     fn is_variant_uninhabited(&self,
236                               variant: &'tcx ty::VariantDef,
237                               substs: &'tcx ty::subst::Substs<'tcx>)
238                               -> bool
239     {
240         if self.tcx.features().exhaustive_patterns {
241             self.tcx.is_enum_variant_uninhabited_from(self.module, variant, substs)
242         } else {
243             false
244         }
245     }
246 }
247
248 #[derive(Clone, Debug, PartialEq)]
249 pub enum Constructor<'tcx> {
250     /// The constructor of all patterns that don't vary by constructor,
251     /// e.g. struct patterns and fixed-length arrays.
252     Single,
253     /// Enum variants.
254     Variant(DefId),
255     /// Literal values.
256     ConstantValue(&'tcx ty::Const<'tcx>),
257     /// Ranges of literal values (`2...5` and `2..5`).
258     ConstantRange(&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>, RangeEnd),
259     /// Array patterns of length n.
260     Slice(u64),
261 }
262
263 impl<'tcx> Constructor<'tcx> {
264     fn variant_index_for_adt(&self, adt: &'tcx ty::AdtDef) -> usize {
265         match self {
266             &Variant(vid) => adt.variant_index_with_id(vid),
267             &Single => {
268                 assert!(!adt.is_enum());
269                 0
270             }
271             _ => bug!("bad constructor {:?} for adt {:?}", self, adt)
272         }
273     }
274 }
275
276 #[derive(Clone, Debug)]
277 pub enum Usefulness<'tcx> {
278     Useful,
279     UsefulWithWitness(Vec<Witness<'tcx>>),
280     NotUseful
281 }
282
283 impl<'tcx> Usefulness<'tcx> {
284     fn is_useful(&self) -> bool {
285         match *self {
286             NotUseful => false,
287             _ => true
288         }
289     }
290 }
291
292 #[derive(Copy, Clone)]
293 pub enum WitnessPreference {
294     ConstructWitness,
295     LeaveOutWitness
296 }
297
298 #[derive(Copy, Clone, Debug)]
299 struct PatternContext<'tcx> {
300     ty: Ty<'tcx>,
301     max_slice_length: u64,
302 }
303
304 /// A stack of patterns in reverse order of construction
305 #[derive(Clone)]
306 pub struct Witness<'tcx>(Vec<Pattern<'tcx>>);
307
308 impl<'tcx> Witness<'tcx> {
309     pub fn single_pattern(&self) -> &Pattern<'tcx> {
310         assert_eq!(self.0.len(), 1);
311         &self.0[0]
312     }
313
314     fn push_wild_constructor<'a>(
315         mut self,
316         cx: &MatchCheckCtxt<'a, 'tcx>,
317         ctor: &Constructor<'tcx>,
318         ty: Ty<'tcx>)
319         -> Self
320     {
321         let sub_pattern_tys = constructor_sub_pattern_tys(cx, ctor, ty);
322         self.0.extend(sub_pattern_tys.into_iter().map(|ty| {
323             Pattern {
324                 ty,
325                 span: DUMMY_SP,
326                 kind: box PatternKind::Wild,
327             }
328         }));
329         self.apply_constructor(cx, ctor, ty)
330     }
331
332
333     /// Constructs a partial witness for a pattern given a list of
334     /// patterns expanded by the specialization step.
335     ///
336     /// When a pattern P is discovered to be useful, this function is used bottom-up
337     /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
338     /// of values, V, where each value in that set is not covered by any previously
339     /// used patterns and is covered by the pattern P'. Examples:
340     ///
341     /// left_ty: tuple of 3 elements
342     /// pats: [10, 20, _]           => (10, 20, _)
343     ///
344     /// left_ty: struct X { a: (bool, &'static str), b: usize}
345     /// pats: [(false, "foo"), 42]  => X { a: (false, "foo"), b: 42 }
346     fn apply_constructor<'a>(
347         mut self,
348         cx: &MatchCheckCtxt<'a,'tcx>,
349         ctor: &Constructor<'tcx>,
350         ty: Ty<'tcx>)
351         -> Self
352     {
353         let arity = constructor_arity(cx, ctor, ty);
354         let pat = {
355             let len = self.0.len() as u64;
356             let mut pats = self.0.drain((len-arity) as usize..).rev();
357
358             match ty.sty {
359                 ty::TyAdt(..) |
360                 ty::TyTuple(..) => {
361                     let pats = pats.enumerate().map(|(i, p)| {
362                         FieldPattern {
363                             field: Field::new(i),
364                             pattern: p
365                         }
366                     }).collect();
367
368                     if let ty::TyAdt(adt, substs) = ty.sty {
369                         if adt.is_enum() {
370                             PatternKind::Variant {
371                                 adt_def: adt,
372                                 substs,
373                                 variant_index: ctor.variant_index_for_adt(adt),
374                                 subpatterns: pats
375                             }
376                         } else {
377                             PatternKind::Leaf { subpatterns: pats }
378                         }
379                     } else {
380                         PatternKind::Leaf { subpatterns: pats }
381                     }
382                 }
383
384                 ty::TyRef(..) => {
385                     PatternKind::Deref { subpattern: pats.nth(0).unwrap() }
386                 }
387
388                 ty::TySlice(_) | ty::TyArray(..) => {
389                     PatternKind::Slice {
390                         prefix: pats.collect(),
391                         slice: None,
392                         suffix: vec![]
393                     }
394                 }
395
396                 _ => {
397                     match *ctor {
398                         ConstantValue(value) => PatternKind::Constant { value },
399                         _ => PatternKind::Wild,
400                     }
401                 }
402             }
403         };
404
405         self.0.push(Pattern {
406             ty,
407             span: DUMMY_SP,
408             kind: Box::new(pat),
409         });
410
411         self
412     }
413 }
414
415 /// This determines the set of all possible constructors of a pattern matching
416 /// values of type `left_ty`. For vectors, this would normally be an infinite set
417 /// but is instead bounded by the maximum fixed length of slice patterns in
418 /// the column of patterns being analyzed.
419 ///
420 /// This intentionally does not list ConstantValue specializations for
421 /// non-booleans, because we currently assume that there is always a
422 /// "non-standard constant" that matches. See issue #12483.
423 ///
424 /// We make sure to omit constructors that are statically impossible. eg for
425 /// Option<!> we do not include Some(_) in the returned list of constructors.
426 fn all_constructors<'a, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
427                                   pcx: PatternContext<'tcx>)
428                                   -> (Vec<Constructor<'tcx>>, bool)
429 {
430     debug!("all_constructors({:?})", pcx.ty);
431     (match pcx.ty.sty {
432         ty::TyBool => {
433             [true, false].iter().map(|&b| {
434                 ConstantValue(ty::Const::from_bool(cx.tcx, b))
435             }).collect()
436         }
437         ty::TyArray(ref sub_ty, len) if len.assert_usize(cx.tcx).is_some() => {
438             let len = len.unwrap_usize(cx.tcx);
439             if len != 0 && cx.is_uninhabited(sub_ty) {
440                 vec![]
441             } else {
442                 vec![Slice(len)]
443             }
444         }
445         // Treat arrays of a constant but unknown length like slices.
446         ty::TyArray(ref sub_ty, _) |
447         ty::TySlice(ref sub_ty) => {
448             if cx.is_uninhabited(sub_ty) {
449                 vec![Slice(0)]
450             } else {
451                 (0..pcx.max_slice_length+1).map(|length| Slice(length)).collect()
452             }
453         }
454         ty::TyAdt(def, substs) if def.is_enum() => {
455             def.variants.iter()
456                 .filter(|v| !cx.is_variant_uninhabited(v, substs))
457                 .map(|v| Variant(v.did))
458                 .collect()
459         }
460         ty::TyUint(ast::UintTy::Usize) => {
461             return (vec![
462                 ConstantRange(ty::Const::from_usize(cx.tcx, 0),
463                               ty::Const::from_usize(cx.tcx, 100),
464                               RangeEnd::Excluded),
465             ], true)
466         }
467         _ => {
468             if cx.is_uninhabited(pcx.ty) {
469                 vec![]
470             } else {
471                 vec![Single]
472             }
473         }
474     }, false)
475 }
476
477 fn max_slice_length<'p, 'a: 'p, 'tcx: 'a, I>(
478     cx: &mut MatchCheckCtxt<'a, 'tcx>,
479     patterns: I) -> u64
480     where I: Iterator<Item=&'p Pattern<'tcx>>
481 {
482     // The exhaustiveness-checking paper does not include any details on
483     // checking variable-length slice patterns. However, they are matched
484     // by an infinite collection of fixed-length array patterns.
485     //
486     // Checking the infinite set directly would take an infinite amount
487     // of time. However, it turns out that for each finite set of
488     // patterns `P`, all sufficiently large array lengths are equivalent:
489     //
490     // Each slice `s` with a "sufficiently-large" length `l â‰¥ L` that applies
491     // to exactly the subset `Pâ‚œ` of `P` can be transformed to a slice
492     // `sₘ` for each sufficiently-large length `m` that applies to exactly
493     // the same subset of `P`.
494     //
495     // Because of that, each witness for reachability-checking from one
496     // of the sufficiently-large lengths can be transformed to an
497     // equally-valid witness from any other length, so we only have
498     // to check slice lengths from the "minimal sufficiently-large length"
499     // and below.
500     //
501     // Note that the fact that there is a *single* `sₘ` for each `m`
502     // not depending on the specific pattern in `P` is important: if
503     // you look at the pair of patterns
504     //     `[true, ..]`
505     //     `[.., false]`
506     // Then any slice of length â‰¥1 that matches one of these two
507     // patterns can be  be trivially turned to a slice of any
508     // other length â‰¥1 that matches them and vice-versa - for
509     // but the slice from length 2 `[false, true]` that matches neither
510     // of these patterns can't be turned to a slice from length 1 that
511     // matches neither of these patterns, so we have to consider
512     // slices from length 2 there.
513     //
514     // Now, to see that that length exists and find it, observe that slice
515     // patterns are either "fixed-length" patterns (`[_, _, _]`) or
516     // "variable-length" patterns (`[_, .., _]`).
517     //
518     // For fixed-length patterns, all slices with lengths *longer* than
519     // the pattern's length have the same outcome (of not matching), so
520     // as long as `L` is greater than the pattern's length we can pick
521     // any `sₘ` from that length and get the same result.
522     //
523     // For variable-length patterns, the situation is more complicated,
524     // because as seen above the precise value of `sₘ` matters.
525     //
526     // However, for each variable-length pattern `p` with a prefix of length
527     // `plâ‚š` and suffix of length `slâ‚š`, only the first `plâ‚š` and the last
528     // `slâ‚š` elements are examined.
529     //
530     // Therefore, as long as `L` is positive (to avoid concerns about empty
531     // types), all elements after the maximum prefix length and before
532     // the maximum suffix length are not examined by any variable-length
533     // pattern, and therefore can be added/removed without affecting
534     // them - creating equivalent patterns from any sufficiently-large
535     // length.
536     //
537     // Of course, if fixed-length patterns exist, we must be sure
538     // that our length is large enough to miss them all, so
539     // we can pick `L = max(FIXED_LEN+1 âˆª {max(PREFIX_LEN) + max(SUFFIX_LEN)})`
540     //
541     // for example, with the above pair of patterns, all elements
542     // but the first and last can be added/removed, so any
543     // witness of length â‰¥2 (say, `[false, false, true]`) can be
544     // turned to a witness from any other length â‰¥2.
545
546     let mut max_prefix_len = 0;
547     let mut max_suffix_len = 0;
548     let mut max_fixed_len = 0;
549
550     for row in patterns {
551         match *row.kind {
552             PatternKind::Constant { value } => {
553                 if let Some(ptr) = value.to_ptr() {
554                     let is_array_ptr = value.ty
555                         .builtin_deref(true)
556                         .and_then(|t| t.ty.builtin_index())
557                         .map_or(false, |t| t == cx.tcx.types.u8);
558                     if is_array_ptr {
559                         let alloc = cx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
560                         max_fixed_len = cmp::max(max_fixed_len, alloc.bytes.len() as u64);
561                     }
562                 }
563             }
564             PatternKind::Slice { ref prefix, slice: None, ref suffix } => {
565                 let fixed_len = prefix.len() as u64 + suffix.len() as u64;
566                 max_fixed_len = cmp::max(max_fixed_len, fixed_len);
567             }
568             PatternKind::Slice { ref prefix, slice: Some(_), ref suffix } => {
569                 max_prefix_len = cmp::max(max_prefix_len, prefix.len() as u64);
570                 max_suffix_len = cmp::max(max_suffix_len, suffix.len() as u64);
571             }
572             _ => {}
573         }
574     }
575
576     cmp::max(max_fixed_len + 1, max_prefix_len + max_suffix_len)
577 }
578
579 /// Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
580 /// The algorithm from the paper has been modified to correctly handle empty
581 /// types. The changes are:
582 ///   (0) We don't exit early if the pattern matrix has zero rows. We just
583 ///       continue to recurse over columns.
584 ///   (1) all_constructors will only return constructors that are statically
585 ///       possible. eg. it will only return Ok for Result<T, !>
586 ///
587 /// This finds whether a (row) vector `v` of patterns is 'useful' in relation
588 /// to a set of such vectors `m` - this is defined as there being a set of
589 /// inputs that will match `v` but not any of the sets in `m`.
590 ///
591 /// All the patterns at each column of the `matrix ++ v` matrix must
592 /// have the same type, except that wildcard (PatternKind::Wild) patterns
593 /// with type TyErr are also allowed, even if the "type of the column"
594 /// is not TyErr. That is used to represent private fields, as using their
595 /// real type would assert that they are inhabited.
596 ///
597 /// This is used both for reachability checking (if a pattern isn't useful in
598 /// relation to preceding patterns, it is not reachable) and exhaustiveness
599 /// checking (if a wildcard pattern is useful in relation to a matrix, the
600 /// matrix isn't exhaustive).
601 pub fn is_useful<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
602                                        matrix: &Matrix<'p, 'tcx>,
603                                        v: &[&'p Pattern<'tcx>],
604                                        witness: WitnessPreference)
605                                        -> Usefulness<'tcx> {
606     let &Matrix(ref rows) = matrix;
607     debug!("is_useful({:#?}, {:#?})", matrix, v);
608
609     // The base case. We are pattern-matching on () and the return value is
610     // based on whether our matrix has a row or not.
611     // NOTE: This could potentially be optimized by checking rows.is_empty()
612     // first and then, if v is non-empty, the return value is based on whether
613     // the type of the tuple we're checking is inhabited or not.
614     if v.is_empty() {
615         return if rows.is_empty() {
616             match witness {
617                 ConstructWitness => UsefulWithWitness(vec![Witness(vec![])]),
618                 LeaveOutWitness => Useful,
619             }
620         } else {
621             NotUseful
622         }
623     };
624
625     assert!(rows.iter().all(|r| r.len() == v.len()));
626
627     let pcx = PatternContext {
628         // TyErr is used to represent the type of wildcard patterns matching
629         // against inaccessible (private) fields of structs, so that we won't
630         // be able to observe whether the types of the struct's fields are
631         // inhabited.
632         //
633         // If the field is truly inaccessible, then all the patterns
634         // matching against it must be wildcard patterns, so its type
635         // does not matter.
636         //
637         // However, if we are matching against non-wildcard patterns, we
638         // need to know the real type of the field so we can specialize
639         // against it. This primarily occurs through constants - they
640         // can include contents for fields that are inaccessible at the
641         // location of the match. In that case, the field's type is
642         // inhabited - by the constant - so we can just use it.
643         //
644         // FIXME: this might lead to "unstable" behavior with macro hygiene
645         // introducing uninhabited patterns for inaccessible fields. We
646         // need to figure out how to model that.
647         ty: rows.iter().map(|r| r[0].ty).find(|ty| !ty.references_error())
648             .unwrap_or(v[0].ty),
649         max_slice_length: max_slice_length(cx, rows.iter().map(|r| r[0]).chain(Some(v[0])))
650     };
651
652     debug!("is_useful_expand_first_col: pcx={:#?}, expanding {:#?}", pcx, v[0]);
653
654     if let Some(constructors) = pat_constructors(cx, v[0], pcx) {
655         debug!("is_useful - expanding constructors: {:#?}", constructors);
656         constructors.into_iter().map(|c|
657             is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness)
658         ).find(|result| result.is_useful()).unwrap_or(NotUseful)
659     } else {
660         debug!("is_useful - expanding wildcard");
661
662         let used_ctors: Vec<Constructor> = rows.iter().flat_map(|row| {
663             pat_constructors(cx, row[0], pcx).unwrap_or(vec![])
664         }).collect();
665         debug!("used_ctors = {:#?}", used_ctors);
666         let (all_ctors, _ranged) = all_constructors(cx, pcx);
667         debug!("all_ctors = {:#?}", all_ctors);
668
669         fn to_inc_range_pair<'tcx>(tcx: TyCtxt<'_, '_, '_>, ctor: &Constructor<'tcx>) -> Option<(u64, u64)> {
670             match ctor {
671                 Single | Variant(_) | Slice(_) => {
672                     None
673                 }
674                 ConstantValue(const_) => {
675                     if let Some(val) = const_.assert_usize(tcx) {
676                         return Some((val, val));
677                     }
678                     None
679                 }
680                 ConstantRange(lo, hi, end) => {
681                     if let Some(lo) = lo.assert_usize(tcx) {
682                         if let Some(hi) = hi.assert_usize(tcx) {
683                             if lo > hi || lo == hi && end == &RangeEnd::Excluded {
684                                 return None;
685                             } else if end == &RangeEnd::Included {
686                                 return Some((lo, hi));
687                             } else {
688                                 return Some((lo, hi - 1));
689                             }
690                         }
691                     }
692                     None
693                 }
694             }
695         }
696
697         fn intersect<'a, 'tcx>(
698                     _deb: bool,
699                     cx: &mut MatchCheckCtxt<'a, 'tcx>,
700                     ranges: Vec<Constructor<'tcx>>,
701                      ctor: &Constructor<'tcx>)
702                      -> (Vec<Constructor<'tcx>>, bool) {
703             if let Some((lo1, hi1)) = to_inc_range_pair(cx.tcx, ctor) {
704                 let mut ctor_was_useful = false;
705                 // values only consists of ranges
706                 let mut new_ranges = vec![];
707                 let mut ranges: Vec<_> =
708                     ranges.into_iter().filter_map(|r| to_inc_range_pair(cx.tcx, &r)).collect();
709                 while let Some((lo2, hi2)) = ranges.pop() {
710                     eprintln!("{:?} {:?}", (lo2, hi2), (lo1, hi1));
711                     if lo1 <= lo2 && hi1 >= hi2 {
712                         if _deb { eprintln!("case 1"); }
713                         ctor_was_useful = true;
714                         continue;
715                     }
716                     if lo1 > hi2 || hi1 < lo2 {
717                         if _deb { eprintln!("case 2"); }
718                         new_ranges.push((lo2, hi2));
719                         continue;
720                     }
721                     if lo1 <= lo2 {
722                         if _deb { eprintln!("case 3"); }
723                         ctor_was_useful = true;
724                         if (hi1 + 1, hi2) == (lo2, hi2) {
725                             new_ranges.push((hi1 + 1, hi2));
726                         } else {
727                             ranges.push((hi1 + 1, hi2));
728                         }
729                         continue;
730                     }
731                     if hi1 >= hi2 {
732                         if _deb { eprintln!("case 4"); }
733                         ctor_was_useful = true;
734                         if (lo2, lo1 - 1) == (lo2, hi2) {
735                             new_ranges.push((lo2, lo1 - 1));
736                         } else {
737                             ranges.push((lo2, lo1 - 1));
738                         }
739                         continue;
740                     }
741                     ctor_was_useful = true;
742                     ranges.push((lo2, lo1));
743                     ranges.push((hi1, hi2));
744                     if _deb { eprintln!("case 5"); }
745                 }
746                 // transform ranges to proper format
747                 (new_ranges.into_iter().map(|(lo, hi)| {
748                     ConstantRange(ty::Const::from_usize(cx.tcx, lo),
749                                 ty::Const::from_usize(cx.tcx, hi),
750                                 RangeEnd::Included)
751                 }).collect(), ctor_was_useful)
752             } else {
753                 (ranges, false)
754             }
755         }
756
757         // `used_ctors` are all the constructors that appear in patterns (must check if guards)
758         // `all_ctors` are all the necessary constructors
759         let mut missing_ctors = vec![];
760         let mut all_actual_ctors = vec![];
761         'req: for req_ctor in all_ctors.clone() {
762             if _deb {
763                 eprintln!("req_ctor before {:?}", req_ctor);
764             }
765             let mut cur = vec![req_ctor.clone()];
766             for used_ctor in &used_ctors {
767                 if _deb {
768                     eprintln!("cut {:?}", used_ctor);
769                 }
770                 if cur.iter().all(|ctor| {
771                     match ctor {
772                         ConstantRange(..) => true,
773                         _ => false,
774                     }
775                 }) {
776                     let (cur2, ctor_was_useful) = intersect(_deb, cx, cur, used_ctor);
777                     cur = cur2;
778                     if ctor_was_useful {
779                         all_actual_ctors.push(used_ctor.clone());
780                     }
781                     if cur.is_empty() {
782                         continue 'req;
783                     }
784                 } else {
785                     if used_ctor == &req_ctor {
786                         continue 'req;
787                     }
788                 }
789             }
790             if _deb {
791                 eprintln!("req_ctor after {:?}", cur);
792             }
793             missing_ctors.extend(cur);
794         }
795
796         // let missing_ctors: Vec<Constructor> = all_ctors.iter().filter(|c| {
797         //     !used_ctors.contains(*c)
798         // }).cloned().collect();
799
800         if _deb {
801             eprintln!("used_ctors {:?}", used_ctors);
802             eprintln!("missing_ctors {:?}", missing_ctors);
803         }
804
805         // if !all_actual_ctors.is_empty() {
806         //     all_ctors = all_actual_ctors;
807         // }
808
809         // `missing_ctors` is the set of constructors from the same type as the
810         // first column of `matrix` that are matched only by wildcard patterns
811         // from the first column.
812         //
813         // Therefore, if there is some pattern that is unmatched by `matrix`,
814         // it will still be unmatched if the first constructor is replaced by
815         // any of the constructors in `missing_ctors`
816         //
817         // However, if our scrutinee is *privately* an empty enum, we
818         // must treat it as though it had an "unknown" constructor (in
819         // that case, all other patterns obviously can't be variants)
820         // to avoid exposing its emptyness. See the `match_privately_empty`
821         // test for details.
822         //
823         // FIXME: currently the only way I know of something can
824         // be a privately-empty enum is when the exhaustive_patterns
825         // feature flag is not present, so this is only
826         // needed for that case.
827
828         let is_privately_empty =
829             all_ctors.is_empty() && !cx.is_uninhabited(pcx.ty);
830         let is_declared_nonexhaustive =
831             cx.is_non_exhaustive_enum(pcx.ty) && !cx.is_local(pcx.ty);
832         debug!("missing_ctors={:#?} is_privately_empty={:#?} is_declared_nonexhaustive={:#?}",
833                missing_ctors, is_privately_empty, is_declared_nonexhaustive);
834
835         // For privately empty and non-exhaustive enums, we work as if there were an "extra"
836         // `_` constructor for the type, so we can never match over all constructors.
837         let is_non_exhaustive = is_privately_empty || is_declared_nonexhaustive;
838
839         if missing_ctors.is_empty() && !is_non_exhaustive {
840             if _ranged && _deb {
841                 return NotUseful;
842             }
843             let z = all_ctors.into_iter().map(|c| {
844                 is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness)
845             }).find(|result| result.is_useful()).unwrap_or(NotUseful);
846             if _deb { eprintln!("ABC 1 {:?}", z); }
847             z
848         } else {
849             if _deb { eprintln!("ABC 2"); }
850             let matrix = rows.iter().filter_map(|r| {
851                 if r[0].is_wildcard() {
852                     Some(r[1..].to_vec())
853                 } else {
854                     None
855                 }
856             }).collect();
857             match is_useful(cx, &matrix, &v[1..], witness) {
858                 UsefulWithWitness(pats) => {
859                     if _deb { eprintln!("ABC 3"); }
860                     let cx = &*cx;
861                     // In this case, there's at least one "free"
862                     // constructor that is only matched against by
863                     // wildcard patterns.
864                     //
865                     // There are 2 ways we can report a witness here.
866                     // Commonly, we can report all the "free"
867                     // constructors as witnesses, e.g. if we have:
868                     //
869                     // ```
870                     //     enum Direction { N, S, E, W }
871                     //     let Direction::N = ...;
872                     // ```
873                     //
874                     // we can report 3 witnesses: `S`, `E`, and `W`.
875                     //
876                     // However, there are 2 cases where we don't want
877                     // to do this and instead report a single `_` witness:
878                     //
879                     // 1) If the user is matching against a non-exhaustive
880                     // enum, there is no point in enumerating all possible
881                     // variants, because the user can't actually match
882                     // against them himself, e.g. in an example like:
883                     // ```
884                     //     let err: io::ErrorKind = ...;
885                     //     match err {
886                     //         io::ErrorKind::NotFound => {},
887                     //     }
888                     // ```
889                     // we don't want to show every possible IO error,
890                     // but instead have `_` as the witness (this is
891                     // actually *required* if the user specified *all*
892                     // IO errors, but is probably what we want in every
893                     // case).
894                     //
895                     // 2) If the user didn't actually specify a constructor
896                     // in this arm, e.g. in
897                     // ```
898                     //     let x: (Direction, Direction, bool) = ...;
899                     //     let (_, _, false) = x;
900                     // ```
901                     // we don't want to show all 16 possible witnesses
902                     // `(<direction-1>, <direction-2>, true)` - we are
903                     // satisfied with `(_, _, true)`. In this case,
904                     // `used_ctors` is empty.
905                     let new_witnesses = if is_non_exhaustive || used_ctors.is_empty() {
906                         if _deb { eprintln!("ABC 4"); }
907                         // All constructors are unused. Add wild patterns
908                         // rather than each individual constructor
909                         pats.into_iter().map(|mut witness| {
910                             witness.0.push(Pattern {
911                                 ty: pcx.ty,
912                                 span: DUMMY_SP,
913                                 kind: box PatternKind::Wild,
914                             });
915                             witness
916                         }).collect()
917                     } else {
918                         if _deb { eprintln!("ABC 5"); }
919                         pats.into_iter().flat_map(|witness| {
920                             missing_ctors.iter().map(move |ctor| {
921                                 witness.clone().push_wild_constructor(cx, ctor, pcx.ty)
922                             })
923                         }).collect()
924                     };
925                     UsefulWithWitness(new_witnesses)
926                 }
927                 result => result
928             }
929         }
930     }
931 }
932
933 fn is_useful_specialized<'p, 'a:'p, 'tcx: 'a>(
934     cx: &mut MatchCheckCtxt<'a, 'tcx>,
935     &Matrix(ref m): &Matrix<'p, 'tcx>,
936     v: &[&'p Pattern<'tcx>],
937     ctor: Constructor<'tcx>,
938     lty: Ty<'tcx>,
939     witness: WitnessPreference) -> Usefulness<'tcx>
940 {
941     debug!("is_useful_specialized({:#?}, {:#?}, {:?})", v, ctor, lty);
942     let sub_pat_tys = constructor_sub_pattern_tys(cx, &ctor, lty);
943     let wild_patterns_owned: Vec<_> = sub_pat_tys.iter().map(|ty| {
944         Pattern {
945             ty,
946             span: DUMMY_SP,
947             kind: box PatternKind::Wild,
948         }
949     }).collect();
950     let wild_patterns: Vec<_> = wild_patterns_owned.iter().collect();
951     let matrix = Matrix(m.iter().flat_map(|r| {
952         specialize(cx, &r, &ctor, &wild_patterns)
953     }).collect());
954     match specialize(cx, v, &ctor, &wild_patterns) {
955         Some(v) => match is_useful(cx, &matrix, &v, witness) {
956             UsefulWithWitness(witnesses) => UsefulWithWitness(
957                 witnesses.into_iter()
958                     .map(|witness| witness.apply_constructor(cx, &ctor, lty))
959                     .collect()
960             ),
961             result => result
962         },
963         None => NotUseful
964     }
965 }
966
967 /// Determines the constructors that the given pattern can be specialized to.
968 ///
969 /// In most cases, there's only one constructor that a specific pattern
970 /// represents, such as a specific enum variant or a specific literal value.
971 /// Slice patterns, however, can match slices of different lengths. For instance,
972 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
973 ///
974 /// Returns None in case of a catch-all, which can't be specialized.
975 fn pat_constructors<'tcx>(cx: &mut MatchCheckCtxt,
976                           pat: &Pattern<'tcx>,
977                           pcx: PatternContext)
978                           -> Option<Vec<Constructor<'tcx>>>
979 {
980     match *pat.kind {
981         PatternKind::Binding { .. } | PatternKind::Wild =>
982             None,
983         PatternKind::Leaf { .. } | PatternKind::Deref { .. } =>
984             Some(vec![Single]),
985         PatternKind::Variant { adt_def, variant_index, .. } =>
986             Some(vec![Variant(adt_def.variants[variant_index].did)]),
987         PatternKind::Constant { value } =>
988             Some(vec![ConstantValue(value)]),
989         PatternKind::Range { lo, hi, end } =>
990             Some(vec![ConstantRange(lo, hi, end)]),
991         PatternKind::Array { .. } => match pcx.ty.sty {
992             ty::TyArray(_, length) => Some(vec![
993                 Slice(length.unwrap_usize(cx.tcx))
994             ]),
995             _ => span_bug!(pat.span, "bad ty {:?} for array pattern", pcx.ty)
996         },
997         PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
998             let pat_len = prefix.len() as u64 + suffix.len() as u64;
999             if slice.is_some() {
1000                 Some((pat_len..pcx.max_slice_length+1).map(Slice).collect())
1001             } else {
1002                 Some(vec![Slice(pat_len)])
1003             }
1004         }
1005     }
1006 }
1007
1008 /// This computes the arity of a constructor. The arity of a constructor
1009 /// is how many subpattern patterns of that constructor should be expanded to.
1010 ///
1011 /// For instance, a tuple pattern (_, 42, Some([])) has the arity of 3.
1012 /// A struct pattern's arity is the number of fields it contains, etc.
1013 fn constructor_arity(_cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> u64 {
1014     debug!("constructor_arity({:#?}, {:?})", ctor, ty);
1015     match ty.sty {
1016         ty::TyTuple(ref fs) => fs.len() as u64,
1017         ty::TySlice(..) | ty::TyArray(..) => match *ctor {
1018             Slice(length) => length,
1019             ConstantValue(_) => 0,
1020             _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
1021         },
1022         ty::TyRef(..) => 1,
1023         ty::TyAdt(adt, _) => {
1024             adt.variants[ctor.variant_index_for_adt(adt)].fields.len() as u64
1025         }
1026         _ => 0
1027     }
1028 }
1029
1030 /// This computes the types of the sub patterns that a constructor should be
1031 /// expanded to.
1032 ///
1033 /// For instance, a tuple pattern (43u32, 'a') has sub pattern types [u32, char].
1034 fn constructor_sub_pattern_tys<'a, 'tcx: 'a>(cx: &MatchCheckCtxt<'a, 'tcx>,
1035                                              ctor: &Constructor,
1036                                              ty: Ty<'tcx>) -> Vec<Ty<'tcx>>
1037 {
1038     debug!("constructor_sub_pattern_tys({:#?}, {:?})", ctor, ty);
1039     match ty.sty {
1040         ty::TyTuple(ref fs) => fs.into_iter().map(|t| *t).collect(),
1041         ty::TySlice(ty) | ty::TyArray(ty, _) => match *ctor {
1042             Slice(length) => (0..length).map(|_| ty).collect(),
1043             ConstantValue(_) => vec![],
1044             _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
1045         },
1046         ty::TyRef(_, rty, _) => vec![rty],
1047         ty::TyAdt(adt, substs) => {
1048             if adt.is_box() {
1049                 // Use T as the sub pattern type of Box<T>.
1050                 vec![substs.type_at(0)]
1051             } else {
1052                 adt.variants[ctor.variant_index_for_adt(adt)].fields.iter().map(|field| {
1053                     let is_visible = adt.is_enum()
1054                         || field.vis.is_accessible_from(cx.module, cx.tcx);
1055                     if is_visible {
1056                         field.ty(cx.tcx, substs)
1057                     } else {
1058                         // Treat all non-visible fields as TyErr. They
1059                         // can't appear in any other pattern from
1060                         // this match (because they are private),
1061                         // so their type does not matter - but
1062                         // we don't want to know they are
1063                         // uninhabited.
1064                         cx.tcx.types.err
1065                     }
1066                 }).collect()
1067             }
1068         }
1069         _ => vec![],
1070     }
1071 }
1072
1073 fn slice_pat_covered_by_constructor<'tcx>(
1074     tcx: TyCtxt<'_, 'tcx, '_>,
1075     _span: Span,
1076     ctor: &Constructor,
1077     prefix: &[Pattern<'tcx>],
1078     slice: &Option<Pattern<'tcx>>,
1079     suffix: &[Pattern<'tcx>]
1080 ) -> Result<bool, ErrorReported> {
1081     let data: &[u8] = match *ctor {
1082         ConstantValue(const_val) => {
1083             let val = match const_val.val {
1084                 ConstValue::Unevaluated(..) |
1085                 ConstValue::ByRef(..) => bug!("unexpected ConstValue: {:?}", const_val),
1086                 ConstValue::Scalar(val) | ConstValue::ScalarPair(val, _) => val,
1087             };
1088             if let Ok(ptr) = val.to_ptr() {
1089                 let is_array_ptr = const_val.ty
1090                     .builtin_deref(true)
1091                     .and_then(|t| t.ty.builtin_index())
1092                     .map_or(false, |t| t == tcx.types.u8);
1093                 assert!(is_array_ptr);
1094                 tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id).bytes.as_ref()
1095             } else {
1096                 bug!("unexpected non-ptr ConstantValue")
1097             }
1098         }
1099         _ => bug!()
1100     };
1101
1102     let pat_len = prefix.len() + suffix.len();
1103     if data.len() < pat_len || (slice.is_none() && data.len() > pat_len) {
1104         return Ok(false);
1105     }
1106
1107     for (ch, pat) in
1108         data[..prefix.len()].iter().zip(prefix).chain(
1109             data[data.len()-suffix.len()..].iter().zip(suffix))
1110     {
1111         match pat.kind {
1112             box PatternKind::Constant { value } => {
1113                 let b = value.unwrap_bits(tcx, ty::ParamEnv::empty().and(pat.ty));
1114                 assert_eq!(b as u8 as u128, b);
1115                 if b as u8 != *ch {
1116                     return Ok(false);
1117                 }
1118             }
1119             _ => {}
1120         }
1121     }
1122
1123     Ok(true)
1124 }
1125
1126 fn constructor_covered_by_range<'a, 'tcx>(
1127     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1128     ctor: &Constructor<'tcx>,
1129     from: &'tcx ty::Const<'tcx>, to: &'tcx ty::Const<'tcx>,
1130     end: RangeEnd,
1131     ty: Ty<'tcx>,
1132 ) -> Result<bool, ErrorReported> {
1133     trace!("constructor_covered_by_range {:#?}, {:#?}, {:#?}, {}", ctor, from, to, ty);
1134     let cmp_from = |c_from| compare_const_vals(tcx, c_from, from, ty::ParamEnv::empty().and(ty))
1135         .map(|res| res != Ordering::Less);
1136     let cmp_to = |c_to| compare_const_vals(tcx, c_to, to, ty::ParamEnv::empty().and(ty));
1137     macro_rules! some_or_ok {
1138         ($e:expr) => {
1139             match $e {
1140                 Some(to) => to,
1141                 None => return Ok(false), // not char or int
1142             }
1143         };
1144     }
1145     match *ctor {
1146         ConstantValue(value) => {
1147             let to = some_or_ok!(cmp_to(value));
1148             let end = (to == Ordering::Less) ||
1149                       (end == RangeEnd::Included && to == Ordering::Equal);
1150             Ok(some_or_ok!(cmp_from(value)) && end)
1151         },
1152         ConstantRange(from, to, RangeEnd::Included) => {
1153             let to = some_or_ok!(cmp_to(to));
1154             let end = (to == Ordering::Less) ||
1155                       (end == RangeEnd::Included && to == Ordering::Equal);
1156             Ok(some_or_ok!(cmp_from(from)) && end)
1157         },
1158         ConstantRange(from, to, RangeEnd::Excluded) => {
1159             let to = some_or_ok!(cmp_to(to));
1160             let end = (to == Ordering::Less) ||
1161                       (end == RangeEnd::Excluded && to == Ordering::Equal);
1162             Ok(some_or_ok!(cmp_from(from)) && end)
1163         }
1164         Single => Ok(true),
1165         _ => bug!(),
1166     }
1167 }
1168
1169 fn patterns_for_variant<'p, 'a: 'p, 'tcx: 'a>(
1170     subpatterns: &'p [FieldPattern<'tcx>],
1171     wild_patterns: &[&'p Pattern<'tcx>])
1172     -> Vec<&'p Pattern<'tcx>>
1173 {
1174     let mut result = wild_patterns.to_owned();
1175
1176     for subpat in subpatterns {
1177         result[subpat.field.index()] = &subpat.pattern;
1178     }
1179
1180     debug!("patterns_for_variant({:#?}, {:#?}) = {:#?}", subpatterns, wild_patterns, result);
1181     result
1182 }
1183
1184 /// This is the main specialization step. It expands the first pattern in the given row
1185 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
1186 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
1187 ///
1188 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
1189 /// different patterns.
1190 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
1191 /// fields filled with wild patterns.
1192 fn specialize<'p, 'a: 'p, 'tcx: 'a>(
1193     cx: &mut MatchCheckCtxt<'a, 'tcx>,
1194     r: &[&'p Pattern<'tcx>],
1195     constructor: &Constructor<'tcx>,
1196     wild_patterns: &[&'p Pattern<'tcx>])
1197     -> Option<Vec<&'p Pattern<'tcx>>>
1198 {
1199     let pat = &r[0];
1200
1201     let head: Option<Vec<&Pattern>> = match *pat.kind {
1202         PatternKind::Binding { .. } | PatternKind::Wild => {
1203             Some(wild_patterns.to_owned())
1204         },
1205
1206         PatternKind::Variant { adt_def, variant_index, ref subpatterns, .. } => {
1207             let ref variant = adt_def.variants[variant_index];
1208             if *constructor == Variant(variant.did) {
1209                 Some(patterns_for_variant(subpatterns, wild_patterns))
1210             } else {
1211                 None
1212             }
1213         }
1214
1215         PatternKind::Leaf { ref subpatterns } => {
1216             Some(patterns_for_variant(subpatterns, wild_patterns))
1217         }
1218
1219         PatternKind::Deref { ref subpattern } => {
1220             Some(vec![subpattern])
1221         }
1222
1223         PatternKind::Constant { value } => {
1224             match *constructor {
1225                 Slice(..) => {
1226                     if let Some(ptr) = value.to_ptr() {
1227                         let is_array_ptr = value.ty
1228                             .builtin_deref(true)
1229                             .and_then(|t| t.ty.builtin_index())
1230                             .map_or(false, |t| t == cx.tcx.types.u8);
1231                         assert!(is_array_ptr);
1232                         let data_len = cx.tcx
1233                             .alloc_map
1234                             .lock()
1235                             .unwrap_memory(ptr.alloc_id)
1236                             .bytes
1237                             .len();
1238                         if wild_patterns.len() == data_len {
1239                             Some(cx.lower_byte_str_pattern(pat))
1240                         } else {
1241                             None
1242                         }
1243                     } else {
1244                         span_bug!(pat.span,
1245                         "unexpected const-val {:?} with ctor {:?}", value, constructor)
1246                     }
1247                 },
1248                 _ => {
1249                     match constructor_covered_by_range(
1250                         cx.tcx,
1251                         constructor, value, value, RangeEnd::Included,
1252                         value.ty,
1253                             ) {
1254                         Ok(true) => Some(vec![]),
1255                         Ok(false) => None,
1256                         Err(ErrorReported) => None,
1257                     }
1258                 }
1259             }
1260         }
1261
1262         PatternKind::Range { lo, hi, ref end } => {
1263             match constructor_covered_by_range(
1264                 cx.tcx,
1265                 constructor, lo, hi, end.clone(), lo.ty,
1266             ) {
1267                 Ok(true) => Some(vec![]),
1268                 Ok(false) => None,
1269                 Err(ErrorReported) => None,
1270             }
1271         }
1272
1273         PatternKind::Array { ref prefix, ref slice, ref suffix } |
1274         PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
1275             match *constructor {
1276                 Slice(..) => {
1277                     let pat_len = prefix.len() + suffix.len();
1278                     if let Some(slice_count) = wild_patterns.len().checked_sub(pat_len) {
1279                         if slice_count == 0 || slice.is_some() {
1280                             Some(
1281                                 prefix.iter().chain(
1282                                 wild_patterns.iter().map(|p| *p)
1283                                                     .skip(prefix.len())
1284                                                     .take(slice_count)
1285                                                     .chain(
1286                                 suffix.iter()
1287                             )).collect())
1288                         } else {
1289                             None
1290                         }
1291                     } else {
1292                         None
1293                     }
1294                 }
1295                 ConstantValue(..) => {
1296                     match slice_pat_covered_by_constructor(
1297                         cx.tcx, pat.span, constructor, prefix, slice, suffix
1298                             ) {
1299                         Ok(true) => Some(vec![]),
1300                         Ok(false) => None,
1301                         Err(ErrorReported) => None
1302                     }
1303                 }
1304                 _ => span_bug!(pat.span,
1305                     "unexpected ctor {:?} for slice pat", constructor)
1306             }
1307         }
1308     };
1309     debug!("specialize({:#?}, {:#?}) = {:#?}", r[0], wild_patterns, head);
1310
1311     head.map(|mut head| {
1312         head.extend_from_slice(&r[1 ..]);
1313         head
1314     })
1315 }