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