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
4 /// (a) the patterns cover every possible constructor for the type [exhaustiveness]
5 /// (b) each pattern is necessary [usefulness]
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).
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).
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
28 /// For example, say we have the following:
30 /// // x: (Option<bool>, Result<()>)
32 /// (Some(true), _) => {}
33 /// (None, Err(())) => {}
34 /// (None, Err(_)) => {}
37 /// Here, the matrix `P` is 3 x 2 (rows x columns).
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.
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`.
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)))
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`.
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)))
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.
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.
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.
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)))`
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.
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
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
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
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
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 use self::Constructor::*;
159 use self::Usefulness::*;
160 use self::WitnessPreference::*;
162 use rustc_data_structures::fx::FxHashMap;
163 use rustc_index::vec::Idx;
165 use super::{compare_const_vals, PatternFoldable, PatternFolder};
166 use super::{FieldPat, Pat, PatKind, PatRange};
168 use rustc::hir::def_id::DefId;
169 use rustc::hir::{HirId, RangeEnd};
170 use rustc::ty::layout::{Integer, IntegerExt, Size, VariantIdx};
171 use rustc::ty::{self, Const, Ty, TyCtxt, TypeFoldable};
174 use rustc::mir::interpret::{truncate, AllocId, ConstValue, Pointer, Scalar};
175 use rustc::mir::Field;
176 use rustc::util::common::ErrorReported;
178 use syntax::attr::{SignedInt, UnsignedInt};
179 use syntax_pos::{Span, DUMMY_SP};
181 use arena::TypedArena;
183 use smallvec::{smallvec, SmallVec};
184 use std::cmp::{self, max, min, Ordering};
185 use std::convert::TryInto;
187 use std::iter::{FromIterator, IntoIterator};
188 use std::ops::RangeInclusive;
191 pub fn expand_pattern<'a, 'tcx>(cx: &MatchCheckCtxt<'a, 'tcx>, pat: Pat<'tcx>) -> Pat<'tcx> {
192 LiteralExpander { tcx: cx.tcx }.fold_pattern(&pat)
195 struct LiteralExpander<'tcx> {
199 impl LiteralExpander<'tcx> {
200 /// Derefs `val` and potentially unsizes the value if `crty` is an array and `rty` a slice.
202 /// `crty` and `rty` can differ because you can use array constants in the presence of slice
203 /// patterns. So the pattern may end up being a slice, but the constant is an array. We convert
204 /// the array to a slice in that case.
205 fn fold_const_value_deref(
207 val: ConstValue<'tcx>,
208 // the pattern's pointee type
210 // the constant's pointee type
212 ) -> ConstValue<'tcx> {
213 debug!("fold_const_value_deref {:?} {:?} {:?}", val, rty, crty);
214 match (val, &crty.kind, &rty.kind) {
215 // the easy case, deref a reference
216 (ConstValue::Scalar(Scalar::Ptr(p)), x, y) if x == y => {
217 let alloc = self.tcx.alloc_map.lock().unwrap_memory(p.alloc_id);
218 ConstValue::ByRef { alloc, offset: p.offset }
220 // unsize array to slice if pattern is array but match value or other patterns are slice
221 (ConstValue::Scalar(Scalar::Ptr(p)), ty::Array(t, n), ty::Slice(u)) => {
224 data: self.tcx.alloc_map.lock().unwrap_memory(p.alloc_id),
225 start: p.offset.bytes().try_into().unwrap(),
226 end: n.eval_usize(self.tcx, ty::ParamEnv::empty()).try_into().unwrap(),
229 // fat pointers stay the same
230 (ConstValue::Slice { .. }, _, _)
231 | (_, ty::Slice(_), ty::Slice(_))
232 | (_, ty::Str, ty::Str) => val,
233 // FIXME(oli-obk): this is reachable for `const FOO: &&&u32 = &&&42;` being used
234 _ => bug!("cannot deref {:#?}, {} -> {}", val, crty, rty),
239 impl PatternFolder<'tcx> for LiteralExpander<'tcx> {
240 fn fold_pattern(&mut self, pat: &Pat<'tcx>) -> Pat<'tcx> {
241 debug!("fold_pattern {:?} {:?} {:?}", pat, pat.ty.kind, pat.kind);
242 match (&pat.ty.kind, &*pat.kind) {
246 value: Const { val, ty: ty::TyS { kind: ty::Ref(_, crty, _), .. } },
251 kind: box PatKind::Deref {
255 kind: box PatKind::Constant {
256 value: self.tcx.mk_const(Const {
257 val: self.fold_const_value_deref(*val, rty, crty),
264 (_, &PatKind::Binding { subpattern: Some(ref s), .. }) => s.fold_with(self),
265 _ => pat.super_fold_with(self),
270 impl<'tcx> Pat<'tcx> {
271 fn is_wildcard(&self) -> bool {
273 PatKind::Binding { subpattern: None, .. } | PatKind::Wild => true,
279 /// A 2D matrix. Nx1 matrices are very common, which is why `SmallVec[_; 2]`
280 /// works well for each row.
281 pub struct Matrix<'p, 'tcx>(Vec<SmallVec<[&'p Pat<'tcx>; 2]>>);
283 impl<'p, 'tcx> Matrix<'p, 'tcx> {
284 pub fn empty() -> Self {
288 pub fn push(&mut self, row: SmallVec<[&'p Pat<'tcx>; 2]>) {
293 /// Pretty-printer for matrices of patterns, example:
294 /// +++++++++++++++++++++++++++++
296 /// +++++++++++++++++++++++++++++
297 /// + true + [First] +
298 /// +++++++++++++++++++++++++++++
299 /// + true + [Second(true)] +
300 /// +++++++++++++++++++++++++++++
302 /// +++++++++++++++++++++++++++++
303 /// + _ + [_, _, tail @ ..] +
304 /// +++++++++++++++++++++++++++++
305 impl<'p, 'tcx> fmt::Debug for Matrix<'p, 'tcx> {
306 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309 let &Matrix(ref m) = self;
310 let pretty_printed_matrix: Vec<Vec<String>> =
311 m.iter().map(|row| row.iter().map(|pat| format!("{:?}", pat)).collect()).collect();
313 let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0);
314 assert!(m.iter().all(|row| row.len() == column_count));
315 let column_widths: Vec<usize> = (0..column_count)
316 .map(|col| pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0))
319 let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1;
320 let br = "+".repeat(total_width);
321 write!(f, "{}\n", br)?;
322 for row in pretty_printed_matrix {
324 for (column, pat_str) in row.into_iter().enumerate() {
326 write!(f, "{:1$}", pat_str, column_widths[column])?;
330 write!(f, "{}\n", br)?;
336 impl<'p, 'tcx> FromIterator<SmallVec<[&'p Pat<'tcx>; 2]>> for Matrix<'p, 'tcx> {
337 fn from_iter<T>(iter: T) -> Self
339 T: IntoIterator<Item = SmallVec<[&'p Pat<'tcx>; 2]>>,
341 Matrix(iter.into_iter().collect())
345 pub struct MatchCheckCtxt<'a, 'tcx> {
346 pub tcx: TyCtxt<'tcx>,
347 /// The module in which the match occurs. This is necessary for
348 /// checking inhabited-ness of types because whether a type is (visibly)
349 /// inhabited can depend on whether it was defined in the current module or
350 /// not. E.g., `struct Foo { _private: ! }` cannot be seen to be empty
351 /// outside it's module and should not be matchable with an empty match
354 param_env: ty::ParamEnv<'tcx>,
355 pub pattern_arena: &'a TypedArena<Pat<'tcx>>,
356 pub byte_array_map: FxHashMap<*const Pat<'tcx>, Vec<&'a Pat<'tcx>>>,
359 impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> {
360 pub fn create_and_enter<F, R>(
362 param_env: ty::ParamEnv<'tcx>,
367 F: for<'b> FnOnce(MatchCheckCtxt<'b, 'tcx>) -> R,
369 let pattern_arena = TypedArena::default();
375 pattern_arena: &pattern_arena,
376 byte_array_map: FxHashMap::default(),
380 fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool {
381 if self.tcx.features().exhaustive_patterns {
382 self.tcx.is_ty_uninhabited_from(self.module, ty)
388 fn is_non_exhaustive_enum(&self, ty: Ty<'tcx>) -> bool {
390 ty::Adt(adt_def, ..) => adt_def.is_variant_list_non_exhaustive(),
395 fn is_local(&self, ty: Ty<'tcx>) -> bool {
397 ty::Adt(adt_def, ..) => adt_def.did.is_local(),
403 #[derive(Clone, Debug)]
404 enum Constructor<'tcx> {
405 /// The constructor of all patterns that don't vary by constructor,
406 /// e.g., struct patterns and fixed-length arrays.
411 ConstantValue(&'tcx ty::Const<'tcx>, Span),
412 /// Ranges of literal values (`2..=5` and `2..5`).
413 ConstantRange(u128, u128, Ty<'tcx>, RangeEnd, Span),
414 /// Array patterns of length n.
418 // Ignore spans when comparing, they don't carry semantic information as they are only for lints.
419 impl<'tcx> std::cmp::PartialEq for Constructor<'tcx> {
420 fn eq(&self, other: &Self) -> bool {
421 match (self, other) {
422 (Constructor::Single, Constructor::Single) => true,
423 (Constructor::Variant(a), Constructor::Variant(b)) => a == b,
424 (Constructor::ConstantValue(a, _), Constructor::ConstantValue(b, _)) => a == b,
426 Constructor::ConstantRange(a_start, a_end, a_ty, a_range_end, _),
427 Constructor::ConstantRange(b_start, b_end, b_ty, b_range_end, _),
428 ) => a_start == b_start && a_end == b_end && a_ty == b_ty && a_range_end == b_range_end,
429 (Constructor::Slice(a), Constructor::Slice(b)) => a == b,
435 impl<'tcx> Constructor<'tcx> {
436 fn is_slice(&self) -> bool {
438 Slice { .. } => true,
443 fn variant_index_for_adt<'a>(
445 cx: &MatchCheckCtxt<'a, 'tcx>,
446 adt: &'tcx ty::AdtDef,
449 Variant(id) => adt.variant_index_with_id(*id),
451 assert!(!adt.is_enum());
454 ConstantValue(c, _) => crate::const_eval::const_variant_index(cx.tcx, cx.param_env, c),
455 _ => bug!("bad constructor {:?} for adt {:?}", self, adt),
459 fn display(&self, tcx: TyCtxt<'tcx>) -> String {
461 Constructor::ConstantValue(val, _) => format!("{}", val),
462 Constructor::ConstantRange(lo, hi, ty, range_end, _) => {
463 // Get the right sign on the output:
464 let ty = ty::ParamEnv::empty().and(*ty);
467 ty::Const::from_bits(tcx, *lo, ty),
469 ty::Const::from_bits(tcx, *hi, ty),
472 Constructor::Slice(val) => format!("[{}]", val),
473 _ => bug!("bad constructor being displayed: `{:?}", self),
478 #[derive(Clone, Debug)]
479 pub enum Usefulness<'tcx> {
481 UsefulWithWitness(Vec<Witness<'tcx>>),
485 impl<'tcx> Usefulness<'tcx> {
486 fn is_useful(&self) -> bool {
494 #[derive(Copy, Clone, Debug)]
495 pub enum WitnessPreference {
500 #[derive(Copy, Clone, Debug)]
501 struct PatCtxt<'tcx> {
503 max_slice_length: u64,
507 /// A witness of non-exhaustiveness for error reporting, represented
508 /// as a list of patterns (in reverse order of construction) with
509 /// wildcards inside to represent elements that can take any inhabitant
510 /// of the type as a value.
512 /// A witness against a list of patterns should have the same types
513 /// and length as the pattern matched against. Because Rust `match`
514 /// is always against a single pattern, at the end the witness will
515 /// have length 1, but in the middle of the algorithm, it can contain
516 /// multiple patterns.
518 /// For example, if we are constructing a witness for the match against
520 /// struct Pair(Option<(u32, u32)>, bool);
522 /// match (p: Pair) {
523 /// Pair(None, _) => {}
524 /// Pair(_, false) => {}
528 /// We'll perform the following steps:
529 /// 1. Start with an empty witness
530 /// `Witness(vec![])`
531 /// 2. Push a witness `Some(_)` against the `None`
532 /// `Witness(vec![Some(_)])`
533 /// 3. Push a witness `true` against the `false`
534 /// `Witness(vec![Some(_), true])`
535 /// 4. Apply the `Pair` constructor to the witnesses
536 /// `Witness(vec![Pair(Some(_), true)])`
538 /// The final `Pair(Some(_), true)` is then the resulting witness.
539 #[derive(Clone, Debug)]
540 pub struct Witness<'tcx>(Vec<Pat<'tcx>>);
542 impl<'tcx> Witness<'tcx> {
543 pub fn single_pattern(self) -> Pat<'tcx> {
544 assert_eq!(self.0.len(), 1);
545 self.0.into_iter().next().unwrap()
548 fn push_wild_constructor<'a>(
550 cx: &MatchCheckCtxt<'a, 'tcx>,
551 ctor: &Constructor<'tcx>,
554 let sub_pattern_tys = constructor_sub_pattern_tys(cx, ctor, ty);
555 self.0.extend(sub_pattern_tys.into_iter().map(|ty| Pat {
558 kind: box PatKind::Wild,
560 self.apply_constructor(cx, ctor, ty)
563 /// Constructs a partial witness for a pattern given a list of
564 /// patterns expanded by the specialization step.
566 /// When a pattern P is discovered to be useful, this function is used bottom-up
567 /// to reconstruct a complete witness, e.g., a pattern P' that covers a subset
568 /// of values, V, where each value in that set is not covered by any previously
569 /// used patterns and is covered by the pattern P'. Examples:
571 /// left_ty: tuple of 3 elements
572 /// pats: [10, 20, _] => (10, 20, _)
574 /// left_ty: struct X { a: (bool, &'static str), b: usize}
575 /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 }
576 fn apply_constructor<'a>(
578 cx: &MatchCheckCtxt<'a, 'tcx>,
579 ctor: &Constructor<'tcx>,
582 let arity = constructor_arity(cx, ctor, ty);
584 let len = self.0.len() as u64;
585 let mut pats = self.0.drain((len - arity) as usize..).rev();
588 ty::Adt(..) | ty::Tuple(..) => {
591 .map(|(i, p)| FieldPat { field: Field::new(i), pattern: p })
594 if let ty::Adt(adt, substs) = ty.kind {
599 variant_index: ctor.variant_index_for_adt(cx, adt),
603 PatKind::Leaf { subpatterns: pats }
606 PatKind::Leaf { subpatterns: pats }
610 ty::Ref(..) => PatKind::Deref { subpattern: pats.nth(0).unwrap() },
612 ty::Slice(_) | ty::Array(..) => {
613 PatKind::Slice { prefix: pats.collect(), slice: None, suffix: vec![] }
617 ConstantValue(value, _) => PatKind::Constant { value },
618 ConstantRange(lo, hi, ty, end, _) => PatKind::Range(PatRange {
619 lo: ty::Const::from_bits(cx.tcx, lo, ty::ParamEnv::empty().and(ty)),
620 hi: ty::Const::from_bits(cx.tcx, hi, ty::ParamEnv::empty().and(ty)),
628 self.0.push(Pat { ty, span: DUMMY_SP, kind: Box::new(pat) });
634 /// This determines the set of all possible constructors of a pattern matching
635 /// values of type `left_ty`. For vectors, this would normally be an infinite set
636 /// but is instead bounded by the maximum fixed length of slice patterns in
637 /// the column of patterns being analyzed.
639 /// We make sure to omit constructors that are statically impossible. E.g., for
640 /// `Option<!>`, we do not include `Some(_)` in the returned list of constructors.
641 fn all_constructors<'a, 'tcx>(
642 cx: &mut MatchCheckCtxt<'a, 'tcx>,
644 ) -> Vec<Constructor<'tcx>> {
645 debug!("all_constructors({:?})", pcx.ty);
646 let ctors = match pcx.ty.kind {
647 ty::Bool => [true, false]
649 .map(|&b| ConstantValue(ty::Const::from_bool(cx.tcx, b), pcx.span))
651 ty::Array(ref sub_ty, len) if len.try_eval_usize(cx.tcx, cx.param_env).is_some() => {
652 let len = len.eval_usize(cx.tcx, cx.param_env);
653 if len != 0 && cx.is_uninhabited(sub_ty) { vec![] } else { vec![Slice(len)] }
655 // Treat arrays of a constant but unknown length like slices.
656 ty::Array(ref sub_ty, _) | ty::Slice(ref sub_ty) => {
657 if cx.is_uninhabited(sub_ty) {
660 (0..pcx.max_slice_length + 1).map(|length| Slice(length)).collect()
663 ty::Adt(def, substs) if def.is_enum() => def
667 !cx.tcx.features().exhaustive_patterns
669 .uninhabited_from(cx.tcx, substs, def.adt_kind())
670 .contains(cx.tcx, cx.module)
672 .map(|v| Variant(v.def_id))
676 // The valid Unicode Scalar Value ranges.
686 '\u{10FFFF}' as u128,
694 let bits = Integer::from_attr(&cx.tcx, SignedInt(ity)).size().bits() as u128;
695 let min = 1u128 << (bits - 1);
697 vec![ConstantRange(min, max, pcx.ty, RangeEnd::Included, pcx.span)]
700 let size = Integer::from_attr(&cx.tcx, UnsignedInt(uty)).size();
701 let max = truncate(u128::max_value(), size);
702 vec![ConstantRange(0, max, pcx.ty, RangeEnd::Included, pcx.span)]
705 if cx.is_uninhabited(pcx.ty) {
715 fn max_slice_length<'p, 'a, 'tcx, I>(cx: &mut MatchCheckCtxt<'a, 'tcx>, patterns: I) -> u64
717 I: Iterator<Item = &'p Pat<'tcx>>,
720 // The exhaustiveness-checking paper does not include any details on
721 // checking variable-length slice patterns. However, they are matched
722 // by an infinite collection of fixed-length array patterns.
724 // Checking the infinite set directly would take an infinite amount
725 // of time. However, it turns out that for each finite set of
726 // patterns `P`, all sufficiently large array lengths are equivalent:
728 // Each slice `s` with a "sufficiently-large" length `l ≥ L` that applies
729 // to exactly the subset `Pₜ` of `P` can be transformed to a slice
730 // `sₘ` for each sufficiently-large length `m` that applies to exactly
731 // the same subset of `P`.
733 // Because of that, each witness for reachability-checking from one
734 // of the sufficiently-large lengths can be transformed to an
735 // equally-valid witness from any other length, so we only have
736 // to check slice lengths from the "minimal sufficiently-large length"
739 // Note that the fact that there is a *single* `sₘ` for each `m`
740 // not depending on the specific pattern in `P` is important: if
741 // you look at the pair of patterns
744 // Then any slice of length ≥1 that matches one of these two
745 // patterns can be trivially turned to a slice of any
746 // other length ≥1 that matches them and vice-versa - for
747 // but the slice from length 2 `[false, true]` that matches neither
748 // of these patterns can't be turned to a slice from length 1 that
749 // matches neither of these patterns, so we have to consider
750 // slices from length 2 there.
752 // Now, to see that that length exists and find it, observe that slice
753 // patterns are either "fixed-length" patterns (`[_, _, _]`) or
754 // "variable-length" patterns (`[_, .., _]`).
756 // For fixed-length patterns, all slices with lengths *longer* than
757 // the pattern's length have the same outcome (of not matching), so
758 // as long as `L` is greater than the pattern's length we can pick
759 // any `sₘ` from that length and get the same result.
761 // For variable-length patterns, the situation is more complicated,
762 // because as seen above the precise value of `sₘ` matters.
764 // However, for each variable-length pattern `p` with a prefix of length
765 // `plₚ` and suffix of length `slₚ`, only the first `plₚ` and the last
766 // `slₚ` elements are examined.
768 // Therefore, as long as `L` is positive (to avoid concerns about empty
769 // types), all elements after the maximum prefix length and before
770 // the maximum suffix length are not examined by any variable-length
771 // pattern, and therefore can be added/removed without affecting
772 // them - creating equivalent patterns from any sufficiently-large
775 // Of course, if fixed-length patterns exist, we must be sure
776 // that our length is large enough to miss them all, so
777 // we can pick `L = max(FIXED_LEN+1 ∪ {max(PREFIX_LEN) + max(SUFFIX_LEN)})`
779 // for example, with the above pair of patterns, all elements
780 // but the first and last can be added/removed, so any
781 // witness of length ≥2 (say, `[false, false, true]`) can be
782 // turned to a witness from any other length ≥2.
784 let mut max_prefix_len = 0;
785 let mut max_suffix_len = 0;
786 let mut max_fixed_len = 0;
788 for row in patterns {
790 PatKind::Constant { value } => {
791 // extract the length of an array/slice from a constant
792 match (value.val, &value.ty.kind) {
793 (_, ty::Array(_, n)) => {
794 max_fixed_len = cmp::max(max_fixed_len, n.eval_usize(cx.tcx, cx.param_env))
796 (ConstValue::Slice { start, end, .. }, ty::Slice(_)) => {
797 max_fixed_len = cmp::max(max_fixed_len, (end - start) as u64)
802 PatKind::Slice { ref prefix, slice: None, ref suffix } => {
803 let fixed_len = prefix.len() as u64 + suffix.len() as u64;
804 max_fixed_len = cmp::max(max_fixed_len, fixed_len);
806 PatKind::Slice { ref prefix, slice: Some(_), ref suffix } => {
807 max_prefix_len = cmp::max(max_prefix_len, prefix.len() as u64);
808 max_suffix_len = cmp::max(max_suffix_len, suffix.len() as u64);
814 cmp::max(max_fixed_len + 1, max_prefix_len + max_suffix_len)
817 /// An inclusive interval, used for precise integer exhaustiveness checking.
818 /// `IntRange`s always store a contiguous range. This means that values are
819 /// encoded such that `0` encodes the minimum value for the integer,
820 /// regardless of the signedness.
821 /// For example, the pattern `-128..=127i8` is encoded as `0..=255`.
822 /// This makes comparisons and arithmetic on interval endpoints much more
823 /// straightforward. See `signed_bias` for details.
825 /// `IntRange` is never used to encode an empty range or a "range" that wraps
826 /// around the (offset) space: i.e., `range.lo <= range.hi`.
827 #[derive(Clone, Debug)]
828 struct IntRange<'tcx> {
829 pub range: RangeInclusive<u128>,
834 impl<'tcx> IntRange<'tcx> {
836 fn is_integral(ty: Ty<'_>) -> bool {
838 ty::Char | ty::Int(_) | ty::Uint(_) => true,
844 fn integral_size_and_signed_bias(tcx: TyCtxt<'tcx>, ty: Ty<'_>) -> Option<(Size, u128)> {
846 ty::Char => Some((Size::from_bytes(4), 0)),
848 let size = Integer::from_attr(&tcx, SignedInt(ity)).size();
849 Some((size, 1u128 << (size.bits() as u128 - 1)))
851 ty::Uint(uty) => Some((Integer::from_attr(&tcx, UnsignedInt(uty)).size(), 0)),
859 param_env: ty::ParamEnv<'tcx>,
862 ) -> Option<IntRange<'tcx>> {
863 if let Some((target_size, bias)) = Self::integral_size_and_signed_bias(tcx, value.ty) {
865 let val = if let ConstValue::Scalar(Scalar::Raw { data, size }) = value.val {
866 // For this specific pattern we can skip a lot of effort and go
867 // straight to the result, after doing a bit of checking. (We
868 // could remove this branch and just use the next branch, which
869 // is more general but much slower.)
870 Scalar::<()>::check_raw(data, size, target_size);
872 } else if let Some(val) = value.try_eval_bits(tcx, param_env, ty) {
873 // This is a more general form of the previous branch.
878 let val = val ^ bias;
879 Some(IntRange { range: val..=val, ty, span })
893 ) -> Option<IntRange<'tcx>> {
894 if Self::is_integral(ty) {
895 // Perform a shift if the underlying types are signed,
896 // which makes the interval arithmetic simpler.
897 let bias = IntRange::signed_bias(tcx, ty);
898 let (lo, hi) = (lo ^ bias, hi ^ bias);
899 // Make sure the interval is well-formed.
900 if lo > hi || lo == hi && *end == RangeEnd::Excluded {
903 let offset = (*end == RangeEnd::Excluded) as u128;
904 Some(IntRange { range: lo..=(hi - offset), ty, span })
913 param_env: ty::ParamEnv<'tcx>,
914 ctor: &Constructor<'tcx>,
915 ) -> Option<IntRange<'tcx>> {
916 // Floating-point ranges are permitted and we don't want
917 // to consider them when constructing integer ranges.
919 ConstantRange(lo, hi, ty, end, span) => Self::from_range(tcx, *lo, *hi, ty, end, *span),
920 ConstantValue(val, span) => Self::from_const(tcx, param_env, val, *span),
927 param_env: ty::ParamEnv<'tcx>,
929 ) -> Option<IntRange<'tcx>> {
932 box PatKind::Constant { value } => {
933 return Self::from_const(tcx, param_env, value, pat.span);
935 box PatKind::Range(PatRange { lo, hi, end }) => {
936 return Self::from_range(
938 lo.eval_bits(tcx, param_env, lo.ty),
939 hi.eval_bits(tcx, param_env, hi.ty),
945 box PatKind::AscribeUserType { ref subpattern, .. } => {
953 // The return value of `signed_bias` should be XORed with an endpoint to encode/decode it.
954 fn signed_bias(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> u128 {
957 let bits = Integer::from_attr(&tcx, SignedInt(ity)).size().bits() as u128;
964 /// Converts a `RangeInclusive` to a `ConstantValue` or inclusive `ConstantRange`.
968 r: RangeInclusive<u128>,
970 ) -> Constructor<'tcx> {
971 let bias = IntRange::signed_bias(tcx, ty);
972 let (lo, hi) = r.into_inner();
974 let ty = ty::ParamEnv::empty().and(ty);
975 ConstantValue(ty::Const::from_bits(tcx, lo ^ bias, ty), span)
977 ConstantRange(lo ^ bias, hi ^ bias, ty, RangeEnd::Included, span)
981 /// Returns a collection of ranges that spans the values covered by `ranges`, subtracted
982 /// by the values covered by `self`: i.e., `ranges \ self` (in set notation).
986 param_env: ty::ParamEnv<'tcx>,
987 ranges: Vec<Constructor<'tcx>>,
988 ) -> Vec<Constructor<'tcx>> {
991 .filter_map(|r| IntRange::from_ctor(tcx, param_env, &r).map(|i| i.range));
992 let mut remaining_ranges = vec![];
994 let (lo, hi) = self.range.into_inner();
995 for subrange in ranges {
996 let (subrange_lo, subrange_hi) = subrange.into_inner();
997 if lo > subrange_hi || subrange_lo > hi {
998 // The pattern doesn't intersect with the subrange at all,
999 // so the subrange remains untouched.
1000 remaining_ranges.push(Self::range_to_ctor(
1003 subrange_lo..=subrange_hi,
1007 if lo > subrange_lo {
1008 // The pattern intersects an upper section of the
1009 // subrange, so a lower section will remain.
1010 remaining_ranges.push(Self::range_to_ctor(
1013 subrange_lo..=(lo - 1),
1017 if hi < subrange_hi {
1018 // The pattern intersects a lower section of the
1019 // subrange, so an upper section will remain.
1020 remaining_ranges.push(Self::range_to_ctor(
1023 (hi + 1)..=subrange_hi,
1032 fn intersection(&self, other: &Self) -> Option<Self> {
1034 let (lo, hi) = (*self.range.start(), *self.range.end());
1035 let (other_lo, other_hi) = (*other.range.start(), *other.range.end());
1036 if lo <= other_hi && other_lo <= hi {
1037 let span = other.span;
1038 Some(IntRange { range: max(lo, other_lo)..=min(hi, other_hi), ty, span })
1044 fn suspicious_intersection(&self, other: &Self) -> bool {
1045 // `false` in the following cases:
1046 // 1 ---- // 1 ---------- // 1 ---- // 1 ----
1047 // 2 ---------- // 2 ---- // 2 ---- // 2 ----
1049 // The following are currently `false`, but could be `true` in the future (#64007):
1050 // 1 --------- // 1 ---------
1051 // 2 ---------- // 2 ----------
1053 // `true` in the following cases:
1054 // 1 ------- // 1 -------
1055 // 2 -------- // 2 -------
1056 let (lo, hi) = (*self.range.start(), *self.range.end());
1057 let (other_lo, other_hi) = (*other.range.start(), *other.range.end());
1058 (lo == other_hi || hi == other_lo)
1062 // A request for missing constructor data in terms of either:
1063 // - whether or not there any missing constructors; or
1064 // - the actual set of missing constructors.
1065 #[derive(PartialEq)]
1066 enum MissingCtorsInfo {
1071 // Used by `compute_missing_ctors`.
1072 #[derive(Debug, PartialEq)]
1073 enum MissingCtors<'tcx> {
1077 // Note that the Vec can be empty.
1078 Ctors(Vec<Constructor<'tcx>>),
1081 // When `info` is `MissingCtorsInfo::Ctors`, compute a set of constructors
1082 // equivalent to `all_ctors \ used_ctors`. When `info` is
1083 // `MissingCtorsInfo::Emptiness`, just determines if that set is empty or not.
1084 // (The split logic gives a performance win, because we always need to know if
1085 // the set is empty, but we rarely need the full set, and it can be expensive
1086 // to compute the full set.)
1087 fn compute_missing_ctors<'tcx>(
1088 info: MissingCtorsInfo,
1090 param_env: ty::ParamEnv<'tcx>,
1091 all_ctors: &Vec<Constructor<'tcx>>,
1092 used_ctors: &Vec<Constructor<'tcx>>,
1093 ) -> MissingCtors<'tcx> {
1094 let mut missing_ctors = vec![];
1096 for req_ctor in all_ctors {
1097 let mut refined_ctors = vec![req_ctor.clone()];
1098 for used_ctor in used_ctors {
1099 if used_ctor == req_ctor {
1100 // If a constructor appears in a `match` arm, we can
1101 // eliminate it straight away.
1102 refined_ctors = vec![]
1103 } else if let Some(interval) = IntRange::from_ctor(tcx, param_env, used_ctor) {
1104 // Refine the required constructors for the type by subtracting
1105 // the range defined by the current constructor pattern.
1106 refined_ctors = interval.subtract_from(tcx, param_env, refined_ctors);
1109 // If the constructor patterns that have been considered so far
1110 // already cover the entire range of values, then we the
1111 // constructor is not missing, and we can move on to the next one.
1112 if refined_ctors.is_empty() {
1116 // If a constructor has not been matched, then it is missing.
1117 // We add `refined_ctors` instead of `req_ctor`, because then we can
1118 // provide more detailed error information about precisely which
1119 // ranges have been omitted.
1120 if info == MissingCtorsInfo::Emptiness {
1121 if !refined_ctors.is_empty() {
1122 // The set is non-empty; return early.
1123 return MissingCtors::NonEmpty;
1126 missing_ctors.extend(refined_ctors);
1130 if info == MissingCtorsInfo::Emptiness {
1131 // If we reached here, the set is empty.
1134 MissingCtors::Ctors(missing_ctors)
1138 /// Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html.
1139 /// The algorithm from the paper has been modified to correctly handle empty
1140 /// types. The changes are:
1141 /// (0) We don't exit early if the pattern matrix has zero rows. We just
1142 /// continue to recurse over columns.
1143 /// (1) all_constructors will only return constructors that are statically
1144 /// possible. E.g., it will only return `Ok` for `Result<T, !>`.
1146 /// This finds whether a (row) vector `v` of patterns is 'useful' in relation
1147 /// to a set of such vectors `m` - this is defined as there being a set of
1148 /// inputs that will match `v` but not any of the sets in `m`.
1150 /// All the patterns at each column of the `matrix ++ v` matrix must
1151 /// have the same type, except that wildcard (PatKind::Wild) patterns
1152 /// with type `TyErr` are also allowed, even if the "type of the column"
1153 /// is not `TyErr`. That is used to represent private fields, as using their
1154 /// real type would assert that they are inhabited.
1156 /// This is used both for reachability checking (if a pattern isn't useful in
1157 /// relation to preceding patterns, it is not reachable) and exhaustiveness
1158 /// checking (if a wildcard pattern is useful in relation to a matrix, the
1159 /// matrix isn't exhaustive).
1160 pub fn is_useful<'p, 'a, 'tcx>(
1161 cx: &mut MatchCheckCtxt<'a, 'tcx>,
1162 matrix: &Matrix<'p, 'tcx>,
1164 witness: WitnessPreference,
1166 ) -> Usefulness<'tcx> {
1167 let &Matrix(ref rows) = matrix;
1168 debug!("is_useful({:#?}, {:#?})", matrix, v);
1170 // The base case. We are pattern-matching on () and the return value is
1171 // based on whether our matrix has a row or not.
1172 // NOTE: This could potentially be optimized by checking rows.is_empty()
1173 // first and then, if v is non-empty, the return value is based on whether
1174 // the type of the tuple we're checking is inhabited or not.
1176 return if rows.is_empty() {
1178 ConstructWitness => UsefulWithWitness(vec![Witness(vec![])]),
1179 LeaveOutWitness => Useful,
1186 assert!(rows.iter().all(|r| r.len() == v.len()));
1188 let (ty, span) = rows
1190 .map(|r| (r[0].ty, r[0].span))
1191 .find(|(ty, _)| !ty.references_error())
1192 .unwrap_or((v[0].ty, v[0].span));
1194 // TyErr is used to represent the type of wildcard patterns matching
1195 // against inaccessible (private) fields of structs, so that we won't
1196 // be able to observe whether the types of the struct's fields are
1199 // If the field is truly inaccessible, then all the patterns
1200 // matching against it must be wildcard patterns, so its type
1203 // However, if we are matching against non-wildcard patterns, we
1204 // need to know the real type of the field so we can specialize
1205 // against it. This primarily occurs through constants - they
1206 // can include contents for fields that are inaccessible at the
1207 // location of the match. In that case, the field's type is
1208 // inhabited - by the constant - so we can just use it.
1210 // FIXME: this might lead to "unstable" behavior with macro hygiene
1211 // introducing uninhabited patterns for inaccessible fields. We
1212 // need to figure out how to model that.
1214 max_slice_length: max_slice_length(cx, rows.iter().map(|r| r[0]).chain(Some(v[0]))),
1218 debug!("is_useful_expand_first_col: pcx={:#?}, expanding {:#?}", pcx, v[0]);
1220 if let Some(constructors) = pat_constructors(cx, v[0], pcx) {
1221 debug!("is_useful - expanding constructors: {:#?}", constructors);
1222 split_grouped_constructors(
1232 .map(|c| is_useful_specialized(cx, matrix, v, c, pcx.ty, witness, hir_id))
1233 .find(|result| result.is_useful())
1234 .unwrap_or(NotUseful)
1236 debug!("is_useful - expanding wildcard");
1238 let used_ctors: Vec<Constructor<'_>> = rows
1240 .flat_map(|row| pat_constructors(cx, row[0], pcx).unwrap_or(vec![]))
1242 debug!("used_ctors = {:#?}", used_ctors);
1243 // `all_ctors` are all the constructors for the given type, which
1244 // should all be represented (or caught with the wild pattern `_`).
1245 let all_ctors = all_constructors(cx, pcx);
1246 debug!("all_ctors = {:#?}", all_ctors);
1248 // `missing_ctors` is the set of constructors from the same type as the
1249 // first column of `matrix` that are matched only by wildcard patterns
1250 // from the first column.
1252 // Therefore, if there is some pattern that is unmatched by `matrix`,
1253 // it will still be unmatched if the first constructor is replaced by
1254 // any of the constructors in `missing_ctors`
1256 // However, if our scrutinee is *privately* an empty enum, we
1257 // must treat it as though it had an "unknown" constructor (in
1258 // that case, all other patterns obviously can't be variants)
1259 // to avoid exposing its emptyness. See the `match_privately_empty`
1260 // test for details.
1262 // FIXME: currently the only way I know of something can
1263 // be a privately-empty enum is when the exhaustive_patterns
1264 // feature flag is not present, so this is only
1265 // needed for that case.
1267 // Missing constructors are those that are not matched by any
1268 // non-wildcard patterns in the current column. We always determine if
1269 // the set is empty, but we only fully construct them on-demand,
1270 // because they're rarely used and can be big.
1271 let cheap_missing_ctors = compute_missing_ctors(
1272 MissingCtorsInfo::Emptiness,
1279 let is_privately_empty = all_ctors.is_empty() && !cx.is_uninhabited(pcx.ty);
1280 let is_declared_nonexhaustive = cx.is_non_exhaustive_enum(pcx.ty) && !cx.is_local(pcx.ty);
1282 "cheap_missing_ctors={:#?} is_privately_empty={:#?} is_declared_nonexhaustive={:#?}",
1283 cheap_missing_ctors, is_privately_empty, is_declared_nonexhaustive
1286 // For privately empty and non-exhaustive enums, we work as if there were an "extra"
1287 // `_` constructor for the type, so we can never match over all constructors.
1288 let is_non_exhaustive = is_privately_empty
1289 || is_declared_nonexhaustive
1290 || (pcx.ty.is_ptr_sized_integral() && !cx.tcx.features().precise_pointer_size_matching);
1292 if cheap_missing_ctors == MissingCtors::Empty && !is_non_exhaustive {
1293 split_grouped_constructors(
1303 .map(|c| is_useful_specialized(cx, matrix, v, c, pcx.ty, witness, hir_id))
1304 .find(|result| result.is_useful())
1305 .unwrap_or(NotUseful)
1310 if r[0].is_wildcard() { Some(SmallVec::from_slice(&r[1..])) } else { None }
1313 match is_useful(cx, &matrix, &v[1..], witness, hir_id) {
1314 UsefulWithWitness(pats) => {
1316 // In this case, there's at least one "free"
1317 // constructor that is only matched against by
1318 // wildcard patterns.
1320 // There are 2 ways we can report a witness here.
1321 // Commonly, we can report all the "free"
1322 // constructors as witnesses, e.g., if we have:
1325 // enum Direction { N, S, E, W }
1326 // let Direction::N = ...;
1329 // we can report 3 witnesses: `S`, `E`, and `W`.
1331 // However, there are 2 cases where we don't want
1332 // to do this and instead report a single `_` witness:
1334 // 1) If the user is matching against a non-exhaustive
1335 // enum, there is no point in enumerating all possible
1336 // variants, because the user can't actually match
1337 // against them himself, e.g., in an example like:
1339 // let err: io::ErrorKind = ...;
1341 // io::ErrorKind::NotFound => {},
1344 // we don't want to show every possible IO error,
1345 // but instead have `_` as the witness (this is
1346 // actually *required* if the user specified *all*
1347 // IO errors, but is probably what we want in every
1350 // 2) If the user didn't actually specify a constructor
1351 // in this arm, e.g., in
1353 // let x: (Direction, Direction, bool) = ...;
1354 // let (_, _, false) = x;
1356 // we don't want to show all 16 possible witnesses
1357 // `(<direction-1>, <direction-2>, true)` - we are
1358 // satisfied with `(_, _, true)`. In this case,
1359 // `used_ctors` is empty.
1360 let new_witnesses = if is_non_exhaustive || used_ctors.is_empty() {
1361 // All constructors are unused. Add wild patterns
1362 // rather than each individual constructor.
1364 .map(|mut witness| {
1365 witness.0.push(Pat {
1368 kind: box PatKind::Wild,
1374 let expensive_missing_ctors = compute_missing_ctors(
1375 MissingCtorsInfo::Ctors,
1381 if let MissingCtors::Ctors(missing_ctors) = expensive_missing_ctors {
1383 .flat_map(|witness| {
1384 missing_ctors.iter().map(move |ctor| {
1385 // Extends the witness with a "wild" version of this
1386 // constructor, that matches everything that can be built with
1387 // it. For example, if `ctor` is a `Constructor::Variant` for
1388 // `Option::Some`, this pushes the witness for `Some(_)`.
1389 witness.clone().push_wild_constructor(cx, ctor, pcx.ty)
1394 bug!("cheap missing ctors")
1397 UsefulWithWitness(new_witnesses)
1405 /// A shorthand for the `U(S(c, P), S(c, q))` operation from the paper. I.e., `is_useful` applied
1406 /// to the specialised version of both the pattern matrix `P` and the new pattern `q`.
1407 fn is_useful_specialized<'p, 'a, 'tcx>(
1408 cx: &mut MatchCheckCtxt<'a, 'tcx>,
1409 &Matrix(ref m): &Matrix<'p, 'tcx>,
1411 ctor: Constructor<'tcx>,
1413 witness: WitnessPreference,
1415 ) -> Usefulness<'tcx> {
1416 debug!("is_useful_specialized({:#?}, {:#?}, {:?})", v, ctor, lty);
1417 let sub_pat_tys = constructor_sub_pattern_tys(cx, &ctor, lty);
1418 let wild_patterns_owned: Vec<_> =
1419 sub_pat_tys.iter().map(|ty| Pat { ty, span: DUMMY_SP, kind: box PatKind::Wild }).collect();
1420 let wild_patterns: Vec<_> = wild_patterns_owned.iter().collect();
1422 Matrix(m.iter().filter_map(|r| specialize(cx, &r, &ctor, &wild_patterns)).collect());
1423 match specialize(cx, v, &ctor, &wild_patterns) {
1424 Some(v) => match is_useful(cx, &matrix, &v, witness, hir_id) {
1425 UsefulWithWitness(witnesses) => UsefulWithWitness(
1428 .map(|witness| witness.apply_constructor(cx, &ctor, lty))
1437 /// Determines the constructors that the given pattern can be specialized to.
1439 /// In most cases, there's only one constructor that a specific pattern
1440 /// represents, such as a specific enum variant or a specific literal value.
1441 /// Slice patterns, however, can match slices of different lengths. For instance,
1442 /// `[a, b, tail @ ..]` can match a slice of length 2, 3, 4 and so on.
1444 /// Returns `None` in case of a catch-all, which can't be specialized.
1445 fn pat_constructors<'tcx>(
1446 cx: &mut MatchCheckCtxt<'_, 'tcx>,
1449 ) -> Option<Vec<Constructor<'tcx>>> {
1451 PatKind::AscribeUserType { ref subpattern, .. } => pat_constructors(cx, subpattern, pcx),
1452 PatKind::Binding { .. } | PatKind::Wild => None,
1453 PatKind::Leaf { .. } | PatKind::Deref { .. } => Some(vec![Single]),
1454 PatKind::Variant { adt_def, variant_index, .. } => {
1455 Some(vec![Variant(adt_def.variants[variant_index].def_id)])
1457 PatKind::Constant { value } => Some(vec![ConstantValue(value, pat.span)]),
1458 PatKind::Range(PatRange { lo, hi, end }) => Some(vec![ConstantRange(
1459 lo.eval_bits(cx.tcx, cx.param_env, lo.ty),
1460 hi.eval_bits(cx.tcx, cx.param_env, hi.ty),
1465 PatKind::Array { .. } => match pcx.ty.kind {
1466 ty::Array(_, length) => Some(vec![Slice(length.eval_usize(cx.tcx, cx.param_env))]),
1467 _ => span_bug!(pat.span, "bad ty {:?} for array pattern", pcx.ty),
1469 PatKind::Slice { ref prefix, ref slice, ref suffix } => {
1470 let pat_len = prefix.len() as u64 + suffix.len() as u64;
1471 if slice.is_some() {
1472 Some((pat_len..pcx.max_slice_length + 1).map(Slice).collect())
1474 Some(vec![Slice(pat_len)])
1477 PatKind::Or { .. } => {
1478 bug!("support for or-patterns has not been fully implemented yet.");
1483 /// This computes the arity of a constructor. The arity of a constructor
1484 /// is how many subpattern patterns of that constructor should be expanded to.
1486 /// For instance, a tuple pattern `(_, 42, Some([]))` has the arity of 3.
1487 /// A struct pattern's arity is the number of fields it contains, etc.
1488 fn constructor_arity(cx: &MatchCheckCtxt<'a, 'tcx>, ctor: &Constructor<'tcx>, ty: Ty<'tcx>) -> u64 {
1489 debug!("constructor_arity({:#?}, {:?})", ctor, ty);
1491 ty::Tuple(ref fs) => fs.len() as u64,
1492 ty::Slice(..) | ty::Array(..) => match *ctor {
1493 Slice(length) => length,
1494 ConstantValue(..) => 0,
1495 _ => bug!("bad slice pattern {:?} {:?}", ctor, ty),
1498 ty::Adt(adt, _) => adt.variants[ctor.variant_index_for_adt(cx, adt)].fields.len() as u64,
1503 /// This computes the types of the sub patterns that a constructor should be
1506 /// For instance, a tuple pattern (43u32, 'a') has sub pattern types [u32, char].
1507 fn constructor_sub_pattern_tys<'a, 'tcx>(
1508 cx: &MatchCheckCtxt<'a, 'tcx>,
1509 ctor: &Constructor<'tcx>,
1511 ) -> Vec<Ty<'tcx>> {
1512 debug!("constructor_sub_pattern_tys({:#?}, {:?})", ctor, ty);
1514 ty::Tuple(ref fs) => fs.into_iter().map(|t| t.expect_ty()).collect(),
1515 ty::Slice(ty) | ty::Array(ty, _) => match *ctor {
1516 Slice(length) => (0..length).map(|_| ty).collect(),
1517 ConstantValue(..) => vec![],
1518 _ => bug!("bad slice pattern {:?} {:?}", ctor, ty),
1520 ty::Ref(_, rty, _) => vec![rty],
1521 ty::Adt(adt, substs) => {
1523 // Use T as the sub pattern type of Box<T>.
1524 vec![substs.type_at(0)]
1526 let variant = &adt.variants[ctor.variant_index_for_adt(cx, adt)];
1527 let is_non_exhaustive = variant.is_field_list_non_exhaustive() && !cx.is_local(ty);
1533 adt.is_enum() || field.vis.is_accessible_from(cx.module, cx.tcx);
1534 let is_uninhabited = cx.is_uninhabited(field.ty(cx.tcx, substs));
1535 match (is_visible, is_non_exhaustive, is_uninhabited) {
1536 // Treat all uninhabited types in non-exhaustive variants as `TyErr`.
1537 (_, true, true) => cx.tcx.types.err,
1538 // Treat all non-visible fields as `TyErr`. They can't appear in any
1539 // other pattern from this match (because they are private), so their
1540 // type does not matter - but we don't want to know they are
1542 (false, ..) => cx.tcx.types.err,
1544 let ty = field.ty(cx.tcx, substs);
1546 // If the field type returned is an array of an unknown size
1549 if len.try_eval_usize(cx.tcx, cx.param_env).is_none() =>
1565 // checks whether a constant is equal to a user-written slice pattern. Only supports byte slices,
1566 // meaning all other types will compare unequal and thus equal patterns often do not cause the
1567 // second pattern to lint about unreachable match arms.
1568 fn slice_pat_covered_by_const<'tcx>(
1571 const_val: &'tcx ty::Const<'tcx>,
1572 prefix: &[Pat<'tcx>],
1573 slice: &Option<Pat<'tcx>>,
1574 suffix: &[Pat<'tcx>],
1575 param_env: ty::ParamEnv<'tcx>,
1576 ) -> Result<bool, ErrorReported> {
1577 let data: &[u8] = match (const_val.val, &const_val.ty.kind) {
1578 (ConstValue::ByRef { offset, alloc, .. }, ty::Array(t, n)) => {
1579 assert_eq!(*t, tcx.types.u8);
1580 let n = n.eval_usize(tcx, param_env);
1581 let ptr = Pointer::new(AllocId(0), offset);
1582 alloc.get_bytes(&tcx, ptr, Size::from_bytes(n)).unwrap()
1584 (ConstValue::Slice { data, start, end }, ty::Slice(t)) => {
1585 assert_eq!(*t, tcx.types.u8);
1586 let ptr = Pointer::new(AllocId(0), Size::from_bytes(start as u64));
1587 data.get_bytes(&tcx, ptr, Size::from_bytes((end - start) as u64)).unwrap()
1589 // FIXME(oli-obk): create a way to extract fat pointers from ByRef
1590 (_, ty::Slice(_)) => return Ok(false),
1592 "slice_pat_covered_by_const: {:#?}, {:#?}, {:#?}, {:#?}",
1600 let pat_len = prefix.len() + suffix.len();
1601 if data.len() < pat_len || (slice.is_none() && data.len() > pat_len) {
1605 for (ch, pat) in data[..prefix.len()]
1608 .chain(data[data.len() - suffix.len()..].iter().zip(suffix))
1611 box PatKind::Constant { value } => {
1612 let b = value.eval_bits(tcx, param_env, pat.ty);
1613 assert_eq!(b as u8 as u128, b);
1625 // Whether to evaluate a constructor using exhaustive integer matching. This is true if the
1626 // constructor is a range or constant with an integer type.
1627 fn should_treat_range_exhaustively(tcx: TyCtxt<'tcx>, ctor: &Constructor<'tcx>) -> bool {
1628 let ty = match ctor {
1629 ConstantValue(value, _) => value.ty,
1630 ConstantRange(_, _, ty, _, _) => ty,
1633 if let ty::Char | ty::Int(_) | ty::Uint(_) = ty.kind {
1634 !ty.is_ptr_sized_integral() || tcx.features().precise_pointer_size_matching
1640 /// For exhaustive integer matching, some constructors are grouped within other constructors
1641 /// (namely integer typed values are grouped within ranges). However, when specialising these
1642 /// constructors, we want to be specialising for the underlying constructors (the integers), not
1643 /// the groups (the ranges). Thus we need to split the groups up. Splitting them up naïvely would
1644 /// mean creating a separate constructor for every single value in the range, which is clearly
1645 /// impractical. However, observe that for some ranges of integers, the specialisation will be
1646 /// identical across all values in that range (i.e., there are equivalence classes of ranges of
1647 /// constructors based on their `is_useful_specialized` outcome). These classes are grouped by
1648 /// the patterns that apply to them (in the matrix `P`). We can split the range whenever the
1649 /// patterns that apply to that range (specifically: the patterns that *intersect* with that range)
1651 /// Our solution, therefore, is to split the range constructor into subranges at every single point
1652 /// the group of intersecting patterns changes (using the method described below).
1653 /// And voilà! We're testing precisely those ranges that we need to, without any exhaustive matching
1654 /// on actual integers. The nice thing about this is that the number of subranges is linear in the
1655 /// number of rows in the matrix (i.e., the number of cases in the `match` statement), so we don't
1656 /// need to be worried about matching over gargantuan ranges.
1658 /// Essentially, given the first column of a matrix representing ranges, looking like the following:
1660 /// |------| |----------| |-------| ||
1661 /// |-------| |-------| |----| ||
1664 /// We split the ranges up into equivalence classes so the ranges are no longer overlapping:
1666 /// |--|--|||-||||--||---|||-------| |-|||| ||
1668 /// The logic for determining how to split the ranges is fairly straightforward: we calculate
1669 /// boundaries for each interval range, sort them, then create constructors for each new interval
1670 /// between every pair of boundary points. (This essentially sums up to performing the intuitive
1671 /// merging operation depicted above.)
1673 /// `hir_id` is `None` when we're evaluating the wildcard pattern, do not lint for overlapping in
1674 /// ranges that case.
1675 fn split_grouped_constructors<'p, 'tcx>(
1677 param_env: ty::ParamEnv<'tcx>,
1678 ctors: Vec<Constructor<'tcx>>,
1679 &Matrix(ref m): &Matrix<'p, 'tcx>,
1682 hir_id: Option<HirId>,
1683 ) -> Vec<Constructor<'tcx>> {
1684 let mut split_ctors = Vec::with_capacity(ctors.len());
1686 for ctor in ctors.into_iter() {
1688 // For now, only ranges may denote groups of "subconstructors", so we only need to
1689 // special-case constant ranges.
1690 ConstantRange(..) if should_treat_range_exhaustively(tcx, &ctor) => {
1691 // We only care about finding all the subranges within the range of the constructor
1692 // range. Anything else is irrelevant, because it is guaranteed to result in
1693 // `NotUseful`, which is the default case anyway, and can be ignored.
1694 let ctor_range = IntRange::from_ctor(tcx, param_env, &ctor).unwrap();
1696 /// Represents a border between 2 integers. Because the intervals spanning borders
1697 /// must be able to cover every integer, we need to be able to represent
1698 /// 2^128 + 1 such borders.
1699 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
1705 // A function for extracting the borders of an integer interval.
1706 fn range_borders(r: IntRange<'_>) -> impl Iterator<Item = Border> {
1707 let (lo, hi) = r.range.into_inner();
1708 let from = Border::JustBefore(lo);
1709 let to = match hi.checked_add(1) {
1710 Some(m) => Border::JustBefore(m),
1711 None => Border::AfterMax,
1713 vec![from, to].into_iter()
1716 // Collect the span and range of all the intersecting ranges to lint on likely
1717 // incorrect range patterns. (#63987)
1718 let mut overlaps = vec![];
1719 // `borders` is the set of borders between equivalence classes: each equivalence
1720 // class lies between 2 borders.
1724 IntRange::from_pat(tcx, param_env, row[0]).map(|r| (r, row.len()))
1726 .flat_map(|(range, row_len)| {
1727 let intersection = ctor_range.intersection(&range);
1728 let should_lint = ctor_range.suspicious_intersection(&range);
1729 if let (Some(range), 1, true) = (&intersection, row_len, should_lint) {
1730 // FIXME: for now, only check for overlapping ranges on simple range
1731 // patterns. Otherwise with the current logic the following is detected
1733 // match (10u8, true) {
1734 // (0 ..= 125, false) => {}
1735 // (126 ..= 255, false) => {}
1736 // (0 ..= 255, true) => {}
1738 overlaps.push(range.clone());
1742 .flat_map(|range| range_borders(range));
1743 let ctor_borders = range_borders(ctor_range.clone());
1744 let mut borders: Vec<_> = row_borders.chain(ctor_borders).collect();
1745 borders.sort_unstable();
1747 lint_overlapping_patterns(tcx, hir_id, ctor_range, ty, overlaps);
1749 // We're going to iterate through every pair of borders, making sure that each
1750 // represents an interval of nonnegative length, and convert each such interval
1751 // into a constructor.
1752 for IntRange { range, .. } in
1753 borders.windows(2).filter_map(|window| match (window[0], window[1]) {
1754 (Border::JustBefore(n), Border::JustBefore(m)) => {
1756 Some(IntRange { range: n..=(m - 1), ty, span })
1761 (Border::JustBefore(n), Border::AfterMax) => {
1762 Some(IntRange { range: n..=u128::MAX, ty, span })
1764 (Border::AfterMax, _) => None,
1767 split_ctors.push(IntRange::range_to_ctor(tcx, ty, range, span));
1770 // Any other constructor can be used unchanged.
1771 _ => split_ctors.push(ctor),
1778 fn lint_overlapping_patterns(
1780 hir_id: Option<HirId>,
1781 ctor_range: IntRange<'tcx>,
1783 overlaps: Vec<IntRange<'tcx>>,
1785 if let (true, Some(hir_id)) = (!overlaps.is_empty(), hir_id) {
1786 let mut err = tcx.struct_span_lint_hir(
1787 lint::builtin::OVERLAPPING_PATTERNS,
1790 "multiple patterns covering the same range",
1792 err.span_label(ctor_range.span, "overlapping patterns");
1793 for int_range in overlaps {
1794 // Use the real type for user display of the ranges:
1798 "this range overlaps on `{}`",
1799 IntRange::range_to_ctor(tcx, ty, int_range.range, DUMMY_SP).display(tcx),
1807 fn constructor_covered_by_range<'tcx>(
1809 param_env: ty::ParamEnv<'tcx>,
1810 ctor: &Constructor<'tcx>,
1812 ) -> Result<bool, ErrorReported> {
1813 let (from, to, end, ty) = match pat.kind {
1814 box PatKind::Constant { value } => (value, value, RangeEnd::Included, value.ty),
1815 box PatKind::Range(PatRange { lo, hi, end }) => (lo, hi, end, lo.ty),
1816 _ => bug!("`constructor_covered_by_range` called with {:?}", pat),
1818 trace!("constructor_covered_by_range {:#?}, {:#?}, {:#?}, {}", ctor, from, to, ty);
1819 let cmp_from = |c_from| {
1820 compare_const_vals(tcx, c_from, from, param_env, ty).map(|res| res != Ordering::Less)
1822 let cmp_to = |c_to| compare_const_vals(tcx, c_to, to, param_env, ty);
1823 macro_rules! some_or_ok {
1827 None => return Ok(false), // not char or int
1832 ConstantValue(value, _) => {
1833 let to = some_or_ok!(cmp_to(value));
1835 (to == Ordering::Less) || (end == RangeEnd::Included && to == Ordering::Equal);
1836 Ok(some_or_ok!(cmp_from(value)) && end)
1838 ConstantRange(from, to, ty, RangeEnd::Included, _) => {
1840 some_or_ok!(cmp_to(ty::Const::from_bits(tcx, to, ty::ParamEnv::empty().and(ty),)));
1842 (to == Ordering::Less) || (end == RangeEnd::Included && to == Ordering::Equal);
1843 Ok(some_or_ok!(cmp_from(ty::Const::from_bits(
1846 ty::ParamEnv::empty().and(ty),
1849 ConstantRange(from, to, ty, RangeEnd::Excluded, _) => {
1851 some_or_ok!(cmp_to(ty::Const::from_bits(tcx, to, ty::ParamEnv::empty().and(ty))));
1853 (to == Ordering::Less) || (end == RangeEnd::Excluded && to == Ordering::Equal);
1854 Ok(some_or_ok!(cmp_from(ty::Const::from_bits(
1857 ty::ParamEnv::empty().and(ty)
1865 fn patterns_for_variant<'p, 'a: 'p, 'tcx>(
1866 cx: &mut MatchCheckCtxt<'a, 'tcx>,
1867 subpatterns: &'p [FieldPat<'tcx>],
1868 wild_patterns: &[&'p Pat<'tcx>],
1869 is_non_exhaustive: bool,
1870 ) -> SmallVec<[&'p Pat<'tcx>; 2]> {
1871 let mut result = SmallVec::from_slice(wild_patterns);
1873 for subpat in subpatterns {
1874 if !is_non_exhaustive || !cx.is_uninhabited(subpat.pattern.ty) {
1875 result[subpat.field.index()] = &subpat.pattern;
1879 debug!("patterns_for_variant({:#?}, {:#?}) = {:#?}", subpatterns, wild_patterns, result);
1883 /// This is the main specialization step. It expands the first pattern in the given row
1884 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
1885 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
1887 /// OTOH, slice patterns with a subslice pattern (tail @ ..) can be expanded into multiple
1888 /// different patterns.
1889 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
1890 /// fields filled with wild patterns.
1891 fn specialize<'p, 'a: 'p, 'tcx>(
1892 cx: &mut MatchCheckCtxt<'a, 'tcx>,
1893 r: &[&'p Pat<'tcx>],
1894 constructor: &Constructor<'tcx>,
1895 wild_patterns: &[&'p Pat<'tcx>],
1896 ) -> Option<SmallVec<[&'p Pat<'tcx>; 2]>> {
1899 let head = match *pat.kind {
1900 PatKind::AscribeUserType { ref subpattern, .. } => {
1901 specialize(cx, ::std::slice::from_ref(&subpattern), constructor, wild_patterns)
1904 PatKind::Binding { .. } | PatKind::Wild => Some(SmallVec::from_slice(wild_patterns)),
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))
1914 PatKind::Leaf { ref subpatterns } => {
1915 Some(patterns_for_variant(cx, subpatterns, wild_patterns, false))
1918 PatKind::Deref { ref subpattern } => Some(smallvec![subpattern]),
1920 PatKind::Constant { value } if constructor.is_slice() => {
1921 // We extract an `Option` for the pointer because slices of zero
1922 // elements don't necessarily point to memory, they are usually
1923 // just integers. The only time they should be pointing to memory
1924 // is when they are subslices of nonzero slices.
1925 let (alloc, offset, n, ty) = match value.ty.kind {
1926 ty::Array(t, n) => match value.val {
1927 ConstValue::ByRef { offset, alloc, .. } => {
1928 (alloc, offset, n.eval_usize(cx.tcx, cx.param_env), t)
1930 _ => span_bug!(pat.span, "array pattern is {:?}", value,),
1934 ConstValue::Slice { data, start, end } => {
1935 (data, Size::from_bytes(start as u64), (end - start) as u64, t)
1937 ConstValue::ByRef { .. } => {
1938 // FIXME(oli-obk): implement `deref` for `ConstValue`
1943 "slice pattern constant must be scalar pair but is {:?}",
1950 "unexpected const-val {:?} with ctor {:?}",
1955 if wild_patterns.len() as u64 == n {
1956 // convert a constant slice/array pattern to a list of patterns.
1957 let layout = cx.tcx.layout_of(cx.param_env.and(ty)).ok()?;
1958 let ptr = Pointer::new(AllocId(0), offset);
1961 let ptr = ptr.offset(layout.size * i, &cx.tcx).ok()?;
1962 let scalar = alloc.read_scalar(&cx.tcx, ptr, layout.size).ok()?;
1963 let scalar = scalar.not_undef().ok()?;
1964 let value = ty::Const::from_scalar(cx.tcx, scalar, ty);
1966 Pat { ty, span: pat.span, kind: box PatKind::Constant { value } };
1967 Some(&*cx.pattern_arena.alloc(pattern))
1975 PatKind::Constant { .. } | PatKind::Range { .. } => {
1976 // If the constructor is a:
1977 // - Single value: add a row if the pattern contains the constructor.
1978 // - Range: add a row if the constructor intersects the pattern.
1979 if should_treat_range_exhaustively(cx.tcx, constructor) {
1981 IntRange::from_ctor(cx.tcx, cx.param_env, constructor),
1982 IntRange::from_pat(cx.tcx, cx.param_env, pat),
1984 (Some(ctor), Some(pat)) => ctor.intersection(&pat).map(|_| {
1985 let (pat_lo, pat_hi) = pat.range.into_inner();
1986 let (ctor_lo, ctor_hi) = ctor.range.into_inner();
1987 assert!(pat_lo <= ctor_lo && ctor_hi <= pat_hi);
1993 // Fallback for non-ranges and ranges that involve
1994 // floating-point numbers, which are not conveniently handled
1995 // by `IntRange`. For these cases, the constructor may not be a
1996 // range so intersection actually devolves into being covered
1998 match constructor_covered_by_range(cx.tcx, cx.param_env, constructor, pat) {
1999 Ok(true) => Some(smallvec![]),
2000 Ok(false) | Err(ErrorReported) => None,
2005 PatKind::Array { ref prefix, ref slice, ref suffix }
2006 | PatKind::Slice { ref prefix, ref slice, ref suffix } => match *constructor {
2008 let pat_len = prefix.len() + suffix.len();
2009 if let Some(slice_count) = wild_patterns.len().checked_sub(pat_len) {
2010 if slice_count == 0 || slice.is_some() {
2020 .chain(suffix.iter()),
2031 ConstantValue(cv, _) => {
2032 match slice_pat_covered_by_const(
2041 Ok(true) => Some(smallvec![]),
2043 Err(ErrorReported) => None,
2046 _ => span_bug!(pat.span, "unexpected ctor {:?} for slice pat", constructor),
2049 PatKind::Or { .. } => {
2050 bug!("support for or-patterns has not been fully implemented yet.");
2053 debug!("specialize({:#?}, {:#?}) = {:#?}", r[0], wild_patterns, head);
2055 head.map(|mut head| {
2056 head.extend_from_slice(&r[1..]);