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