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