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