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