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