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