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