]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/hair/pattern/_match.rs
Rollup merge of #55953 - blitzerr:master, r=nikomatsakis
[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 "specialized 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 ///        The specialization of a row vector is computed by `specialize`.
63 ///
64 ///        It is computed as follows. For each row `p_i` of P, we have four cases:
65 ///             1.1. `p_(i,1) = c(r_1, .., r_a)`. Then `S(c, P)` has a corresponding row:
66 ///                     r_1, .., r_a, p_(i,2), .., p_(i,n)
67 ///             1.2. `p_(i,1) = c'(r_1, .., r_a')` where `c ≠ c'`. Then `S(c, P)` has no
68 ///                  corresponding row.
69 ///             1.3. `p_(i,1) = _`. Then `S(c, P)` has a corresponding row:
70 ///                     _, .., _, p_(i,2), .., p_(i,n)
71 ///             1.4. `p_(i,1) = r_1 | r_2`. Then `S(c, P)` has corresponding rows inlined from:
72 ///                     S(c, (r_1, p_(i,2), .., p_(i,n)))
73 ///                     S(c, (r_2, p_(i,2), .., p_(i,n)))
74 ///
75 ///     2. `D(P)` is a "default matrix". This is used when we know there are missing
76 ///        constructor cases, but there might be existing wildcard patterns, so to check the
77 ///        usefulness of the matrix, we have to check all its *other* components.
78 ///        The default matrix is computed inline in `is_useful`.
79 ///
80 ///         It is computed as follows. For each row `p_i` of P, we have three cases:
81 ///             1.1. `p_(i,1) = c(r_1, .., r_a)`. Then `D(P)` has no corresponding row.
82 ///             1.2. `p_(i,1) = _`. Then `D(P)` has a corresponding row:
83 ///                     p_(i,2), .., p_(i,n)
84 ///             1.3. `p_(i,1) = r_1 | r_2`. Then `D(P)` has corresponding rows inlined from:
85 ///                     D((r_1, p_(i,2), .., p_(i,n)))
86 ///                     D((r_2, p_(i,2), .., p_(i,n)))
87 ///
88 ///     Note that the OR-patterns are not always used directly in Rust, but are used to derive
89 ///     the exhaustive integer matching rules, so they're written here for posterity.
90 ///
91 /// The algorithm for computing `U`
92 /// -------------------------------
93 /// The algorithm is inductive (on the number of columns: i.e. components of tuple patterns).
94 /// That means we're going to check the components from left-to-right, so the algorithm
95 /// operates principally on the first component of the matrix and new pattern `p_{m + 1}`.
96 /// This algorithm is realised in the `is_useful` function.
97 ///
98 /// Base case. (`n = 0`, i.e. an empty tuple pattern)
99 ///     - If `P` already contains an empty pattern (i.e. if the number of patterns `m > 0`),
100 ///       then `U(P, p_{m + 1})` is false.
101 ///     - Otherwise, `P` must be empty, so `U(P, p_{m + 1})` is true.
102 ///
103 /// Inductive step. (`n > 0`, i.e. whether there's at least one column
104 ///                  [which may then be expanded into further columns later])
105 ///     We're going to match on the new pattern, `p_{m + 1}`.
106 ///         - If `p_{m + 1} == c(r_1, .., r_a)`, then we have a constructor pattern.
107 ///           Thus, the usefulness of `p_{m + 1}` can be reduced to whether it is useful when
108 ///           we ignore all the patterns in `P` that involve other constructors. This is where
109 ///           `S(c, P)` comes in:
110 ///           `U(P, p_{m + 1}) := U(S(c, P), S(c, p_{m + 1}))`
111 ///           This special case is handled in `is_useful_specialized`.
112 ///         - If `p_{m + 1} == _`, then we have two more cases:
113 ///             + All the constructors of the first component of the type exist within
114 ///               all the rows (after having expanded OR-patterns). In this case:
115 ///               `U(P, p_{m + 1}) := ∨(k ϵ constructors) U(S(k, P), S(k, p_{m + 1}))`
116 ///               I.e. the pattern `p_{m + 1}` is only useful when all the constructors are
117 ///               present *if* its later components are useful for the respective constructors
118 ///               covered by `p_{m + 1}` (usually a single constructor, but all in the case of `_`).
119 ///             + Some constructors are not present in the existing rows (after having expanded
120 ///               OR-patterns). However, there might be wildcard patterns (`_`) present. Thus, we
121 ///               are only really concerned with the other patterns leading with wildcards. This is
122 ///               where `D` comes in:
123 ///               `U(P, p_{m + 1}) := U(D(P), p_({m + 1},2), ..,  p_({m + 1},n))`
124 ///         - If `p_{m + 1} == r_1 | r_2`, then the usefulness depends on each separately:
125 ///           `U(P, p_{m + 1}) := U(P, (r_1, p_({m + 1},2), .., p_({m + 1},n)))
126 ///                            || U(P, (r_2, p_({m + 1},2), .., p_({m + 1},n)))`
127 ///
128 /// Modifications to the algorithm
129 /// ------------------------------
130 /// The algorithm in the paper doesn't cover some of the special cases that arise in Rust, for
131 /// example uninhabited types and variable-length slice patterns. These are drawn attention to
132 /// throughout the code below. I'll make a quick note here about how exhaustive integer matching
133 /// is accounted for, though.
134 ///
135 /// Exhaustive integer matching
136 /// ---------------------------
137 /// An integer type can be thought of as a (huge) sum type: 1 | 2 | 3 | ...
138 /// So to support exhaustive integer matching, we can make use of the logic in the paper for
139 /// OR-patterns. However, we obviously can't just treat ranges x..=y as individual sums, because
140 /// they are likely gigantic. So we instead treat ranges as constructors of the integers. This means
141 /// that we have a constructor *of* constructors (the integers themselves). We then need to work
142 /// through all the inductive step rules above, deriving how the ranges would be treated as
143 /// OR-patterns, and making sure that they're treated in the same way even when they're ranges.
144 /// There are really only four special cases here:
145 /// - When we match on a constructor that's actually a range, we have to treat it as if we would
146 ///   an OR-pattern.
147 ///     + It turns out that we can simply extend the case for single-value patterns in
148 ///      `specialize` to either be *equal* to a value constructor, or *contained within* a range
149 ///      constructor.
150 ///     + When the pattern itself is a range, you just want to tell whether any of the values in
151 ///       the pattern range coincide with values in the constructor range, which is precisely
152 ///       intersection.
153 ///   Since when encountering a range pattern for a value constructor, we also use inclusion, it
154 ///   means that whenever the constructor is a value/range and the pattern is also a value/range,
155 ///   we can simply use intersection to test usefulness.
156 /// - When we're testing for usefulness of a pattern and the pattern's first component is a
157 ///   wildcard.
158 ///     + If all the constructors appear in the matrix, we have a slight complication. By default,
159 ///       the behaviour (i.e. a disjunction over specialised matrices for each constructor) is
160 ///       invalid, because we want a disjunction over every *integer* in each range, not just a
161 ///       disjunction over every range. This is a bit more tricky to deal with: essentially we need
162 ///       to form equivalence classes of subranges of the constructor range for which the behaviour
163 ///       of the matrix `P` and new pattern `p_{m + 1}` are the same. This is described in more
164 ///       detail in `split_grouped_constructors`.
165 ///     + If some constructors are missing from the matrix, it turns out we don't need to do
166 ///       anything special (because we know none of the integers are actually wildcards: i.e. we
167 ///       can't span wildcards using ranges).
168
169 use self::Constructor::*;
170 use self::Usefulness::*;
171 use self::WitnessPreference::*;
172
173 use rustc_data_structures::fx::FxHashMap;
174 use rustc_data_structures::indexed_vec::Idx;
175
176 use super::{FieldPattern, Pattern, PatternKind};
177 use super::{PatternFoldable, PatternFolder, compare_const_vals};
178
179 use rustc::hir::def_id::DefId;
180 use rustc::hir::RangeEnd;
181 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
182 use rustc::ty::layout::{Integer, IntegerExt, VariantIdx};
183
184 use rustc::mir::Field;
185 use rustc::mir::interpret::ConstValue;
186 use rustc::util::common::ErrorReported;
187
188 use syntax::attr::{SignedInt, UnsignedInt};
189 use syntax_pos::{Span, DUMMY_SP};
190
191 use arena::TypedArena;
192
193 use std::cmp::{self, Ordering, min, max};
194 use std::fmt;
195 use std::iter::{FromIterator, IntoIterator};
196 use std::ops::RangeInclusive;
197 use std::u128;
198
199 pub fn expand_pattern<'a, 'tcx>(cx: &MatchCheckCtxt<'a, 'tcx>, pat: Pattern<'tcx>)
200                                 -> &'a Pattern<'tcx>
201 {
202     cx.pattern_arena.alloc(LiteralExpander.fold_pattern(&pat))
203 }
204
205 struct LiteralExpander;
206 impl<'tcx> PatternFolder<'tcx> for LiteralExpander {
207     fn fold_pattern(&mut self, pat: &Pattern<'tcx>) -> Pattern<'tcx> {
208         match (&pat.ty.sty, &*pat.kind) {
209             (&ty::Ref(_, rty, _), &PatternKind::Constant { ref value }) => {
210                 Pattern {
211                     ty: pat.ty,
212                     span: pat.span,
213                     kind: box PatternKind::Deref {
214                         subpattern: Pattern {
215                             ty: rty,
216                             span: pat.span,
217                             kind: box PatternKind::Constant { value: value.clone() },
218                         }
219                     }
220                 }
221             }
222             (_, &PatternKind::Binding { subpattern: Some(ref s), .. }) => {
223                 s.fold_with(self)
224             }
225             _ => pat.super_fold_with(self)
226         }
227     }
228 }
229
230 impl<'tcx> Pattern<'tcx> {
231     fn is_wildcard(&self) -> bool {
232         match *self.kind {
233             PatternKind::Binding { subpattern: None, .. } | PatternKind::Wild =>
234                 true,
235             _ => false
236         }
237     }
238 }
239
240 pub struct Matrix<'a, 'tcx: 'a>(Vec<Vec<&'a Pattern<'tcx>>>);
241
242 impl<'a, 'tcx> Matrix<'a, 'tcx> {
243     pub fn empty() -> Self {
244         Matrix(vec![])
245     }
246
247     pub fn push(&mut self, row: Vec<&'a Pattern<'tcx>>) {
248         self.0.push(row)
249     }
250 }
251
252 /// Pretty-printer for matrices of patterns, example:
253 /// ++++++++++++++++++++++++++
254 /// + _     + []             +
255 /// ++++++++++++++++++++++++++
256 /// + true  + [First]        +
257 /// ++++++++++++++++++++++++++
258 /// + true  + [Second(true)] +
259 /// ++++++++++++++++++++++++++
260 /// + false + [_]            +
261 /// ++++++++++++++++++++++++++
262 /// + _     + [_, _, ..tail] +
263 /// ++++++++++++++++++++++++++
264 impl<'a, 'tcx> fmt::Debug for Matrix<'a, 'tcx> {
265     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
266         write!(f, "\n")?;
267
268         let &Matrix(ref m) = self;
269         let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| {
270             row.iter().map(|pat| format!("{:?}", pat)).collect()
271         }).collect();
272
273         let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0);
274         assert!(m.iter().all(|row| row.len() == column_count));
275         let column_widths: Vec<usize> = (0..column_count).map(|col| {
276             pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0)
277         }).collect();
278
279         let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1;
280         let br = "+".repeat(total_width);
281         write!(f, "{}\n", br)?;
282         for row in pretty_printed_matrix {
283             write!(f, "+")?;
284             for (column, pat_str) in row.into_iter().enumerate() {
285                 write!(f, " ")?;
286                 write!(f, "{:1$}", pat_str, column_widths[column])?;
287                 write!(f, " +")?;
288             }
289             write!(f, "\n")?;
290             write!(f, "{}\n", br)?;
291         }
292         Ok(())
293     }
294 }
295
296 impl<'a, 'tcx> FromIterator<Vec<&'a Pattern<'tcx>>> for Matrix<'a, 'tcx> {
297     fn from_iter<T: IntoIterator<Item=Vec<&'a Pattern<'tcx>>>>(iter: T) -> Self
298     {
299         Matrix(iter.into_iter().collect())
300     }
301 }
302
303 pub struct MatchCheckCtxt<'a, 'tcx: 'a> {
304     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
305     /// The module in which the match occurs. This is necessary for
306     /// checking inhabited-ness of types because whether a type is (visibly)
307     /// inhabited can depend on whether it was defined in the current module or
308     /// not. eg. `struct Foo { _private: ! }` cannot be seen to be empty
309     /// outside it's module and should not be matchable with an empty match
310     /// statement.
311     pub module: DefId,
312     pub pattern_arena: &'a TypedArena<Pattern<'tcx>>,
313     pub byte_array_map: FxHashMap<*const Pattern<'tcx>, Vec<&'a Pattern<'tcx>>>,
314 }
315
316 impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> {
317     pub fn create_and_enter<F, R>(
318         tcx: TyCtxt<'a, 'tcx, 'tcx>,
319         module: DefId,
320         f: F) -> R
321         where F: for<'b> FnOnce(MatchCheckCtxt<'b, 'tcx>) -> R
322     {
323         let pattern_arena = TypedArena::default();
324
325         f(MatchCheckCtxt {
326             tcx,
327             module,
328             pattern_arena: &pattern_arena,
329             byte_array_map: FxHashMap::default(),
330         })
331     }
332
333     // convert a byte-string pattern to a list of u8 patterns.
334     fn lower_byte_str_pattern<'p>(&mut self, pat: &'p Pattern<'tcx>) -> Vec<&'p Pattern<'tcx>>
335             where 'a: 'p
336     {
337         let pattern_arena = &*self.pattern_arena;
338         let tcx = self.tcx;
339         self.byte_array_map.entry(pat).or_insert_with(|| {
340             match pat.kind {
341                 box PatternKind::Constant {
342                     value: const_val
343                 } => {
344                     if let Some(ptr) = const_val.to_ptr() {
345                         let is_array_ptr = const_val.ty
346                             .builtin_deref(true)
347                             .and_then(|t| t.ty.builtin_index())
348                             .map_or(false, |t| t == tcx.types.u8);
349                         assert!(is_array_ptr);
350                         let alloc = tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
351                         assert_eq!(ptr.offset.bytes(), 0);
352                         // FIXME: check length
353                         alloc.bytes.iter().map(|b| {
354                             &*pattern_arena.alloc(Pattern {
355                                 ty: tcx.types.u8,
356                                 span: pat.span,
357                                 kind: box PatternKind::Constant {
358                                     value: ty::Const::from_bits(
359                                         tcx,
360                                         *b as u128,
361                                         ty::ParamEnv::empty().and(tcx.types.u8))
362                                 }
363                             })
364                         }).collect()
365                     } else {
366                         bug!("not a byte str: {:?}", const_val)
367                     }
368                 }
369                 _ => span_bug!(pat.span, "unexpected byte array pattern {:?}", pat)
370             }
371         }).clone()
372     }
373
374     fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool {
375         if self.tcx.features().exhaustive_patterns {
376             self.tcx.is_ty_uninhabited_from(self.module, ty)
377         } else {
378             false
379         }
380     }
381
382     fn is_non_exhaustive_enum(&self, ty: Ty<'tcx>) -> bool {
383         match ty.sty {
384             ty::Adt(adt_def, ..) => adt_def.is_variant_list_non_exhaustive(),
385             _ => false,
386         }
387     }
388
389     fn is_local(&self, ty: Ty<'tcx>) -> bool {
390         match ty.sty {
391             ty::Adt(adt_def, ..) => adt_def.did.is_local(),
392             _ => false,
393         }
394     }
395
396     fn is_variant_uninhabited(&self,
397                               variant: &'tcx ty::VariantDef,
398                               substs: &'tcx ty::subst::Substs<'tcx>)
399                               -> bool
400     {
401         if self.tcx.features().exhaustive_patterns {
402             self.tcx.is_enum_variant_uninhabited_from(self.module, variant, substs)
403         } else {
404             false
405         }
406     }
407 }
408
409 #[derive(Clone, Debug, PartialEq)]
410 pub enum Constructor<'tcx> {
411     /// The constructor of all patterns that don't vary by constructor,
412     /// e.g. struct patterns and fixed-length arrays.
413     Single,
414     /// Enum variants.
415     Variant(DefId),
416     /// Literal values.
417     ConstantValue(&'tcx ty::Const<'tcx>),
418     /// Ranges of literal values (`2...5` and `2..5`).
419     ConstantRange(u128, u128, Ty<'tcx>, RangeEnd),
420     /// Array patterns of length n.
421     Slice(u64),
422 }
423
424 impl<'tcx> Constructor<'tcx> {
425     fn variant_index_for_adt(&self, adt: &'tcx ty::AdtDef) -> VariantIdx {
426         match self {
427             &Variant(vid) => adt.variant_index_with_id(vid),
428             &Single => {
429                 assert!(!adt.is_enum());
430                 VariantIdx::new(0)
431             }
432             _ => bug!("bad constructor {:?} for adt {:?}", self, adt)
433         }
434     }
435 }
436
437 #[derive(Clone, Debug)]
438 pub enum Usefulness<'tcx> {
439     Useful,
440     UsefulWithWitness(Vec<Witness<'tcx>>),
441     NotUseful
442 }
443
444 impl<'tcx> Usefulness<'tcx> {
445     fn is_useful(&self) -> bool {
446         match *self {
447             NotUseful => false,
448             _ => true
449         }
450     }
451 }
452
453 #[derive(Copy, Clone, Debug)]
454 pub enum WitnessPreference {
455     ConstructWitness,
456     LeaveOutWitness
457 }
458
459 #[derive(Copy, Clone, Debug)]
460 struct PatternContext<'tcx> {
461     ty: Ty<'tcx>,
462     max_slice_length: u64,
463 }
464
465 /// A witness of non-exhaustiveness for error reporting, represented
466 /// as a list of patterns (in reverse order of construction) with
467 /// wildcards inside to represent elements that can take any inhabitant
468 /// of the type as a value.
469 ///
470 /// A witness against a list of patterns should have the same types
471 /// and length as the pattern matched against. Because Rust `match`
472 /// is always against a single pattern, at the end the witness will
473 /// have length 1, but in the middle of the algorithm, it can contain
474 /// multiple patterns.
475 ///
476 /// For example, if we are constructing a witness for the match against
477 /// ```
478 /// struct Pair(Option<(u32, u32)>, bool);
479 ///
480 /// match (p: Pair) {
481 ///    Pair(None, _) => {}
482 ///    Pair(_, false) => {}
483 /// }
484 /// ```
485 ///
486 /// We'll perform the following steps:
487 /// 1. Start with an empty witness
488 ///     `Witness(vec![])`
489 /// 2. Push a witness `Some(_)` against the `None`
490 ///     `Witness(vec![Some(_)])`
491 /// 3. Push a witness `true` against the `false`
492 ///     `Witness(vec![Some(_), true])`
493 /// 4. Apply the `Pair` constructor to the witnesses
494 ///     `Witness(vec![Pair(Some(_), true)])`
495 ///
496 /// The final `Pair(Some(_), true)` is then the resulting witness.
497 #[derive(Clone, Debug)]
498 pub struct Witness<'tcx>(Vec<Pattern<'tcx>>);
499
500 impl<'tcx> Witness<'tcx> {
501     pub fn single_pattern(&self) -> &Pattern<'tcx> {
502         assert_eq!(self.0.len(), 1);
503         &self.0[0]
504     }
505
506     fn push_wild_constructor<'a>(
507         mut self,
508         cx: &MatchCheckCtxt<'a, 'tcx>,
509         ctor: &Constructor<'tcx>,
510         ty: Ty<'tcx>)
511         -> Self
512     {
513         let sub_pattern_tys = constructor_sub_pattern_tys(cx, ctor, ty);
514         self.0.extend(sub_pattern_tys.into_iter().map(|ty| {
515             Pattern {
516                 ty,
517                 span: DUMMY_SP,
518                 kind: box PatternKind::Wild,
519             }
520         }));
521         self.apply_constructor(cx, ctor, ty)
522     }
523
524
525     /// Constructs a partial witness for a pattern given a list of
526     /// patterns expanded by the specialization step.
527     ///
528     /// When a pattern P is discovered to be useful, this function is used bottom-up
529     /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
530     /// of values, V, where each value in that set is not covered by any previously
531     /// used patterns and is covered by the pattern P'. Examples:
532     ///
533     /// left_ty: tuple of 3 elements
534     /// pats: [10, 20, _]           => (10, 20, _)
535     ///
536     /// left_ty: struct X { a: (bool, &'static str), b: usize}
537     /// pats: [(false, "foo"), 42]  => X { a: (false, "foo"), b: 42 }
538     fn apply_constructor<'a>(
539         mut self,
540         cx: &MatchCheckCtxt<'a,'tcx>,
541         ctor: &Constructor<'tcx>,
542         ty: Ty<'tcx>)
543         -> Self
544     {
545         let arity = constructor_arity(cx, ctor, ty);
546         let pat = {
547             let len = self.0.len() as u64;
548             let mut pats = self.0.drain((len - arity) as usize..).rev();
549
550             match ty.sty {
551                 ty::Adt(..) |
552                 ty::Tuple(..) => {
553                     let pats = pats.enumerate().map(|(i, p)| {
554                         FieldPattern {
555                             field: Field::new(i),
556                             pattern: p
557                         }
558                     }).collect();
559
560                     if let ty::Adt(adt, substs) = ty.sty {
561                         if adt.is_enum() {
562                             PatternKind::Variant {
563                                 adt_def: adt,
564                                 substs,
565                                 variant_index: ctor.variant_index_for_adt(adt),
566                                 subpatterns: pats
567                             }
568                         } else {
569                             PatternKind::Leaf { subpatterns: pats }
570                         }
571                     } else {
572                         PatternKind::Leaf { subpatterns: pats }
573                     }
574                 }
575
576                 ty::Ref(..) => {
577                     PatternKind::Deref { subpattern: pats.nth(0).unwrap() }
578                 }
579
580                 ty::Slice(_) | ty::Array(..) => {
581                     PatternKind::Slice {
582                         prefix: pats.collect(),
583                         slice: None,
584                         suffix: vec![]
585                     }
586                 }
587
588                 _ => {
589                     match *ctor {
590                         ConstantValue(value) => PatternKind::Constant { value },
591                         ConstantRange(lo, hi, ty, end) => PatternKind::Range {
592                             lo: ty::Const::from_bits(cx.tcx, lo, ty::ParamEnv::empty().and(ty)),
593                             hi: ty::Const::from_bits(cx.tcx, hi, ty::ParamEnv::empty().and(ty)),
594                             ty,
595                             end,
596                         },
597                         _ => PatternKind::Wild,
598                     }
599                 }
600             }
601         };
602
603         self.0.push(Pattern {
604             ty,
605             span: DUMMY_SP,
606             kind: Box::new(pat),
607         });
608
609         self
610     }
611 }
612
613 /// This determines the set of all possible constructors of a pattern matching
614 /// values of type `left_ty`. For vectors, this would normally be an infinite set
615 /// but is instead bounded by the maximum fixed length of slice patterns in
616 /// the column of patterns being analyzed.
617 ///
618 /// We make sure to omit constructors that are statically impossible. eg for
619 /// Option<!> we do not include Some(_) in the returned list of constructors.
620 fn all_constructors<'a, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
621                                   pcx: PatternContext<'tcx>)
622                                   -> Vec<Constructor<'tcx>>
623 {
624     debug!("all_constructors({:?})", pcx.ty);
625     let exhaustive_integer_patterns = cx.tcx.features().exhaustive_integer_patterns;
626     let ctors = match pcx.ty.sty {
627         ty::Bool => {
628             [true, false].iter().map(|&b| {
629                 ConstantValue(ty::Const::from_bool(cx.tcx, b))
630             }).collect()
631         }
632         ty::Array(ref sub_ty, len) if len.assert_usize(cx.tcx).is_some() => {
633             let len = len.unwrap_usize(cx.tcx);
634             if len != 0 && cx.is_uninhabited(sub_ty) {
635                 vec![]
636             } else {
637                 vec![Slice(len)]
638             }
639         }
640         // Treat arrays of a constant but unknown length like slices.
641         ty::Array(ref sub_ty, _) |
642         ty::Slice(ref sub_ty) => {
643             if cx.is_uninhabited(sub_ty) {
644                 vec![Slice(0)]
645             } else {
646                 (0..pcx.max_slice_length+1).map(|length| Slice(length)).collect()
647             }
648         }
649         ty::Adt(def, substs) if def.is_enum() => {
650             def.variants.iter()
651                 .filter(|v| !cx.is_variant_uninhabited(v, substs))
652                 .map(|v| Variant(v.did))
653                 .collect()
654         }
655         ty::Char if exhaustive_integer_patterns => {
656             vec![
657                 // The valid Unicode Scalar Value ranges.
658                 ConstantRange('\u{0000}' as u128,
659                               '\u{D7FF}' as u128,
660                               cx.tcx.types.char,
661                               RangeEnd::Included
662                 ),
663                 ConstantRange('\u{E000}' as u128,
664                               '\u{10FFFF}' as u128,
665                               cx.tcx.types.char,
666                               RangeEnd::Included
667                 ),
668             ]
669         }
670         ty::Int(ity) if exhaustive_integer_patterns => {
671             // FIXME(49937): refactor these bit manipulations into interpret.
672             let bits = Integer::from_attr(&cx.tcx, SignedInt(ity)).size().bits() as u128;
673             let min = 1u128 << (bits - 1);
674             let max = (1u128 << (bits - 1)) - 1;
675             vec![ConstantRange(min, max, pcx.ty, RangeEnd::Included)]
676         }
677         ty::Uint(uty) if exhaustive_integer_patterns => {
678             // FIXME(49937): refactor these bit manipulations into interpret.
679             let bits = Integer::from_attr(&cx.tcx, UnsignedInt(uty)).size().bits() as u128;
680             let max = !0u128 >> (128 - bits);
681             vec![ConstantRange(0, max, pcx.ty, RangeEnd::Included)]
682         }
683         _ => {
684             if cx.is_uninhabited(pcx.ty) {
685                 vec![]
686             } else {
687                 vec![Single]
688             }
689         }
690     };
691     ctors
692 }
693
694 fn max_slice_length<'p, 'a: 'p, 'tcx: 'a, I>(
695     cx: &mut MatchCheckCtxt<'a, 'tcx>,
696     patterns: I) -> u64
697     where I: Iterator<Item=&'p Pattern<'tcx>>
698 {
699     // The exhaustiveness-checking paper does not include any details on
700     // checking variable-length slice patterns. However, they are matched
701     // by an infinite collection of fixed-length array patterns.
702     //
703     // Checking the infinite set directly would take an infinite amount
704     // of time. However, it turns out that for each finite set of
705     // patterns `P`, all sufficiently large array lengths are equivalent:
706     //
707     // Each slice `s` with a "sufficiently-large" length `l ≥ L` that applies
708     // to exactly the subset `Pₜ` of `P` can be transformed to a slice
709     // `sₘ` for each sufficiently-large length `m` that applies to exactly
710     // the same subset of `P`.
711     //
712     // Because of that, each witness for reachability-checking from one
713     // of the sufficiently-large lengths can be transformed to an
714     // equally-valid witness from any other length, so we only have
715     // to check slice lengths from the "minimal sufficiently-large length"
716     // and below.
717     //
718     // Note that the fact that there is a *single* `sₘ` for each `m`
719     // not depending on the specific pattern in `P` is important: if
720     // you look at the pair of patterns
721     //     `[true, ..]`
722     //     `[.., false]`
723     // Then any slice of length ≥1 that matches one of these two
724     // patterns can be trivially turned to a slice of any
725     // other length ≥1 that matches them and vice-versa - for
726     // but the slice from length 2 `[false, true]` that matches neither
727     // of these patterns can't be turned to a slice from length 1 that
728     // matches neither of these patterns, so we have to consider
729     // slices from length 2 there.
730     //
731     // Now, to see that that length exists and find it, observe that slice
732     // patterns are either "fixed-length" patterns (`[_, _, _]`) or
733     // "variable-length" patterns (`[_, .., _]`).
734     //
735     // For fixed-length patterns, all slices with lengths *longer* than
736     // the pattern's length have the same outcome (of not matching), so
737     // as long as `L` is greater than the pattern's length we can pick
738     // any `sₘ` from that length and get the same result.
739     //
740     // For variable-length patterns, the situation is more complicated,
741     // because as seen above the precise value of `sₘ` matters.
742     //
743     // However, for each variable-length pattern `p` with a prefix of length
744     // `plₚ` and suffix of length `slₚ`, only the first `plₚ` and the last
745     // `slₚ` elements are examined.
746     //
747     // Therefore, as long as `L` is positive (to avoid concerns about empty
748     // types), all elements after the maximum prefix length and before
749     // the maximum suffix length are not examined by any variable-length
750     // pattern, and therefore can be added/removed without affecting
751     // them - creating equivalent patterns from any sufficiently-large
752     // length.
753     //
754     // Of course, if fixed-length patterns exist, we must be sure
755     // that our length is large enough to miss them all, so
756     // we can pick `L = max(FIXED_LEN+1 ∪ {max(PREFIX_LEN) + max(SUFFIX_LEN)})`
757     //
758     // for example, with the above pair of patterns, all elements
759     // but the first and last can be added/removed, so any
760     // witness of length ≥2 (say, `[false, false, true]`) can be
761     // turned to a witness from any other length ≥2.
762
763     let mut max_prefix_len = 0;
764     let mut max_suffix_len = 0;
765     let mut max_fixed_len = 0;
766
767     for row in patterns {
768         match *row.kind {
769             PatternKind::Constant { value } => {
770                 if let Some(ptr) = value.to_ptr() {
771                     let is_array_ptr = value.ty
772                         .builtin_deref(true)
773                         .and_then(|t| t.ty.builtin_index())
774                         .map_or(false, |t| t == cx.tcx.types.u8);
775                     if is_array_ptr {
776                         let alloc = cx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
777                         max_fixed_len = cmp::max(max_fixed_len, alloc.bytes.len() as u64);
778                     }
779                 }
780             }
781             PatternKind::Slice { ref prefix, slice: None, ref suffix } => {
782                 let fixed_len = prefix.len() as u64 + suffix.len() as u64;
783                 max_fixed_len = cmp::max(max_fixed_len, fixed_len);
784             }
785             PatternKind::Slice { ref prefix, slice: Some(_), ref suffix } => {
786                 max_prefix_len = cmp::max(max_prefix_len, prefix.len() as u64);
787                 max_suffix_len = cmp::max(max_suffix_len, suffix.len() as u64);
788             }
789             _ => {}
790         }
791     }
792
793     cmp::max(max_fixed_len + 1, max_prefix_len + max_suffix_len)
794 }
795
796 /// An inclusive interval, used for precise integer exhaustiveness checking.
797 /// `IntRange`s always store a contiguous range. This means that values are
798 /// encoded such that `0` encodes the minimum value for the integer,
799 /// regardless of the signedness.
800 /// For example, the pattern `-128...127i8` is encoded as `0..=255`.
801 /// This makes comparisons and arithmetic on interval endpoints much more
802 /// straightforward. See `signed_bias` for details.
803 ///
804 /// `IntRange` is never used to encode an empty range or a "range" that wraps
805 /// around the (offset) space: i.e. `range.lo <= range.hi`.
806 #[derive(Clone)]
807 struct IntRange<'tcx> {
808     pub range: RangeInclusive<u128>,
809     pub ty: Ty<'tcx>,
810 }
811
812 impl<'tcx> IntRange<'tcx> {
813     fn from_ctor(tcx: TyCtxt<'_, 'tcx, 'tcx>,
814                  ctor: &Constructor<'tcx>)
815                  -> Option<IntRange<'tcx>> {
816         match ctor {
817             ConstantRange(lo, hi, ty, end) => {
818                 // Perform a shift if the underlying types are signed,
819                 // which makes the interval arithmetic simpler.
820                 let bias = IntRange::signed_bias(tcx, ty);
821                 let (lo, hi) = (lo ^ bias, hi ^ bias);
822                 // Make sure the interval is well-formed.
823                 if lo > hi || lo == hi && *end == RangeEnd::Excluded {
824                     None
825                 } else {
826                     let offset = (*end == RangeEnd::Excluded) as u128;
827                     Some(IntRange { range: lo..=(hi - offset), ty })
828                 }
829             }
830             ConstantValue(val) => {
831                 let ty = val.ty;
832                 if let Some(val) = val.assert_bits(tcx, ty::ParamEnv::empty().and(ty)) {
833                     let bias = IntRange::signed_bias(tcx, ty);
834                     let val = val ^ bias;
835                     Some(IntRange { range: val..=val, ty })
836                 } else {
837                     None
838                 }
839             }
840             Single | Variant(_) | Slice(_) => {
841                 None
842             }
843         }
844     }
845
846     fn from_pat(tcx: TyCtxt<'_, 'tcx, 'tcx>,
847                 pat: &Pattern<'tcx>)
848                 -> Option<IntRange<'tcx>> {
849         Self::from_ctor(tcx, &match pat.kind {
850             box PatternKind::Constant { value } => ConstantValue(value),
851             box PatternKind::Range { lo, hi, ty, end } => ConstantRange(
852                 lo.to_bits(tcx, ty::ParamEnv::empty().and(ty)).unwrap(),
853                 hi.to_bits(tcx, ty::ParamEnv::empty().and(ty)).unwrap(),
854                 ty,
855                 end,
856             ),
857             _ => return None,
858         })
859     }
860
861     // The return value of `signed_bias` should be XORed with an endpoint to encode/decode it.
862     fn signed_bias(tcx: TyCtxt<'_, 'tcx, 'tcx>, ty: Ty<'tcx>) -> u128 {
863         match ty.sty {
864             ty::Int(ity) => {
865                 let bits = Integer::from_attr(&tcx, SignedInt(ity)).size().bits() as u128;
866                 1u128 << (bits - 1)
867             }
868             _ => 0
869         }
870     }
871
872     /// Convert a `RangeInclusive` to a `ConstantValue` or inclusive `ConstantRange`.
873     fn range_to_ctor(
874         tcx: TyCtxt<'_, 'tcx, 'tcx>,
875         ty: Ty<'tcx>,
876         r: RangeInclusive<u128>,
877     ) -> Constructor<'tcx> {
878         let bias = IntRange::signed_bias(tcx, ty);
879         let (lo, hi) = r.into_inner();
880         if lo == hi {
881             let ty = ty::ParamEnv::empty().and(ty);
882             ConstantValue(ty::Const::from_bits(tcx, lo ^ bias, ty))
883         } else {
884             ConstantRange(lo ^ bias, hi ^ bias, ty, RangeEnd::Included)
885         }
886     }
887
888     /// Return a collection of ranges that spans the values covered by `ranges`, subtracted
889     /// by the values covered by `self`: i.e. `ranges \ self` (in set notation).
890     fn subtract_from(self,
891                      tcx: TyCtxt<'_, 'tcx, 'tcx>,
892                      ranges: Vec<Constructor<'tcx>>)
893                      -> Vec<Constructor<'tcx>> {
894         let ranges = ranges.into_iter().filter_map(|r| {
895             IntRange::from_ctor(tcx, &r).map(|i| i.range)
896         });
897         let mut remaining_ranges = vec![];
898         let ty = self.ty;
899         let (lo, hi) = self.range.into_inner();
900         for subrange in ranges {
901             let (subrange_lo, subrange_hi) = subrange.into_inner();
902             if lo > subrange_hi || subrange_lo > hi  {
903                 // The pattern doesn't intersect with the subrange at all,
904                 // so the subrange remains untouched.
905                 remaining_ranges.push(Self::range_to_ctor(tcx, ty, subrange_lo..=subrange_hi));
906             } else {
907                 if lo > subrange_lo {
908                     // The pattern intersects an upper section of the
909                     // subrange, so a lower section will remain.
910                     remaining_ranges.push(Self::range_to_ctor(tcx, ty, subrange_lo..=(lo - 1)));
911                 }
912                 if hi < subrange_hi {
913                     // The pattern intersects a lower section of the
914                     // subrange, so an upper section will remain.
915                     remaining_ranges.push(Self::range_to_ctor(tcx, ty, (hi + 1)..=subrange_hi));
916                 }
917             }
918         }
919         remaining_ranges
920     }
921
922     fn intersection(&self, other: &Self) -> Option<Self> {
923         let ty = self.ty;
924         let (lo, hi) = (*self.range.start(), *self.range.end());
925         let (other_lo, other_hi) = (*other.range.start(), *other.range.end());
926         if lo <= other_hi && other_lo <= hi {
927             Some(IntRange { range: max(lo, other_lo)..=min(hi, other_hi), ty })
928         } else {
929             None
930         }
931     }
932 }
933
934 // A request for missing constructor data in terms of either:
935 // - whether or not there any missing constructors; or
936 // - the actual set of missing constructors.
937 #[derive(PartialEq)]
938 enum MissingCtorsInfo {
939     Emptiness,
940     Ctors,
941 }
942
943 // Used by `compute_missing_ctors`.
944 #[derive(Debug, PartialEq)]
945 enum MissingCtors<'tcx> {
946     Empty,
947     NonEmpty,
948
949     // Note that the Vec can be empty.
950     Ctors(Vec<Constructor<'tcx>>),
951 }
952
953 // When `info` is `MissingCtorsInfo::Ctors`, compute a set of constructors
954 // equivalent to `all_ctors \ used_ctors`. When `info` is
955 // `MissingCtorsInfo::Emptiness`, just determines if that set is empty or not.
956 // (The split logic gives a performance win, because we always need to know if
957 // the set is empty, but we rarely need the full set, and it can be expensive
958 // to compute the full set.)
959 fn compute_missing_ctors<'a, 'tcx: 'a>(
960     info: MissingCtorsInfo,
961     tcx: TyCtxt<'a, 'tcx, 'tcx>,
962     all_ctors: &Vec<Constructor<'tcx>>,
963     used_ctors: &Vec<Constructor<'tcx>>,
964 ) -> MissingCtors<'tcx> {
965     let mut missing_ctors = vec![];
966
967     for req_ctor in all_ctors {
968         let mut refined_ctors = vec![req_ctor.clone()];
969         for used_ctor in used_ctors {
970             if used_ctor == req_ctor {
971                 // If a constructor appears in a `match` arm, we can
972                 // eliminate it straight away.
973                 refined_ctors = vec![]
974             } else if tcx.features().exhaustive_integer_patterns {
975                 if let Some(interval) = IntRange::from_ctor(tcx, used_ctor) {
976                     // Refine the required constructors for the type by subtracting
977                     // the range defined by the current constructor pattern.
978                     refined_ctors = interval.subtract_from(tcx, refined_ctors);
979                 }
980             }
981
982             // If the constructor patterns that have been considered so far
983             // already cover the entire range of values, then we the
984             // constructor is not missing, and we can move on to the next one.
985             if refined_ctors.is_empty() {
986                 break;
987             }
988         }
989         // If a constructor has not been matched, then it is missing.
990         // We add `refined_ctors` instead of `req_ctor`, because then we can
991         // provide more detailed error information about precisely which
992         // ranges have been omitted.
993         if info == MissingCtorsInfo::Emptiness {
994             if !refined_ctors.is_empty() {
995                 // The set is non-empty; return early.
996                 return MissingCtors::NonEmpty;
997             }
998         } else {
999             missing_ctors.extend(refined_ctors);
1000         }
1001     }
1002
1003     if info == MissingCtorsInfo::Emptiness {
1004         // If we reached here, the set is empty.
1005         MissingCtors::Empty
1006     } else {
1007         MissingCtors::Ctors(missing_ctors)
1008     }
1009 }
1010
1011 /// Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
1012 /// The algorithm from the paper has been modified to correctly handle empty
1013 /// types. The changes are:
1014 ///   (0) We don't exit early if the pattern matrix has zero rows. We just
1015 ///       continue to recurse over columns.
1016 ///   (1) all_constructors will only return constructors that are statically
1017 ///       possible. eg. it will only return Ok for Result<T, !>
1018 ///
1019 /// This finds whether a (row) vector `v` of patterns is 'useful' in relation
1020 /// to a set of such vectors `m` - this is defined as there being a set of
1021 /// inputs that will match `v` but not any of the sets in `m`.
1022 ///
1023 /// All the patterns at each column of the `matrix ++ v` matrix must
1024 /// have the same type, except that wildcard (PatternKind::Wild) patterns
1025 /// with type TyErr are also allowed, even if the "type of the column"
1026 /// is not TyErr. That is used to represent private fields, as using their
1027 /// real type would assert that they are inhabited.
1028 ///
1029 /// This is used both for reachability checking (if a pattern isn't useful in
1030 /// relation to preceding patterns, it is not reachable) and exhaustiveness
1031 /// checking (if a wildcard pattern is useful in relation to a matrix, the
1032 /// matrix isn't exhaustive).
1033 pub fn is_useful<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
1034                                        matrix: &Matrix<'p, 'tcx>,
1035                                        v: &[&'p Pattern<'tcx>],
1036                                        witness: WitnessPreference)
1037                                        -> Usefulness<'tcx> {
1038     let &Matrix(ref rows) = matrix;
1039     debug!("is_useful({:#?}, {:#?})", matrix, v);
1040
1041     // The base case. We are pattern-matching on () and the return value is
1042     // based on whether our matrix has a row or not.
1043     // NOTE: This could potentially be optimized by checking rows.is_empty()
1044     // first and then, if v is non-empty, the return value is based on whether
1045     // the type of the tuple we're checking is inhabited or not.
1046     if v.is_empty() {
1047         return if rows.is_empty() {
1048             match witness {
1049                 ConstructWitness => UsefulWithWitness(vec![Witness(vec![])]),
1050                 LeaveOutWitness => Useful,
1051             }
1052         } else {
1053             NotUseful
1054         }
1055     };
1056
1057     assert!(rows.iter().all(|r| r.len() == v.len()));
1058
1059     let pcx = PatternContext {
1060         // TyErr is used to represent the type of wildcard patterns matching
1061         // against inaccessible (private) fields of structs, so that we won't
1062         // be able to observe whether the types of the struct's fields are
1063         // inhabited.
1064         //
1065         // If the field is truly inaccessible, then all the patterns
1066         // matching against it must be wildcard patterns, so its type
1067         // does not matter.
1068         //
1069         // However, if we are matching against non-wildcard patterns, we
1070         // need to know the real type of the field so we can specialize
1071         // against it. This primarily occurs through constants - they
1072         // can include contents for fields that are inaccessible at the
1073         // location of the match. In that case, the field's type is
1074         // inhabited - by the constant - so we can just use it.
1075         //
1076         // FIXME: this might lead to "unstable" behavior with macro hygiene
1077         // introducing uninhabited patterns for inaccessible fields. We
1078         // need to figure out how to model that.
1079         ty: rows.iter().map(|r| r[0].ty).find(|ty| !ty.references_error()).unwrap_or(v[0].ty),
1080         max_slice_length: max_slice_length(cx, rows.iter().map(|r| r[0]).chain(Some(v[0])))
1081     };
1082
1083     debug!("is_useful_expand_first_col: pcx={:#?}, expanding {:#?}", pcx, v[0]);
1084
1085     if let Some(constructors) = pat_constructors(cx, v[0], pcx) {
1086         debug!("is_useful - expanding constructors: {:#?}", constructors);
1087         split_grouped_constructors(cx.tcx, constructors, matrix, pcx.ty).into_iter().map(|c|
1088             is_useful_specialized(cx, matrix, v, c, pcx.ty, witness)
1089         ).find(|result| result.is_useful()).unwrap_or(NotUseful)
1090     } else {
1091         debug!("is_useful - expanding wildcard");
1092
1093         let used_ctors: Vec<Constructor> = rows.iter().flat_map(|row| {
1094             pat_constructors(cx, row[0], pcx).unwrap_or(vec![])
1095         }).collect();
1096         debug!("used_ctors = {:#?}", used_ctors);
1097         // `all_ctors` are all the constructors for the given type, which
1098         // should all be represented (or caught with the wild pattern `_`).
1099         let all_ctors = all_constructors(cx, pcx);
1100         debug!("all_ctors = {:#?}", all_ctors);
1101
1102         // `missing_ctors` is the set of constructors from the same type as the
1103         // first column of `matrix` that are matched only by wildcard patterns
1104         // from the first column.
1105         //
1106         // Therefore, if there is some pattern that is unmatched by `matrix`,
1107         // it will still be unmatched if the first constructor is replaced by
1108         // any of the constructors in `missing_ctors`
1109         //
1110         // However, if our scrutinee is *privately* an empty enum, we
1111         // must treat it as though it had an "unknown" constructor (in
1112         // that case, all other patterns obviously can't be variants)
1113         // to avoid exposing its emptyness. See the `match_privately_empty`
1114         // test for details.
1115         //
1116         // FIXME: currently the only way I know of something can
1117         // be a privately-empty enum is when the exhaustive_patterns
1118         // feature flag is not present, so this is only
1119         // needed for that case.
1120
1121         // Missing constructors are those that are not matched by any
1122         // non-wildcard patterns in the current column. We always determine if
1123         // the set is empty, but we only fully construct them on-demand,
1124         // because they're rarely used and can be big.
1125         let cheap_missing_ctors =
1126             compute_missing_ctors(MissingCtorsInfo::Emptiness, cx.tcx, &all_ctors, &used_ctors);
1127
1128         let is_privately_empty = all_ctors.is_empty() && !cx.is_uninhabited(pcx.ty);
1129         let is_declared_nonexhaustive = cx.is_non_exhaustive_enum(pcx.ty) && !cx.is_local(pcx.ty);
1130         debug!("cheap_missing_ctors={:#?} is_privately_empty={:#?} is_declared_nonexhaustive={:#?}",
1131                cheap_missing_ctors, is_privately_empty, is_declared_nonexhaustive);
1132
1133         // For privately empty and non-exhaustive enums, we work as if there were an "extra"
1134         // `_` constructor for the type, so we can never match over all constructors.
1135         let is_non_exhaustive = is_privately_empty || is_declared_nonexhaustive;
1136
1137         if cheap_missing_ctors == MissingCtors::Empty && !is_non_exhaustive {
1138             split_grouped_constructors(cx.tcx, all_ctors, matrix, pcx.ty).into_iter().map(|c| {
1139                 is_useful_specialized(cx, matrix, v, c, pcx.ty, witness)
1140             }).find(|result| result.is_useful()).unwrap_or(NotUseful)
1141         } else {
1142             let matrix = rows.iter().filter_map(|r| {
1143                 if r[0].is_wildcard() {
1144                     Some(r[1..].to_vec())
1145                 } else {
1146                     None
1147                 }
1148             }).collect();
1149             match is_useful(cx, &matrix, &v[1..], witness) {
1150                 UsefulWithWitness(pats) => {
1151                     let cx = &*cx;
1152                     // In this case, there's at least one "free"
1153                     // constructor that is only matched against by
1154                     // wildcard patterns.
1155                     //
1156                     // There are 2 ways we can report a witness here.
1157                     // Commonly, we can report all the "free"
1158                     // constructors as witnesses, e.g. if we have:
1159                     //
1160                     // ```
1161                     //     enum Direction { N, S, E, W }
1162                     //     let Direction::N = ...;
1163                     // ```
1164                     //
1165                     // we can report 3 witnesses: `S`, `E`, and `W`.
1166                     //
1167                     // However, there are 2 cases where we don't want
1168                     // to do this and instead report a single `_` witness:
1169                     //
1170                     // 1) If the user is matching against a non-exhaustive
1171                     // enum, there is no point in enumerating all possible
1172                     // variants, because the user can't actually match
1173                     // against them himself, e.g. in an example like:
1174                     // ```
1175                     //     let err: io::ErrorKind = ...;
1176                     //     match err {
1177                     //         io::ErrorKind::NotFound => {},
1178                     //     }
1179                     // ```
1180                     // we don't want to show every possible IO error,
1181                     // but instead have `_` as the witness (this is
1182                     // actually *required* if the user specified *all*
1183                     // IO errors, but is probably what we want in every
1184                     // case).
1185                     //
1186                     // 2) If the user didn't actually specify a constructor
1187                     // in this arm, e.g. in
1188                     // ```
1189                     //     let x: (Direction, Direction, bool) = ...;
1190                     //     let (_, _, false) = x;
1191                     // ```
1192                     // we don't want to show all 16 possible witnesses
1193                     // `(<direction-1>, <direction-2>, true)` - we are
1194                     // satisfied with `(_, _, true)`. In this case,
1195                     // `used_ctors` is empty.
1196                     let new_witnesses = if is_non_exhaustive || used_ctors.is_empty() {
1197                         // All constructors are unused. Add wild patterns
1198                         // rather than each individual constructor.
1199                         pats.into_iter().map(|mut witness| {
1200                             witness.0.push(Pattern {
1201                                 ty: pcx.ty,
1202                                 span: DUMMY_SP,
1203                                 kind: box PatternKind::Wild,
1204                             });
1205                             witness
1206                         }).collect()
1207                     } else {
1208                         let expensive_missing_ctors =
1209                             compute_missing_ctors(MissingCtorsInfo::Ctors, cx.tcx, &all_ctors,
1210                                                   &used_ctors);
1211                         if let MissingCtors::Ctors(missing_ctors) = expensive_missing_ctors {
1212                             pats.into_iter().flat_map(|witness| {
1213                                 missing_ctors.iter().map(move |ctor| {
1214                                     // Extends the witness with a "wild" version of this
1215                                     // constructor, that matches everything that can be built with
1216                                     // it. For example, if `ctor` is a `Constructor::Variant` for
1217                                     // `Option::Some`, this pushes the witness for `Some(_)`.
1218                                     witness.clone().push_wild_constructor(cx, ctor, pcx.ty)
1219                                 })
1220                             }).collect()
1221                         } else {
1222                             bug!("cheap missing ctors")
1223                         }
1224                     };
1225                     UsefulWithWitness(new_witnesses)
1226                 }
1227                 result => result
1228             }
1229         }
1230     }
1231 }
1232
1233 /// A shorthand for the `U(S(c, P), S(c, q))` operation from the paper. I.e. `is_useful` applied
1234 /// to the specialised version of both the pattern matrix `P` and the new pattern `q`.
1235 fn is_useful_specialized<'p, 'a:'p, 'tcx: 'a>(
1236     cx: &mut MatchCheckCtxt<'a, 'tcx>,
1237     &Matrix(ref m): &Matrix<'p, 'tcx>,
1238     v: &[&'p Pattern<'tcx>],
1239     ctor: Constructor<'tcx>,
1240     lty: Ty<'tcx>,
1241     witness: WitnessPreference,
1242 ) -> Usefulness<'tcx> {
1243     debug!("is_useful_specialized({:#?}, {:#?}, {:?})", v, ctor, lty);
1244     let sub_pat_tys = constructor_sub_pattern_tys(cx, &ctor, lty);
1245     let wild_patterns_owned: Vec<_> = sub_pat_tys.iter().map(|ty| {
1246         Pattern {
1247             ty,
1248             span: DUMMY_SP,
1249             kind: box PatternKind::Wild,
1250         }
1251     }).collect();
1252     let wild_patterns: Vec<_> = wild_patterns_owned.iter().collect();
1253     let matrix = Matrix(m.iter().flat_map(|r| {
1254         specialize(cx, &r, &ctor, &wild_patterns)
1255     }).collect());
1256     match specialize(cx, v, &ctor, &wild_patterns) {
1257         Some(v) => match is_useful(cx, &matrix, &v, witness) {
1258             UsefulWithWitness(witnesses) => UsefulWithWitness(
1259                 witnesses.into_iter()
1260                     .map(|witness| witness.apply_constructor(cx, &ctor, lty))
1261                     .collect()
1262             ),
1263             result => result
1264         }
1265         None => NotUseful
1266     }
1267 }
1268
1269 /// Determines the constructors that the given pattern can be specialized to.
1270 ///
1271 /// In most cases, there's only one constructor that a specific pattern
1272 /// represents, such as a specific enum variant or a specific literal value.
1273 /// Slice patterns, however, can match slices of different lengths. For instance,
1274 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
1275 ///
1276 /// Returns None in case of a catch-all, which can't be specialized.
1277 fn pat_constructors<'tcx>(cx: &mut MatchCheckCtxt<'_, 'tcx>,
1278                           pat: &Pattern<'tcx>,
1279                           pcx: PatternContext)
1280                           -> Option<Vec<Constructor<'tcx>>>
1281 {
1282     match *pat.kind {
1283         PatternKind::AscribeUserType { ref subpattern, .. } =>
1284             pat_constructors(cx, subpattern, pcx),
1285         PatternKind::Binding { .. } | PatternKind::Wild => None,
1286         PatternKind::Leaf { .. } | PatternKind::Deref { .. } => Some(vec![Single]),
1287         PatternKind::Variant { adt_def, variant_index, .. } => {
1288             Some(vec![Variant(adt_def.variants[variant_index].did)])
1289         }
1290         PatternKind::Constant { value } => Some(vec![ConstantValue(value)]),
1291         PatternKind::Range { lo, hi, ty, end } =>
1292             Some(vec![ConstantRange(
1293                 lo.to_bits(cx.tcx, ty::ParamEnv::empty().and(ty)).unwrap(),
1294                 hi.to_bits(cx.tcx, ty::ParamEnv::empty().and(ty)).unwrap(),
1295                 ty,
1296                 end,
1297             )]),
1298         PatternKind::Array { .. } => match pcx.ty.sty {
1299             ty::Array(_, length) => Some(vec![
1300                 Slice(length.unwrap_usize(cx.tcx))
1301             ]),
1302             _ => span_bug!(pat.span, "bad ty {:?} for array pattern", pcx.ty)
1303         },
1304         PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
1305             let pat_len = prefix.len() as u64 + suffix.len() as u64;
1306             if slice.is_some() {
1307                 Some((pat_len..pcx.max_slice_length+1).map(Slice).collect())
1308             } else {
1309                 Some(vec![Slice(pat_len)])
1310             }
1311         }
1312     }
1313 }
1314
1315 /// This computes the arity of a constructor. The arity of a constructor
1316 /// is how many subpattern patterns of that constructor should be expanded to.
1317 ///
1318 /// For instance, a tuple pattern (_, 42, Some([])) has the arity of 3.
1319 /// A struct pattern's arity is the number of fields it contains, etc.
1320 fn constructor_arity(_cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> u64 {
1321     debug!("constructor_arity({:#?}, {:?})", ctor, ty);
1322     match ty.sty {
1323         ty::Tuple(ref fs) => fs.len() as u64,
1324         ty::Slice(..) | ty::Array(..) => match *ctor {
1325             Slice(length) => length,
1326             ConstantValue(_) => 0,
1327             _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
1328         },
1329         ty::Ref(..) => 1,
1330         ty::Adt(adt, _) => {
1331             adt.variants[ctor.variant_index_for_adt(adt)].fields.len() as u64
1332         }
1333         _ => 0
1334     }
1335 }
1336
1337 /// This computes the types of the sub patterns that a constructor should be
1338 /// expanded to.
1339 ///
1340 /// For instance, a tuple pattern (43u32, 'a') has sub pattern types [u32, char].
1341 fn constructor_sub_pattern_tys<'a, 'tcx: 'a>(cx: &MatchCheckCtxt<'a, 'tcx>,
1342                                              ctor: &Constructor,
1343                                              ty: Ty<'tcx>) -> Vec<Ty<'tcx>>
1344 {
1345     debug!("constructor_sub_pattern_tys({:#?}, {:?})", ctor, ty);
1346     match ty.sty {
1347         ty::Tuple(ref fs) => fs.into_iter().map(|t| *t).collect(),
1348         ty::Slice(ty) | ty::Array(ty, _) => match *ctor {
1349             Slice(length) => (0..length).map(|_| ty).collect(),
1350             ConstantValue(_) => vec![],
1351             _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
1352         },
1353         ty::Ref(_, rty, _) => vec![rty],
1354         ty::Adt(adt, substs) => {
1355             if adt.is_box() {
1356                 // Use T as the sub pattern type of Box<T>.
1357                 vec![substs.type_at(0)]
1358             } else {
1359                 adt.variants[ctor.variant_index_for_adt(adt)].fields.iter().map(|field| {
1360                     let is_visible = adt.is_enum()
1361                         || field.vis.is_accessible_from(cx.module, cx.tcx);
1362                     if is_visible {
1363                         field.ty(cx.tcx, substs)
1364                     } else {
1365                         // Treat all non-visible fields as TyErr. They
1366                         // can't appear in any other pattern from
1367                         // this match (because they are private),
1368                         // so their type does not matter - but
1369                         // we don't want to know they are
1370                         // uninhabited.
1371                         cx.tcx.types.err
1372                     }
1373                 }).collect()
1374             }
1375         }
1376         _ => vec![],
1377     }
1378 }
1379
1380 fn slice_pat_covered_by_constructor<'tcx>(
1381     tcx: TyCtxt<'_, 'tcx, '_>,
1382     _span: Span,
1383     ctor: &Constructor,
1384     prefix: &[Pattern<'tcx>],
1385     slice: &Option<Pattern<'tcx>>,
1386     suffix: &[Pattern<'tcx>]
1387 ) -> Result<bool, ErrorReported> {
1388     let data: &[u8] = match *ctor {
1389         ConstantValue(const_val) => {
1390             let val = match const_val.val {
1391                 ConstValue::Unevaluated(..) |
1392                 ConstValue::ByRef(..) => bug!("unexpected ConstValue: {:?}", const_val),
1393                 ConstValue::Scalar(val) | ConstValue::ScalarPair(val, _) => val,
1394             };
1395             if let Ok(ptr) = val.to_ptr() {
1396                 let is_array_ptr = const_val.ty
1397                     .builtin_deref(true)
1398                     .and_then(|t| t.ty.builtin_index())
1399                     .map_or(false, |t| t == tcx.types.u8);
1400                 assert!(is_array_ptr);
1401                 tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id).bytes.as_ref()
1402             } else {
1403                 bug!("unexpected non-ptr ConstantValue")
1404             }
1405         }
1406         _ => bug!()
1407     };
1408
1409     let pat_len = prefix.len() + suffix.len();
1410     if data.len() < pat_len || (slice.is_none() && data.len() > pat_len) {
1411         return Ok(false);
1412     }
1413
1414     for (ch, pat) in
1415         data[..prefix.len()].iter().zip(prefix).chain(
1416             data[data.len()-suffix.len()..].iter().zip(suffix))
1417     {
1418         match pat.kind {
1419             box PatternKind::Constant { value } => {
1420                 let b = value.unwrap_bits(tcx, ty::ParamEnv::empty().and(pat.ty));
1421                 assert_eq!(b as u8 as u128, b);
1422                 if b as u8 != *ch {
1423                     return Ok(false);
1424                 }
1425             }
1426             _ => {}
1427         }
1428     }
1429
1430     Ok(true)
1431 }
1432
1433 // Whether to evaluate a constructor using exhaustive integer matching. This is true if the
1434 // constructor is a range or constant with an integer type.
1435 fn should_treat_range_exhaustively(tcx: TyCtxt<'_, 'tcx, 'tcx>, ctor: &Constructor<'tcx>) -> bool {
1436     if tcx.features().exhaustive_integer_patterns {
1437         let ty = match ctor {
1438             ConstantValue(value) => value.ty,
1439             ConstantRange(_, _, ty, _) => ty,
1440             _ => return false,
1441         };
1442         if let ty::Char | ty::Int(_) | ty::Uint(_) = ty.sty {
1443             return true;
1444         }
1445     }
1446     false
1447 }
1448
1449 /// For exhaustive integer matching, some constructors are grouped within other constructors
1450 /// (namely integer typed values are grouped within ranges). However, when specialising these
1451 /// constructors, we want to be specialising for the underlying constructors (the integers), not
1452 /// the groups (the ranges). Thus we need to split the groups up. Splitting them up naïvely would
1453 /// mean creating a separate constructor for every single value in the range, which is clearly
1454 /// impractical. However, observe that for some ranges of integers, the specialisation will be
1455 /// identical across all values in that range (i.e. there are equivalence classes of ranges of
1456 /// constructors based on their `is_useful_specialized` outcome). These classes are grouped by
1457 /// the patterns that apply to them (in the matrix `P`). We can split the range whenever the
1458 /// patterns that apply to that range (specifically: the patterns that *intersect* with that range)
1459 /// change.
1460 /// Our solution, therefore, is to split the range constructor into subranges at every single point
1461 /// the group of intersecting patterns changes (using the method described below).
1462 /// And voilà! We're testing precisely those ranges that we need to, without any exhaustive matching
1463 /// on actual integers. The nice thing about this is that the number of subranges is linear in the
1464 /// number of rows in the matrix (i.e. the number of cases in the `match` statement), so we don't
1465 /// need to be worried about matching over gargantuan ranges.
1466 ///
1467 /// Essentially, given the first column of a matrix representing ranges, looking like the following:
1468 ///
1469 /// |------|  |----------| |-------|    ||
1470 ///    |-------| |-------|            |----| ||
1471 ///       |---------|
1472 ///
1473 /// We split the ranges up into equivalence classes so the ranges are no longer overlapping:
1474 ///
1475 /// |--|--|||-||||--||---|||-------|  |-|||| ||
1476 ///
1477 /// The logic for determining how to split the ranges is fairly straightforward: we calculate
1478 /// boundaries for each interval range, sort them, then create constructors for each new interval
1479 /// between every pair of boundary points. (This essentially sums up to performing the intuitive
1480 /// merging operation depicted above.)
1481 fn split_grouped_constructors<'p, 'a: 'p, 'tcx: 'a>(
1482     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1483     ctors: Vec<Constructor<'tcx>>,
1484     &Matrix(ref m): &Matrix<'p, 'tcx>,
1485     ty: Ty<'tcx>,
1486 ) -> Vec<Constructor<'tcx>> {
1487     let mut split_ctors = Vec::with_capacity(ctors.len());
1488
1489     for ctor in ctors.into_iter() {
1490         match ctor {
1491             // For now, only ranges may denote groups of "subconstructors", so we only need to
1492             // special-case constant ranges.
1493             ConstantRange(..) if should_treat_range_exhaustively(tcx, &ctor) => {
1494                 // We only care about finding all the subranges within the range of the constructor
1495                 // range. Anything else is irrelevant, because it is guaranteed to result in
1496                 // `NotUseful`, which is the default case anyway, and can be ignored.
1497                 let ctor_range = IntRange::from_ctor(tcx, &ctor).unwrap();
1498
1499                 /// Represents a border between 2 integers. Because the intervals spanning borders
1500                 /// must be able to cover every integer, we need to be able to represent
1501                 /// 2^128 + 1 such borders.
1502                 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1503                 enum Border {
1504                     JustBefore(u128),
1505                     AfterMax,
1506                 }
1507
1508                 // A function for extracting the borders of an integer interval.
1509                 fn range_borders(r: IntRange<'_>) -> impl Iterator<Item = Border> {
1510                     let (lo, hi) = r.range.into_inner();
1511                     let from = Border::JustBefore(lo);
1512                     let to = match hi.checked_add(1) {
1513                         Some(m) => Border::JustBefore(m),
1514                         None => Border::AfterMax,
1515                     };
1516                     vec![from, to].into_iter()
1517                 }
1518
1519                 // `borders` is the set of borders between equivalence classes: each equivalence
1520                 // class lies between 2 borders.
1521                 let row_borders = m.iter()
1522                     .flat_map(|row| IntRange::from_pat(tcx, row[0]))
1523                     .flat_map(|range| ctor_range.intersection(&range))
1524                     .flat_map(|range| range_borders(range));
1525                 let ctor_borders = range_borders(ctor_range.clone());
1526                 let mut borders: Vec<_> = row_borders.chain(ctor_borders).collect();
1527                 borders.sort_unstable();
1528
1529                 // We're going to iterate through every pair of borders, making sure that each
1530                 // represents an interval of nonnegative length, and convert each such interval
1531                 // into a constructor.
1532                 for IntRange { range, .. } in borders.windows(2).filter_map(|window| {
1533                     match (window[0], window[1]) {
1534                         (Border::JustBefore(n), Border::JustBefore(m)) => {
1535                             if n < m {
1536                                 Some(IntRange { range: n..=(m - 1), ty })
1537                             } else {
1538                                 None
1539                             }
1540                         }
1541                         (Border::JustBefore(n), Border::AfterMax) => {
1542                             Some(IntRange { range: n..=u128::MAX, ty })
1543                         }
1544                         (Border::AfterMax, _) => None,
1545                     }
1546                 }) {
1547                     split_ctors.push(IntRange::range_to_ctor(tcx, ty, range));
1548                 }
1549             }
1550             // Any other constructor can be used unchanged.
1551             _ => split_ctors.push(ctor),
1552         }
1553     }
1554
1555     split_ctors
1556 }
1557
1558 /// Check whether there exists any shared value in either `ctor` or `pat` by intersecting them.
1559 fn constructor_intersects_pattern<'p, 'a: 'p, 'tcx: 'a>(
1560     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1561     ctor: &Constructor<'tcx>,
1562     pat: &'p Pattern<'tcx>,
1563 ) -> Option<Vec<&'p Pattern<'tcx>>> {
1564     if should_treat_range_exhaustively(tcx, ctor) {
1565         match (IntRange::from_ctor(tcx, ctor), IntRange::from_pat(tcx, pat)) {
1566             (Some(ctor), Some(pat)) => {
1567                 ctor.intersection(&pat).map(|_| {
1568                     let (pat_lo, pat_hi) = pat.range.into_inner();
1569                     let (ctor_lo, ctor_hi) = ctor.range.into_inner();
1570                     assert!(pat_lo <= ctor_lo && ctor_hi <= pat_hi);
1571                     vec![]
1572                 })
1573             }
1574             _ => None,
1575         }
1576     } else {
1577         // Fallback for non-ranges and ranges that involve floating-point numbers, which are not
1578         // conveniently handled by `IntRange`. For these cases, the constructor may not be a range
1579         // so intersection actually devolves into being covered by the pattern.
1580         match constructor_covered_by_range(tcx, ctor, pat) {
1581             Ok(true) => Some(vec![]),
1582             Ok(false) | Err(ErrorReported) => None,
1583         }
1584     }
1585 }
1586
1587 fn constructor_covered_by_range<'a, 'tcx>(
1588     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1589     ctor: &Constructor<'tcx>,
1590     pat: &Pattern<'tcx>,
1591 ) -> Result<bool, ErrorReported> {
1592     let (from, to, end, ty) = match pat.kind {
1593         box PatternKind::Constant { value } => (value, value, RangeEnd::Included, value.ty),
1594         box PatternKind::Range { lo, hi, ty, end } => (lo, hi, end, ty),
1595         _ => bug!("`constructor_covered_by_range` called with {:?}", pat),
1596     };
1597     trace!("constructor_covered_by_range {:#?}, {:#?}, {:#?}, {}", ctor, from, to, ty);
1598     let cmp_from = |c_from| compare_const_vals(tcx, c_from, from, ty::ParamEnv::empty().and(ty))
1599         .map(|res| res != Ordering::Less);
1600     let cmp_to = |c_to| compare_const_vals(tcx, c_to, to, ty::ParamEnv::empty().and(ty));
1601     macro_rules! some_or_ok {
1602         ($e:expr) => {
1603             match $e {
1604                 Some(to) => to,
1605                 None => return Ok(false), // not char or int
1606             }
1607         };
1608     }
1609     match *ctor {
1610         ConstantValue(value) => {
1611             let to = some_or_ok!(cmp_to(value));
1612             let end = (to == Ordering::Less) ||
1613                       (end == RangeEnd::Included && to == Ordering::Equal);
1614             Ok(some_or_ok!(cmp_from(value)) && end)
1615         },
1616         ConstantRange(from, to, ty, RangeEnd::Included) => {
1617             let to = some_or_ok!(cmp_to(ty::Const::from_bits(
1618                 tcx,
1619                 to,
1620                 ty::ParamEnv::empty().and(ty),
1621             )));
1622             let end = (to == Ordering::Less) ||
1623                       (end == RangeEnd::Included && to == Ordering::Equal);
1624             Ok(some_or_ok!(cmp_from(ty::Const::from_bits(
1625                 tcx,
1626                 from,
1627                 ty::ParamEnv::empty().and(ty),
1628             ))) && end)
1629         },
1630         ConstantRange(from, to, ty, RangeEnd::Excluded) => {
1631             let to = some_or_ok!(cmp_to(ty::Const::from_bits(
1632                 tcx,
1633                 to,
1634                 ty::ParamEnv::empty().and(ty)
1635             )));
1636             let end = (to == Ordering::Less) ||
1637                       (end == RangeEnd::Excluded && to == Ordering::Equal);
1638             Ok(some_or_ok!(cmp_from(ty::Const::from_bits(
1639                 tcx,
1640                 from,
1641                 ty::ParamEnv::empty().and(ty)))
1642             ) && end)
1643         }
1644         Single => Ok(true),
1645         _ => bug!(),
1646     }
1647 }
1648
1649 fn patterns_for_variant<'p, 'a: 'p, 'tcx: 'a>(
1650     subpatterns: &'p [FieldPattern<'tcx>],
1651     wild_patterns: &[&'p Pattern<'tcx>])
1652     -> Vec<&'p Pattern<'tcx>>
1653 {
1654     let mut result = wild_patterns.to_owned();
1655
1656     for subpat in subpatterns {
1657         result[subpat.field.index()] = &subpat.pattern;
1658     }
1659
1660     debug!("patterns_for_variant({:#?}, {:#?}) = {:#?}", subpatterns, wild_patterns, result);
1661     result
1662 }
1663
1664 /// This is the main specialization step. It expands the first pattern in the given row
1665 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
1666 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
1667 ///
1668 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
1669 /// different patterns.
1670 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
1671 /// fields filled with wild patterns.
1672 fn specialize<'p, 'a: 'p, 'tcx: 'a>(
1673     cx: &mut MatchCheckCtxt<'a, 'tcx>,
1674     r: &[&'p Pattern<'tcx>],
1675     constructor: &Constructor<'tcx>,
1676     wild_patterns: &[&'p Pattern<'tcx>],
1677 ) -> Option<Vec<&'p Pattern<'tcx>>> {
1678     let pat = &r[0];
1679
1680     let head: Option<Vec<&Pattern>> = match *pat.kind {
1681         PatternKind::AscribeUserType { ref subpattern, .. } =>
1682             specialize(cx, ::std::slice::from_ref(&subpattern), constructor, wild_patterns),
1683
1684         PatternKind::Binding { .. } | PatternKind::Wild => {
1685             Some(wild_patterns.to_owned())
1686         }
1687
1688         PatternKind::Variant { adt_def, variant_index, ref subpatterns, .. } => {
1689             let ref variant = adt_def.variants[variant_index];
1690             if *constructor == Variant(variant.did) {
1691                 Some(patterns_for_variant(subpatterns, wild_patterns))
1692             } else {
1693                 None
1694             }
1695         }
1696
1697         PatternKind::Leaf { ref subpatterns } => {
1698             Some(patterns_for_variant(subpatterns, wild_patterns))
1699         }
1700
1701         PatternKind::Deref { ref subpattern } => {
1702             Some(vec![subpattern])
1703         }
1704
1705         PatternKind::Constant { value } => {
1706             match *constructor {
1707                 Slice(..) => {
1708                     if let Some(ptr) = value.to_ptr() {
1709                         let is_array_ptr = value.ty
1710                             .builtin_deref(true)
1711                             .and_then(|t| t.ty.builtin_index())
1712                             .map_or(false, |t| t == cx.tcx.types.u8);
1713                         assert!(is_array_ptr);
1714                         let data_len = cx.tcx
1715                             .alloc_map
1716                             .lock()
1717                             .unwrap_memory(ptr.alloc_id)
1718                             .bytes
1719                             .len();
1720                         if wild_patterns.len() == data_len {
1721                             Some(cx.lower_byte_str_pattern(pat))
1722                         } else {
1723                             None
1724                         }
1725                     } else {
1726                         span_bug!(pat.span,
1727                         "unexpected const-val {:?} with ctor {:?}", value, constructor)
1728                     }
1729                 }
1730                 _ => {
1731                     // If the constructor is a:
1732                     //      Single value: add a row if the constructor equals the pattern.
1733                     //      Range: add a row if the constructor contains the pattern.
1734                     constructor_intersects_pattern(cx.tcx, constructor, pat)
1735                 }
1736             }
1737         }
1738
1739         PatternKind::Range { .. } => {
1740             // If the constructor is a:
1741             //      Single value: add a row if the pattern contains the constructor.
1742             //      Range: add a row if the constructor intersects the pattern.
1743             constructor_intersects_pattern(cx.tcx, constructor, pat)
1744         }
1745
1746         PatternKind::Array { ref prefix, ref slice, ref suffix } |
1747         PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
1748             match *constructor {
1749                 Slice(..) => {
1750                     let pat_len = prefix.len() + suffix.len();
1751                     if let Some(slice_count) = wild_patterns.len().checked_sub(pat_len) {
1752                         if slice_count == 0 || slice.is_some() {
1753                             Some(prefix.iter().chain(
1754                                     wild_patterns.iter().map(|p| *p)
1755                                                  .skip(prefix.len())
1756                                                  .take(slice_count)
1757                                                  .chain(suffix.iter())
1758                             ).collect())
1759                         } else {
1760                             None
1761                         }
1762                     } else {
1763                         None
1764                     }
1765                 }
1766                 ConstantValue(..) => {
1767                     match slice_pat_covered_by_constructor(
1768                         cx.tcx, pat.span, constructor, prefix, slice, suffix
1769                             ) {
1770                         Ok(true) => Some(vec![]),
1771                         Ok(false) => None,
1772                         Err(ErrorReported) => None
1773                     }
1774                 }
1775                 _ => span_bug!(pat.span,
1776                     "unexpected ctor {:?} for slice pat", constructor)
1777             }
1778         }
1779     };
1780     debug!("specialize({:#?}, {:#?}) = {:#?}", r[0], wild_patterns, head);
1781
1782     head.map(|mut head| {
1783         head.extend_from_slice(&r[1 ..]);
1784         head
1785     })
1786 }