]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/hair/pattern/_match.rs
Require just the Unicode Scalar Values to be matched for a char
[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)]
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     let exhaustive_integer_patterns = cx.tcx.features().exhaustive_integer_patterns;
432     let mut value_constructors = false;
433     let ctors = match pcx.ty.sty {
434         ty::TyBool => {
435             [true, false].iter().map(|&b| {
436                 ConstantValue(ty::Const::from_bool(cx.tcx, b))
437             }).collect()
438         }
439         ty::TyArray(ref sub_ty, len) if len.assert_usize(cx.tcx).is_some() => {
440             let len = len.unwrap_usize(cx.tcx);
441             if len != 0 && cx.is_uninhabited(sub_ty) {
442                 vec![]
443             } else {
444                 vec![Slice(len)]
445             }
446         }
447         // Treat arrays of a constant but unknown length like slices.
448         ty::TyArray(ref sub_ty, _) |
449         ty::TySlice(ref sub_ty) => {
450             if cx.is_uninhabited(sub_ty) {
451                 vec![Slice(0)]
452             } else {
453                 (0..pcx.max_slice_length+1).map(|length| Slice(length)).collect()
454             }
455         }
456         ty::TyAdt(def, substs) if def.is_enum() => {
457             def.variants.iter()
458                 .filter(|v| !cx.is_variant_uninhabited(v, substs))
459                 .map(|v| Variant(v.did))
460                 .collect()
461         }
462         ty::TyChar if exhaustive_integer_patterns => {
463             let endpoint = |c: char| {
464                 ty::Const::from_bits(cx.tcx, c as u128, cx.tcx.types.char)
465             };
466             value_constructors = true;
467             vec![
468                 // The valid Unicode Scalar Value ranges.
469                 ConstantRange(endpoint('\u{0000}'), endpoint('\u{D7FF}'), RangeEnd::Included),
470                 ConstantRange(endpoint('\u{E000}'), endpoint('\u{10FFFF}'), RangeEnd::Included),
471             ]
472         }
473         ty::TyInt(int_ty) if exhaustive_integer_patterns => {
474             use syntax::ast::IntTy::*;
475             macro_rules! min_max_ty {
476                 ($ity:ident, $uty:ty, $sty:expr) => {
477                     ($ity::MIN as $uty as u128, $ity::MAX as $uty as u128, $sty)
478                 }
479             }
480             let (min, max, ty) = match int_ty {
481                 Isize => min_max_ty!(isize, usize, cx.tcx.types.isize),
482                 I8    => min_max_ty!(i8, u8, cx.tcx.types.i8),
483                 I16   => min_max_ty!(i16, u16, cx.tcx.types.i16),
484                 I32   => min_max_ty!(i32, u32, cx.tcx.types.i32),
485                 I64   => min_max_ty!(i64, u64, cx.tcx.types.i64),
486                 I128  => min_max_ty!(i128, u128, cx.tcx.types.i128),
487             };
488             value_constructors = true;
489             vec![ConstantRange(ty::Const::from_bits(cx.tcx, min, ty),
490                                ty::Const::from_bits(cx.tcx, max, ty),
491                                RangeEnd::Included)]
492         }
493         ty::TyUint(uint_ty) if exhaustive_integer_patterns => {
494             use syntax::ast::UintTy::*;
495             let (min, (max, ty)) = (0u128, match uint_ty {
496                 Usize => (usize::MAX as u128, cx.tcx.types.usize),
497                 U8    => (   u8::MAX as u128, cx.tcx.types.u8),
498                 U16   => (  u16::MAX as u128, cx.tcx.types.u16),
499                 U32   => (  u32::MAX as u128, cx.tcx.types.u32),
500                 U64   => (  u64::MAX as u128, cx.tcx.types.u64),
501                 U128  => ( u128::MAX as u128, cx.tcx.types.u128),
502             });
503             value_constructors = true;
504             vec![ConstantRange(ty::Const::from_bits(cx.tcx, min, ty),
505                                ty::Const::from_bits(cx.tcx, max, ty),
506                                RangeEnd::Included)]
507         }
508         _ => {
509             if cx.is_uninhabited(pcx.ty) {
510                 vec![]
511             } else {
512                 vec![Single]
513             }
514         }
515     };
516     (ctors, value_constructors)
517 }
518
519 fn max_slice_length<'p, 'a: 'p, 'tcx: 'a, I>(
520     cx: &mut MatchCheckCtxt<'a, 'tcx>,
521     patterns: I) -> u64
522     where I: Iterator<Item=&'p Pattern<'tcx>>
523 {
524     // The exhaustiveness-checking paper does not include any details on
525     // checking variable-length slice patterns. However, they are matched
526     // by an infinite collection of fixed-length array patterns.
527     //
528     // Checking the infinite set directly would take an infinite amount
529     // of time. However, it turns out that for each finite set of
530     // patterns `P`, all sufficiently large array lengths are equivalent:
531     //
532     // Each slice `s` with a "sufficiently-large" length `l â‰¥ L` that applies
533     // to exactly the subset `Pâ‚œ` of `P` can be transformed to a slice
534     // `sₘ` for each sufficiently-large length `m` that applies to exactly
535     // the same subset of `P`.
536     //
537     // Because of that, each witness for reachability-checking from one
538     // of the sufficiently-large lengths can be transformed to an
539     // equally-valid witness from any other length, so we only have
540     // to check slice lengths from the "minimal sufficiently-large length"
541     // and below.
542     //
543     // Note that the fact that there is a *single* `sₘ` for each `m`
544     // not depending on the specific pattern in `P` is important: if
545     // you look at the pair of patterns
546     //     `[true, ..]`
547     //     `[.., false]`
548     // Then any slice of length â‰¥1 that matches one of these two
549     // patterns can be  be trivially turned to a slice of any
550     // other length â‰¥1 that matches them and vice-versa - for
551     // but the slice from length 2 `[false, true]` that matches neither
552     // of these patterns can't be turned to a slice from length 1 that
553     // matches neither of these patterns, so we have to consider
554     // slices from length 2 there.
555     //
556     // Now, to see that that length exists and find it, observe that slice
557     // patterns are either "fixed-length" patterns (`[_, _, _]`) or
558     // "variable-length" patterns (`[_, .., _]`).
559     //
560     // For fixed-length patterns, all slices with lengths *longer* than
561     // the pattern's length have the same outcome (of not matching), so
562     // as long as `L` is greater than the pattern's length we can pick
563     // any `sₘ` from that length and get the same result.
564     //
565     // For variable-length patterns, the situation is more complicated,
566     // because as seen above the precise value of `sₘ` matters.
567     //
568     // However, for each variable-length pattern `p` with a prefix of length
569     // `plâ‚š` and suffix of length `slâ‚š`, only the first `plâ‚š` and the last
570     // `slâ‚š` elements are examined.
571     //
572     // Therefore, as long as `L` is positive (to avoid concerns about empty
573     // types), all elements after the maximum prefix length and before
574     // the maximum suffix length are not examined by any variable-length
575     // pattern, and therefore can be added/removed without affecting
576     // them - creating equivalent patterns from any sufficiently-large
577     // length.
578     //
579     // Of course, if fixed-length patterns exist, we must be sure
580     // that our length is large enough to miss them all, so
581     // we can pick `L = max(FIXED_LEN+1 âˆª {max(PREFIX_LEN) + max(SUFFIX_LEN)})`
582     //
583     // for example, with the above pair of patterns, all elements
584     // but the first and last can be added/removed, so any
585     // witness of length â‰¥2 (say, `[false, false, true]`) can be
586     // turned to a witness from any other length â‰¥2.
587
588     let mut max_prefix_len = 0;
589     let mut max_suffix_len = 0;
590     let mut max_fixed_len = 0;
591
592     for row in patterns {
593         match *row.kind {
594             PatternKind::Constant { value } => {
595                 if let Some(ptr) = value.to_ptr() {
596                     let is_array_ptr = value.ty
597                         .builtin_deref(true)
598                         .and_then(|t| t.ty.builtin_index())
599                         .map_or(false, |t| t == cx.tcx.types.u8);
600                     if is_array_ptr {
601                         let alloc = cx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
602                         max_fixed_len = cmp::max(max_fixed_len, alloc.bytes.len() as u64);
603                     }
604                 }
605             }
606             PatternKind::Slice { ref prefix, slice: None, ref suffix } => {
607                 let fixed_len = prefix.len() as u64 + suffix.len() as u64;
608                 max_fixed_len = cmp::max(max_fixed_len, fixed_len);
609             }
610             PatternKind::Slice { ref prefix, slice: Some(_), ref suffix } => {
611                 max_prefix_len = cmp::max(max_prefix_len, prefix.len() as u64);
612                 max_suffix_len = cmp::max(max_suffix_len, suffix.len() as u64);
613             }
614             _ => {}
615         }
616     }
617
618     cmp::max(max_fixed_len + 1, max_prefix_len + max_suffix_len)
619 }
620
621 /// An inclusive interval, used for precise integer exhaustiveness checking.
622 struct Interval<'tcx> {
623     pub lo: u128,
624     pub hi: u128,
625     pub ty: Ty<'tcx>,
626 }
627
628 impl<'tcx> Interval<'tcx> {
629     fn from_ctor(ctor: &Constructor<'tcx>) -> Option<Interval<'tcx>> {
630         match ctor {
631             ConstantRange(lo, hi, end) => {
632                 assert_eq!(lo.ty, hi.ty);
633                 let ty = lo.ty;
634                 if let Some(lo) = lo.assert_bits(ty) {
635                     if let Some(hi) = hi.assert_bits(ty) {
636                         // Perform a shift if the underlying types are signed,
637                         // which makes the interval arithmetic simpler.
638                         let (lo, hi) = Interval::offset_sign(ty, (lo, hi), true);
639                         // Make sure the interval is well-formed.
640                         return if lo > hi || lo == hi && *end == RangeEnd::Excluded {
641                             None
642                         } else {
643                             let offset = (*end == RangeEnd::Excluded) as u128;
644                             Some(Interval { lo, hi: hi - offset, ty })
645                         };
646                     }
647                 }
648                 None
649             }
650             ConstantValue(val) => {
651                 let ty = val.ty;
652                 val.assert_bits(ty).map(|val| Interval { lo: val, hi: val, ty })
653             }
654             Single | Variant(_) | Slice(_) => {
655                 None
656             }
657         }
658     }
659
660     fn offset_sign(ty: Ty<'tcx>, (lo, hi): (u128, u128), forwards: bool) -> (u128, u128) {
661         use syntax::ast::IntTy::*;
662         match ty.sty {
663             ty::TyInt(int_ty) => {
664                 macro_rules! offset_sign_for_ty {
665                     ($ity:ident, $uty:ty) => {{
666                         let min = Wrapping($ity::MIN as $uty);
667                         if forwards {
668                             ((Wrapping(lo as $uty) + min).0 as u128,
669                              (Wrapping(hi as $uty) + min).0 as u128)
670                         } else {
671                             ((Wrapping(lo as $uty) + min).0 as $ity as u128,
672                              (Wrapping(hi as $uty) + min).0 as $ity as u128)
673                         }
674                     }}
675                 }
676                 match int_ty {
677                     Isize => offset_sign_for_ty!(isize, usize),
678                     I8    => offset_sign_for_ty!(i8, u8),
679                     I16   => offset_sign_for_ty!(i16, u16),
680                     I32   => offset_sign_for_ty!(i32, u32),
681                     I64   => offset_sign_for_ty!(i64, u64),
682                     I128  => offset_sign_for_ty!(i128, u128),
683                 }
684             }
685             ty::TyUint(_) | ty::TyChar => {
686                 (lo, hi)
687             }
688             _ => bug!("`Interval` should only contain integer types")
689         }
690     }
691
692     fn into_inner(self) -> (u128, u128) {
693         (self.lo, self.hi)
694     }
695 }
696
697 /// Given a pattern in a `match` and a collection of ranges corresponding to the
698 /// domain of values of a type (say, an integer), return a new collection of ranges
699 /// corresponding to those ranges minus the ranges covered by the pattern.
700 fn ranges_subtract_pattern<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
701                                      pat_ctor: &Constructor<'tcx>,
702                                      ranges: Vec<Constructor<'tcx>>)
703                                      -> Vec<Constructor<'tcx>> {
704     if let Some(pat_interval) = Interval::from_ctor(pat_ctor) {
705         let mut remaining_ranges = vec![];
706         let mut ranges: Vec<_> = ranges.into_iter().filter_map(|r| {
707             Interval::from_ctor(&r).map(|i| i.into_inner())
708         }).collect();
709         for (subrange_lo, subrange_hi) in ranges {
710             if pat_interval.lo > subrange_hi || pat_interval.hi < subrange_lo {
711                 // The pattern doesn't intersect with the subrange at all,
712                 // so the subrange remains untouched.
713                 remaining_ranges.push((subrange_lo, subrange_hi));
714             } else if pat_interval.lo <= subrange_lo && pat_interval.hi >= subrange_hi {
715                 // The pattern entirely covers the subrange of values,
716                 // so we no longer have to consider this subrange_
717             } else if pat_interval.lo <= subrange_lo {
718                 // The pattern intersects a lower section of the subrange,
719                 // so only the upper section will remain.
720                 remaining_ranges.push((pat_interval.hi + 1, subrange_hi));
721             } else if pat_interval.hi >= subrange_hi {
722                 // The pattern intersects an upper section of the subrange,
723                 // so only the lower section will remain.
724                 remaining_ranges.push((subrange_lo, pat_interval.lo - 1));
725             } else {
726                 // The pattern intersects the middle of the subrange,
727                 // so we create two ranges either side of the intersection.)
728                 remaining_ranges.push((subrange_lo, pat_interval.lo));
729                 remaining_ranges.push((pat_interval.hi, subrange_hi));
730             }
731         }
732         // Convert the remaining ranges from pairs to inclusive `ConstantRange`s.
733         let ty = pat_interval.ty;
734         remaining_ranges.into_iter().map(|(lo, hi)| {
735             let (lo, hi) = Interval::offset_sign(ty, (lo, hi), false);
736             ConstantRange(ty::Const::from_bits(cx.tcx, lo, ty),
737                           ty::Const::from_bits(cx.tcx, hi, ty),
738                           RangeEnd::Included)
739         }).collect()
740     } else {
741         ranges
742     }
743 }
744
745 /// Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
746 /// The algorithm from the paper has been modified to correctly handle empty
747 /// types. The changes are:
748 ///   (0) We don't exit early if the pattern matrix has zero rows. We just
749 ///       continue to recurse over columns.
750 ///   (1) all_constructors will only return constructors that are statically
751 ///       possible. eg. it will only return Ok for Result<T, !>
752 ///
753 /// This finds whether a (row) vector `v` of patterns is 'useful' in relation
754 /// to a set of such vectors `m` - this is defined as there being a set of
755 /// inputs that will match `v` but not any of the sets in `m`.
756 ///
757 /// All the patterns at each column of the `matrix ++ v` matrix must
758 /// have the same type, except that wildcard (PatternKind::Wild) patterns
759 /// with type TyErr are also allowed, even if the "type of the column"
760 /// is not TyErr. That is used to represent private fields, as using their
761 /// real type would assert that they are inhabited.
762 ///
763 /// This is used both for reachability checking (if a pattern isn't useful in
764 /// relation to preceding patterns, it is not reachable) and exhaustiveness
765 /// checking (if a wildcard pattern is useful in relation to a matrix, the
766 /// matrix isn't exhaustive).
767 pub fn is_useful<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
768                                        matrix: &Matrix<'p, 'tcx>,
769                                        v: &[&'p Pattern<'tcx>],
770                                        witness: WitnessPreference)
771                                        -> Usefulness<'tcx> {
772     let &Matrix(ref rows) = matrix;
773     debug!("is_useful({:#?}, {:#?})", matrix, v);
774
775     // The base case. We are pattern-matching on () and the return value is
776     // based on whether our matrix has a row or not.
777     // NOTE: This could potentially be optimized by checking rows.is_empty()
778     // first and then, if v is non-empty, the return value is based on whether
779     // the type of the tuple we're checking is inhabited or not.
780     if v.is_empty() {
781         return if rows.is_empty() {
782             match witness {
783                 ConstructWitness => UsefulWithWitness(vec![Witness(vec![])]),
784                 LeaveOutWitness => Useful,
785             }
786         } else {
787             NotUseful
788         }
789     };
790
791     assert!(rows.iter().all(|r| r.len() == v.len()));
792
793     let pcx = PatternContext {
794         // TyErr is used to represent the type of wildcard patterns matching
795         // against inaccessible (private) fields of structs, so that we won't
796         // be able to observe whether the types of the struct's fields are
797         // inhabited.
798         //
799         // If the field is truly inaccessible, then all the patterns
800         // matching against it must be wildcard patterns, so its type
801         // does not matter.
802         //
803         // However, if we are matching against non-wildcard patterns, we
804         // need to know the real type of the field so we can specialize
805         // against it. This primarily occurs through constants - they
806         // can include contents for fields that are inaccessible at the
807         // location of the match. In that case, the field's type is
808         // inhabited - by the constant - so we can just use it.
809         //
810         // FIXME: this might lead to "unstable" behavior with macro hygiene
811         // introducing uninhabited patterns for inaccessible fields. We
812         // need to figure out how to model that.
813         ty: rows.iter().map(|r| r[0].ty).find(|ty| !ty.references_error())
814             .unwrap_or(v[0].ty),
815         max_slice_length: max_slice_length(cx, rows.iter().map(|r| r[0]).chain(Some(v[0])))
816     };
817
818     debug!("is_useful_expand_first_col: pcx={:#?}, expanding {:#?}", pcx, v[0]);
819
820     if let Some(constructors) = pat_constructors(cx, v[0], pcx) {
821         debug!("is_useful - expanding constructors: {:#?}", constructors);
822         constructors.into_iter().map(|c|
823             is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness)
824         ).find(|result| result.is_useful()).unwrap_or(NotUseful)
825     } else {
826         debug!("is_useful - expanding wildcard");
827
828         let used_ctors: Vec<Constructor> = rows.iter().flat_map(|row| {
829             pat_constructors(cx, row[0], pcx).unwrap_or(vec![])
830         }).collect();
831         debug!("used_ctors = {:#?}", used_ctors);
832         // `all_ctors` are all the constructors for the given type, which
833         // should all be represented (or caught with the wild pattern `_`).
834         // `value_constructors` is true if we may exhaustively consider all
835         // the possible values (e.g. integers) of a type as its constructors.
836         let (all_ctors, value_constructors) = all_constructors(cx, pcx);
837         debug!("all_ctors = {:#?}", all_ctors);
838
839         // `missing_ctors` are those that should have appeared
840         // as patterns in the `match` expression, but did not.
841         let mut missing_ctors = vec![];
842         'req: for req_ctor in all_ctors.clone() {
843             let mut sub_ctors = vec![req_ctor.clone()];
844             // The only constructor patterns for which it is valid to
845             // treat the values as constructors are ranges (see
846             // `all_constructors` for details).
847             let consider_value_constructors = value_constructors && match req_ctor {
848                 ConstantRange(..) => true,
849                 _ => false,
850             };
851             for used_ctor in &used_ctors {
852                 if consider_value_constructors {
853                     sub_ctors = ranges_subtract_pattern(cx, used_ctor, sub_ctors);
854                     // If the constructor patterns that have been considered so far
855                     // already cover the entire range of values, then we the
856                     // constructor is not missing, and we can move on to the next one.
857                     if sub_ctors.is_empty() {
858                         continue 'req;
859                     }
860                 } else {
861                     // If the pattern for the required constructor
862                     // appears in the `match`, then it is not missing,
863                     // and we can move on to the next one.
864                     if *used_ctor == req_ctor {
865                         continue 'req;
866                     }
867                 }
868             }
869             // If a constructor has not been matched, then it is missing.
870             // We add `sub_ctors` instead of `req_ctor`, because then we can
871             // provide more detailed error information about precisely which
872             // ranges have been omitted.
873             missing_ctors.extend(sub_ctors);
874         }
875
876         // `missing_ctors` is the set of constructors from the same type as the
877         // first column of `matrix` that are matched only by wildcard patterns
878         // from the first column.
879         //
880         // Therefore, if there is some pattern that is unmatched by `matrix`,
881         // it will still be unmatched if the first constructor is replaced by
882         // any of the constructors in `missing_ctors`
883         //
884         // However, if our scrutinee is *privately* an empty enum, we
885         // must treat it as though it had an "unknown" constructor (in
886         // that case, all other patterns obviously can't be variants)
887         // to avoid exposing its emptyness. See the `match_privately_empty`
888         // test for details.
889         //
890         // FIXME: currently the only way I know of something can
891         // be a privately-empty enum is when the exhaustive_patterns
892         // feature flag is not present, so this is only
893         // needed for that case.
894
895         let is_privately_empty =
896             all_ctors.is_empty() && !cx.is_uninhabited(pcx.ty);
897         let is_declared_nonexhaustive =
898             cx.is_non_exhaustive_enum(pcx.ty) && !cx.is_local(pcx.ty);
899         debug!("missing_ctors={:#?} is_privately_empty={:#?} is_declared_nonexhaustive={:#?}",
900                missing_ctors, is_privately_empty, is_declared_nonexhaustive);
901
902         // For privately empty and non-exhaustive enums, we work as if there were an "extra"
903         // `_` constructor for the type, so we can never match over all constructors.
904         let is_non_exhaustive = is_privately_empty || is_declared_nonexhaustive;
905
906         if missing_ctors.is_empty() && !is_non_exhaustive {
907             if value_constructors {
908                 // If we've successfully matched every value
909                 // of the type, then we're done.
910                 NotUseful
911             } else {
912                 all_ctors.into_iter().map(|c| {
913                     is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness)
914                 }).find(|result| result.is_useful()).unwrap_or(NotUseful)
915             }
916         } else {
917             let matrix = rows.iter().filter_map(|r| {
918                 if r[0].is_wildcard() {
919                     Some(r[1..].to_vec())
920                 } else {
921                     None
922                 }
923             }).collect();
924             match is_useful(cx, &matrix, &v[1..], witness) {
925                 UsefulWithWitness(pats) => {
926                     let cx = &*cx;
927                     // In this case, there's at least one "free"
928                     // constructor that is only matched against by
929                     // wildcard patterns.
930                     //
931                     // There are 2 ways we can report a witness here.
932                     // Commonly, we can report all the "free"
933                     // constructors as witnesses, e.g. if we have:
934                     //
935                     // ```
936                     //     enum Direction { N, S, E, W }
937                     //     let Direction::N = ...;
938                     // ```
939                     //
940                     // we can report 3 witnesses: `S`, `E`, and `W`.
941                     //
942                     // However, there are 2 cases where we don't want
943                     // to do this and instead report a single `_` witness:
944                     //
945                     // 1) If the user is matching against a non-exhaustive
946                     // enum, there is no point in enumerating all possible
947                     // variants, because the user can't actually match
948                     // against them himself, e.g. in an example like:
949                     // ```
950                     //     let err: io::ErrorKind = ...;
951                     //     match err {
952                     //         io::ErrorKind::NotFound => {},
953                     //     }
954                     // ```
955                     // we don't want to show every possible IO error,
956                     // but instead have `_` as the witness (this is
957                     // actually *required* if the user specified *all*
958                     // IO errors, but is probably what we want in every
959                     // case).
960                     //
961                     // 2) If the user didn't actually specify a constructor
962                     // in this arm, e.g. in
963                     // ```
964                     //     let x: (Direction, Direction, bool) = ...;
965                     //     let (_, _, false) = x;
966                     // ```
967                     // we don't want to show all 16 possible witnesses
968                     // `(<direction-1>, <direction-2>, true)` - we are
969                     // satisfied with `(_, _, true)`. In this case,
970                     // `used_ctors` is empty.
971                     let new_witnesses = if is_non_exhaustive || used_ctors.is_empty() {
972                         // All constructors are unused. Add wild patterns
973                         // rather than each individual constructor
974                         pats.into_iter().map(|mut witness| {
975                             witness.0.push(Pattern {
976                                 ty: pcx.ty,
977                                 span: DUMMY_SP,
978                                 kind: box PatternKind::Wild,
979                             });
980                             witness
981                         }).collect()
982                     } else {
983                         if value_constructors {
984                             // If we've been trying to exhaustively match
985                             // over the domain of values for a type,
986                             // then we can provide better diagnostics
987                             // regarding which values were missing.
988                             missing_ctors.into_iter().map(|ctor| {
989                                 match ctor {
990                                     // A constant range of length 1 is simply
991                                     // a constant value.
992                                     ConstantRange(lo, hi, _) if lo == hi => {
993                                         Witness(vec![Pattern {
994                                             ty: pcx.ty,
995                                             span: DUMMY_SP,
996                                             kind: box PatternKind::Constant { value: lo },
997                                         }])
998                                     }
999                                     // We always report missing intervals
1000                                     // in terms of inclusive ranges.
1001                                     ConstantRange(lo, hi, end) => {
1002                                         Witness(vec![Pattern {
1003                                             ty: pcx.ty,
1004                                             span: DUMMY_SP,
1005                                             kind: box PatternKind::Range { lo, hi, end },
1006                                         }])
1007                                     },
1008                                     _ => bug!("`ranges_subtract_pattern` should only produce \
1009                                                `ConstantRange`s"),
1010                                 }
1011                             }).collect()
1012                         } else {
1013                             pats.into_iter().flat_map(|witness| {
1014                                 missing_ctors.iter().map(move |ctor| {
1015                                     witness.clone().push_wild_constructor(cx, ctor, pcx.ty)
1016                                 })
1017                             }).collect()
1018                         }
1019                     };
1020                     UsefulWithWitness(new_witnesses)
1021                 }
1022                 result => result
1023             }
1024         }
1025     }
1026 }
1027
1028 fn is_useful_specialized<'p, 'a:'p, 'tcx: 'a>(
1029     cx: &mut MatchCheckCtxt<'a, 'tcx>,
1030     &Matrix(ref m): &Matrix<'p, 'tcx>,
1031     v: &[&'p Pattern<'tcx>],
1032     ctor: Constructor<'tcx>,
1033     lty: Ty<'tcx>,
1034     witness: WitnessPreference) -> Usefulness<'tcx>
1035 {
1036     debug!("is_useful_specialized({:#?}, {:#?}, {:?})", v, ctor, lty);
1037     let sub_pat_tys = constructor_sub_pattern_tys(cx, &ctor, lty);
1038     let wild_patterns_owned: Vec<_> = sub_pat_tys.iter().map(|ty| {
1039         Pattern {
1040             ty,
1041             span: DUMMY_SP,
1042             kind: box PatternKind::Wild,
1043         }
1044     }).collect();
1045     let wild_patterns: Vec<_> = wild_patterns_owned.iter().collect();
1046     let matrix = Matrix(m.iter().flat_map(|r| {
1047         specialize(cx, &r, &ctor, &wild_patterns)
1048     }).collect());
1049     match specialize(cx, v, &ctor, &wild_patterns) {
1050         Some(v) => match is_useful(cx, &matrix, &v, witness) {
1051             UsefulWithWitness(witnesses) => UsefulWithWitness(
1052                 witnesses.into_iter()
1053                     .map(|witness| witness.apply_constructor(cx, &ctor, lty))
1054                     .collect()
1055             ),
1056             result => result
1057         },
1058         None => NotUseful
1059     }
1060 }
1061
1062 /// Determines the constructors that the given pattern can be specialized to.
1063 ///
1064 /// In most cases, there's only one constructor that a specific pattern
1065 /// represents, such as a specific enum variant or a specific literal value.
1066 /// Slice patterns, however, can match slices of different lengths. For instance,
1067 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
1068 ///
1069 /// Returns None in case of a catch-all, which can't be specialized.
1070 fn pat_constructors<'tcx>(cx: &mut MatchCheckCtxt,
1071                           pat: &Pattern<'tcx>,
1072                           pcx: PatternContext)
1073                           -> Option<Vec<Constructor<'tcx>>>
1074 {
1075     match *pat.kind {
1076         PatternKind::Binding { .. } | PatternKind::Wild =>
1077             None,
1078         PatternKind::Leaf { .. } | PatternKind::Deref { .. } =>
1079             Some(vec![Single]),
1080         PatternKind::Variant { adt_def, variant_index, .. } =>
1081             Some(vec![Variant(adt_def.variants[variant_index].did)]),
1082         PatternKind::Constant { value } =>
1083             Some(vec![ConstantValue(value)]),
1084         PatternKind::Range { lo, hi, end } =>
1085             Some(vec![ConstantRange(lo, hi, end)]),
1086         PatternKind::Array { .. } => match pcx.ty.sty {
1087             ty::TyArray(_, length) => Some(vec![
1088                 Slice(length.unwrap_usize(cx.tcx))
1089             ]),
1090             _ => span_bug!(pat.span, "bad ty {:?} for array pattern", pcx.ty)
1091         },
1092         PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
1093             let pat_len = prefix.len() as u64 + suffix.len() as u64;
1094             if slice.is_some() {
1095                 Some((pat_len..pcx.max_slice_length+1).map(Slice).collect())
1096             } else {
1097                 Some(vec![Slice(pat_len)])
1098             }
1099         }
1100     }
1101 }
1102
1103 /// This computes the arity of a constructor. The arity of a constructor
1104 /// is how many subpattern patterns of that constructor should be expanded to.
1105 ///
1106 /// For instance, a tuple pattern (_, 42, Some([])) has the arity of 3.
1107 /// A struct pattern's arity is the number of fields it contains, etc.
1108 fn constructor_arity(_cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> u64 {
1109     debug!("constructor_arity({:#?}, {:?})", ctor, ty);
1110     match ty.sty {
1111         ty::TyTuple(ref fs) => fs.len() as u64,
1112         ty::TySlice(..) | ty::TyArray(..) => match *ctor {
1113             Slice(length) => length,
1114             ConstantValue(_) => 0,
1115             _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
1116         },
1117         ty::TyRef(..) => 1,
1118         ty::TyAdt(adt, _) => {
1119             adt.variants[ctor.variant_index_for_adt(adt)].fields.len() as u64
1120         }
1121         _ => 0
1122     }
1123 }
1124
1125 /// This computes the types of the sub patterns that a constructor should be
1126 /// expanded to.
1127 ///
1128 /// For instance, a tuple pattern (43u32, 'a') has sub pattern types [u32, char].
1129 fn constructor_sub_pattern_tys<'a, 'tcx: 'a>(cx: &MatchCheckCtxt<'a, 'tcx>,
1130                                              ctor: &Constructor,
1131                                              ty: Ty<'tcx>) -> Vec<Ty<'tcx>>
1132 {
1133     debug!("constructor_sub_pattern_tys({:#?}, {:?})", ctor, ty);
1134     match ty.sty {
1135         ty::TyTuple(ref fs) => fs.into_iter().map(|t| *t).collect(),
1136         ty::TySlice(ty) | ty::TyArray(ty, _) => match *ctor {
1137             Slice(length) => (0..length).map(|_| ty).collect(),
1138             ConstantValue(_) => vec![],
1139             _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
1140         },
1141         ty::TyRef(_, rty, _) => vec![rty],
1142         ty::TyAdt(adt, substs) => {
1143             if adt.is_box() {
1144                 // Use T as the sub pattern type of Box<T>.
1145                 vec![substs.type_at(0)]
1146             } else {
1147                 adt.variants[ctor.variant_index_for_adt(adt)].fields.iter().map(|field| {
1148                     let is_visible = adt.is_enum()
1149                         || field.vis.is_accessible_from(cx.module, cx.tcx);
1150                     if is_visible {
1151                         field.ty(cx.tcx, substs)
1152                     } else {
1153                         // Treat all non-visible fields as TyErr. They
1154                         // can't appear in any other pattern from
1155                         // this match (because they are private),
1156                         // so their type does not matter - but
1157                         // we don't want to know they are
1158                         // uninhabited.
1159                         cx.tcx.types.err
1160                     }
1161                 }).collect()
1162             }
1163         }
1164         _ => vec![],
1165     }
1166 }
1167
1168 fn slice_pat_covered_by_constructor<'tcx>(
1169     tcx: TyCtxt<'_, 'tcx, '_>,
1170     _span: Span,
1171     ctor: &Constructor,
1172     prefix: &[Pattern<'tcx>],
1173     slice: &Option<Pattern<'tcx>>,
1174     suffix: &[Pattern<'tcx>]
1175 ) -> Result<bool, ErrorReported> {
1176     let data: &[u8] = match *ctor {
1177         ConstantValue(const_val) => {
1178             let val = match const_val.val {
1179                 ConstValue::Unevaluated(..) |
1180                 ConstValue::ByRef(..) => bug!("unexpected ConstValue: {:?}", const_val),
1181                 ConstValue::Scalar(val) | ConstValue::ScalarPair(val, _) => val,
1182             };
1183             if let Ok(ptr) = val.to_ptr() {
1184                 let is_array_ptr = const_val.ty
1185                     .builtin_deref(true)
1186                     .and_then(|t| t.ty.builtin_index())
1187                     .map_or(false, |t| t == tcx.types.u8);
1188                 assert!(is_array_ptr);
1189                 tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id).bytes.as_ref()
1190             } else {
1191                 bug!("unexpected non-ptr ConstantValue")
1192             }
1193         }
1194         _ => bug!()
1195     };
1196
1197     let pat_len = prefix.len() + suffix.len();
1198     if data.len() < pat_len || (slice.is_none() && data.len() > pat_len) {
1199         return Ok(false);
1200     }
1201
1202     for (ch, pat) in
1203         data[..prefix.len()].iter().zip(prefix).chain(
1204             data[data.len()-suffix.len()..].iter().zip(suffix))
1205     {
1206         match pat.kind {
1207             box PatternKind::Constant { value } => {
1208                 let b = value.unwrap_bits(tcx, ty::ParamEnv::empty().and(pat.ty));
1209                 assert_eq!(b as u8 as u128, b);
1210                 if b as u8 != *ch {
1211                     return Ok(false);
1212                 }
1213             }
1214             _ => {}
1215         }
1216     }
1217
1218     Ok(true)
1219 }
1220
1221 fn constructor_covered_by_range<'a, 'tcx>(
1222     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1223     ctor: &Constructor<'tcx>,
1224     from: &'tcx ty::Const<'tcx>, to: &'tcx ty::Const<'tcx>,
1225     end: RangeEnd,
1226     ty: Ty<'tcx>,
1227 ) -> Result<bool, ErrorReported> {
1228     trace!("constructor_covered_by_range {:#?}, {:#?}, {:#?}, {}", ctor, from, to, ty);
1229     let cmp_from = |c_from| compare_const_vals(tcx, c_from, from, ty::ParamEnv::empty().and(ty))
1230         .map(|res| res != Ordering::Less);
1231     let cmp_to = |c_to| compare_const_vals(tcx, c_to, to, ty::ParamEnv::empty().and(ty));
1232     macro_rules! some_or_ok {
1233         ($e:expr) => {
1234             match $e {
1235                 Some(to) => to,
1236                 None => return Ok(false), // not char or int
1237             }
1238         };
1239     }
1240     match *ctor {
1241         ConstantValue(value) => {
1242             let to = some_or_ok!(cmp_to(value));
1243             let end = (to == Ordering::Less) ||
1244                       (end == RangeEnd::Included && to == Ordering::Equal);
1245             Ok(some_or_ok!(cmp_from(value)) && end)
1246         },
1247         ConstantRange(from, to, RangeEnd::Included) => {
1248             let to = some_or_ok!(cmp_to(to));
1249             let end = (to == Ordering::Less) ||
1250                       (end == RangeEnd::Included && to == Ordering::Equal);
1251             Ok(some_or_ok!(cmp_from(from)) && end)
1252         },
1253         ConstantRange(from, to, RangeEnd::Excluded) => {
1254             let to = some_or_ok!(cmp_to(to));
1255             let end = (to == Ordering::Less) ||
1256                       (end == RangeEnd::Excluded && to == Ordering::Equal);
1257             Ok(some_or_ok!(cmp_from(from)) && end)
1258         }
1259         Single => Ok(true),
1260         _ => bug!(),
1261     }
1262 }
1263
1264 fn patterns_for_variant<'p, 'a: 'p, 'tcx: 'a>(
1265     subpatterns: &'p [FieldPattern<'tcx>],
1266     wild_patterns: &[&'p Pattern<'tcx>])
1267     -> Vec<&'p Pattern<'tcx>>
1268 {
1269     let mut result = wild_patterns.to_owned();
1270
1271     for subpat in subpatterns {
1272         result[subpat.field.index()] = &subpat.pattern;
1273     }
1274
1275     debug!("patterns_for_variant({:#?}, {:#?}) = {:#?}", subpatterns, wild_patterns, result);
1276     result
1277 }
1278
1279 /// This is the main specialization step. It expands the first pattern in the given row
1280 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
1281 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
1282 ///
1283 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
1284 /// different patterns.
1285 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
1286 /// fields filled with wild patterns.
1287 fn specialize<'p, 'a: 'p, 'tcx: 'a>(
1288     cx: &mut MatchCheckCtxt<'a, 'tcx>,
1289     r: &[&'p Pattern<'tcx>],
1290     constructor: &Constructor<'tcx>,
1291     wild_patterns: &[&'p Pattern<'tcx>])
1292     -> Option<Vec<&'p Pattern<'tcx>>>
1293 {
1294     let pat = &r[0];
1295
1296     let head: Option<Vec<&Pattern>> = match *pat.kind {
1297         PatternKind::Binding { .. } | PatternKind::Wild => {
1298             Some(wild_patterns.to_owned())
1299         },
1300
1301         PatternKind::Variant { adt_def, variant_index, ref subpatterns, .. } => {
1302             let ref variant = adt_def.variants[variant_index];
1303             if *constructor == Variant(variant.did) {
1304                 Some(patterns_for_variant(subpatterns, wild_patterns))
1305             } else {
1306                 None
1307             }
1308         }
1309
1310         PatternKind::Leaf { ref subpatterns } => {
1311             Some(patterns_for_variant(subpatterns, wild_patterns))
1312         }
1313
1314         PatternKind::Deref { ref subpattern } => {
1315             Some(vec![subpattern])
1316         }
1317
1318         PatternKind::Constant { value } => {
1319             match *constructor {
1320                 Slice(..) => {
1321                     if let Some(ptr) = value.to_ptr() {
1322                         let is_array_ptr = value.ty
1323                             .builtin_deref(true)
1324                             .and_then(|t| t.ty.builtin_index())
1325                             .map_or(false, |t| t == cx.tcx.types.u8);
1326                         assert!(is_array_ptr);
1327                         let data_len = cx.tcx
1328                             .alloc_map
1329                             .lock()
1330                             .unwrap_memory(ptr.alloc_id)
1331                             .bytes
1332                             .len();
1333                         if wild_patterns.len() == data_len {
1334                             Some(cx.lower_byte_str_pattern(pat))
1335                         } else {
1336                             None
1337                         }
1338                     } else {
1339                         span_bug!(pat.span,
1340                         "unexpected const-val {:?} with ctor {:?}", value, constructor)
1341                     }
1342                 },
1343                 _ => {
1344                     match constructor_covered_by_range(
1345                         cx.tcx,
1346                         constructor, value, value, RangeEnd::Included,
1347                         value.ty,
1348                             ) {
1349                         Ok(true) => Some(vec![]),
1350                         Ok(false) => None,
1351                         Err(ErrorReported) => None,
1352                     }
1353                 }
1354             }
1355         }
1356
1357         PatternKind::Range { lo, hi, ref end } => {
1358             match constructor_covered_by_range(
1359                 cx.tcx,
1360                 constructor, lo, hi, end.clone(), lo.ty,
1361             ) {
1362                 Ok(true) => Some(vec![]),
1363                 Ok(false) => None,
1364                 Err(ErrorReported) => None,
1365             }
1366         }
1367
1368         PatternKind::Array { ref prefix, ref slice, ref suffix } |
1369         PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
1370             match *constructor {
1371                 Slice(..) => {
1372                     let pat_len = prefix.len() + suffix.len();
1373                     if let Some(slice_count) = wild_patterns.len().checked_sub(pat_len) {
1374                         if slice_count == 0 || slice.is_some() {
1375                             Some(
1376                                 prefix.iter().chain(
1377                                 wild_patterns.iter().map(|p| *p)
1378                                                     .skip(prefix.len())
1379                                                     .take(slice_count)
1380                                                     .chain(
1381                                 suffix.iter()
1382                             )).collect())
1383                         } else {
1384                             None
1385                         }
1386                     } else {
1387                         None
1388                     }
1389                 }
1390                 ConstantValue(..) => {
1391                     match slice_pat_covered_by_constructor(
1392                         cx.tcx, pat.span, constructor, prefix, slice, suffix
1393                             ) {
1394                         Ok(true) => Some(vec![]),
1395                         Ok(false) => None,
1396                         Err(ErrorReported) => None
1397                     }
1398                 }
1399                 _ => span_bug!(pat.span,
1400                     "unexpected ctor {:?} for slice pat", constructor)
1401             }
1402         }
1403     };
1404     debug!("specialize({:#?}, {:#?}) = {:#?}", r[0], wild_patterns, head);
1405
1406     head.map(|mut head| {
1407         head.extend_from_slice(&r[1 ..]);
1408         head
1409     })
1410 }