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