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).
159 use self::Constructor::*;
160 use self::Usefulness::*;
161 use self::WitnessPreference::*;
163 use rustc_data_structures::fx::FxHashMap;
164 use rustc_data_structures::indexed_vec::Idx;
166 use super::{FieldPattern, Pattern, PatternKind, PatternRange};
167 use super::{PatternFoldable, PatternFolder, compare_const_vals};
169 use rustc::hir::def_id::DefId;
170 use rustc::hir::RangeEnd;
171 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable, Const};
172 use rustc::ty::layout::{Integer, IntegerExt, VariantIdx, Size};
174 use rustc::mir::Field;
175 use rustc::mir::interpret::{ConstValue, Scalar, truncate, AllocId, Pointer};
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, Ordering, min, max};
186 use std::iter::{FromIterator, IntoIterator};
187 use std::ops::RangeInclusive;
189 use std::convert::TryInto;
191 pub fn expand_pattern<'a, 'tcx>(cx: &MatchCheckCtxt<'a, 'tcx>, pat: Pattern<'tcx>)
194 cx.pattern_arena.alloc(LiteralExpander { tcx: cx.tcx }.fold_pattern(&pat))
197 struct LiteralExpander<'tcx> {
201 impl LiteralExpander<'tcx> {
202 /// Derefs `val` and potentially unsizes the value if `crty` is an array and `rty` a slice.
204 /// `crty` and `rty` can differ because you can use array constants in the presence of slice
205 /// patterns. So the pattern may end up being a slice, but the constant is an array. We convert
206 /// the array to a slice in that case.
207 fn fold_const_value_deref(
209 val: ConstValue<'tcx>,
210 // the pattern's pointee type
212 // the constant's pointee type
214 ) -> ConstValue<'tcx> {
215 debug!("fold_const_value_deref {:?} {:?} {:?}", val, rty, crty);
216 match (val, &crty.sty, &rty.sty) {
217 // the easy case, deref a reference
218 (ConstValue::Scalar(Scalar::Ptr(p)), x, y) if x == y => {
219 let alloc = self.tcx.alloc_map.lock().unwrap_memory(p.alloc_id);
225 // unsize array to slice if pattern is array but match value or other patterns are slice
226 (ConstValue::Scalar(Scalar::Ptr(p)), ty::Array(t, n), ty::Slice(u)) => {
229 data: self.tcx.alloc_map.lock().unwrap_memory(p.alloc_id),
230 start: p.offset.bytes().try_into().unwrap(),
231 end: n.eval_usize(self.tcx, ty::ParamEnv::empty()).try_into().unwrap(),
234 // fat pointers stay the same
235 | (ConstValue::Slice { .. }, _, _)
236 | (_, ty::Slice(_), ty::Slice(_))
237 | (_, ty::Str, ty::Str)
239 // FIXME(oli-obk): this is reachable for `const FOO: &&&u32 = &&&42;` being used
240 _ => bug!("cannot deref {:#?}, {} -> {}", val, crty, rty),
245 impl PatternFolder<'tcx> for LiteralExpander<'tcx> {
246 fn fold_pattern(&mut self, pat: &Pattern<'tcx>) -> Pattern<'tcx> {
247 debug!("fold_pattern {:?} {:?} {:?}", pat, pat.ty.sty, pat.kind);
248 match (&pat.ty.sty, &*pat.kind) {
251 &PatternKind::Constant { value: Const {
253 ty: ty::TyS { sty: ty::Ref(_, crty, _), .. },
259 kind: box PatternKind::Deref {
260 subpattern: Pattern {
263 kind: box PatternKind::Constant { value: self.tcx.mk_const(Const {
264 val: self.fold_const_value_deref(*val, rty, crty),
271 (_, &PatternKind::Binding { subpattern: Some(ref s), .. }) => {
274 _ => pat.super_fold_with(self)
279 impl<'tcx> Pattern<'tcx> {
280 fn is_wildcard(&self) -> bool {
282 PatternKind::Binding { subpattern: None, .. } | PatternKind::Wild =>
289 /// A 2D matrix. Nx1 matrices are very common, which is why `SmallVec[_; 2]`
290 /// works well for each row.
291 pub struct Matrix<'p, 'tcx>(Vec<SmallVec<[&'p Pattern<'tcx>; 2]>>);
293 impl<'p, 'tcx> Matrix<'p, 'tcx> {
294 pub fn empty() -> Self {
298 pub fn push(&mut self, row: SmallVec<[&'p Pattern<'tcx>; 2]>) {
303 /// Pretty-printer for matrices of patterns, example:
304 /// ++++++++++++++++++++++++++
306 /// ++++++++++++++++++++++++++
307 /// + true + [First] +
308 /// ++++++++++++++++++++++++++
309 /// + true + [Second(true)] +
310 /// ++++++++++++++++++++++++++
312 /// ++++++++++++++++++++++++++
313 /// + _ + [_, _, ..tail] +
314 /// ++++++++++++++++++++++++++
315 impl<'p, 'tcx> fmt::Debug for Matrix<'p, 'tcx> {
316 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
319 let &Matrix(ref m) = self;
320 let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| {
321 row.iter().map(|pat| format!("{:?}", pat)).collect()
324 let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0);
325 assert!(m.iter().all(|row| row.len() == column_count));
326 let column_widths: Vec<usize> = (0..column_count).map(|col| {
327 pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0)
330 let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1;
331 let br = "+".repeat(total_width);
332 write!(f, "{}\n", br)?;
333 for row in pretty_printed_matrix {
335 for (column, pat_str) in row.into_iter().enumerate() {
337 write!(f, "{:1$}", pat_str, column_widths[column])?;
341 write!(f, "{}\n", br)?;
347 impl<'p, 'tcx> FromIterator<SmallVec<[&'p Pattern<'tcx>; 2]>> for Matrix<'p, 'tcx> {
348 fn from_iter<T>(iter: T) -> Self
349 where T: IntoIterator<Item=SmallVec<[&'p Pattern<'tcx>; 2]>>
351 Matrix(iter.into_iter().collect())
355 pub struct MatchCheckCtxt<'a, 'tcx> {
356 pub tcx: TyCtxt<'tcx>,
357 /// The module in which the match occurs. This is necessary for
358 /// checking inhabited-ness of types because whether a type is (visibly)
359 /// inhabited can depend on whether it was defined in the current module or
360 /// not. E.g., `struct Foo { _private: ! }` cannot be seen to be empty
361 /// outside it's module and should not be matchable with an empty match
364 param_env: ty::ParamEnv<'tcx>,
365 pub pattern_arena: &'a TypedArena<Pattern<'tcx>>,
366 pub byte_array_map: FxHashMap<*const Pattern<'tcx>, Vec<&'a Pattern<'tcx>>>,
369 impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> {
370 pub fn create_and_enter<F, R>(
372 param_env: ty::ParamEnv<'tcx>,
377 F: for<'b> FnOnce(MatchCheckCtxt<'b, 'tcx>) -> R,
379 let pattern_arena = TypedArena::default();
385 pattern_arena: &pattern_arena,
386 byte_array_map: FxHashMap::default(),
390 fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool {
391 if self.tcx.features().exhaustive_patterns {
392 self.tcx.is_ty_uninhabited_from(self.module, ty)
398 fn is_non_exhaustive_variant<'p>(&self, pattern: &'p Pattern<'tcx>) -> bool {
399 match *pattern.kind {
400 PatternKind::Variant { adt_def, variant_index, .. } => {
401 let ref variant = adt_def.variants[variant_index];
402 variant.is_field_list_non_exhaustive()
408 fn is_non_exhaustive_enum(&self, ty: Ty<'tcx>) -> bool {
410 ty::Adt(adt_def, ..) => adt_def.is_variant_list_non_exhaustive(),
415 fn is_local(&self, ty: Ty<'tcx>) -> bool {
417 ty::Adt(adt_def, ..) => adt_def.did.is_local(),
423 #[derive(Clone, Debug, PartialEq)]
424 enum Constructor<'tcx> {
425 /// The constructor of all patterns that don't vary by constructor,
426 /// e.g., struct patterns and fixed-length arrays.
431 ConstantValue(&'tcx ty::Const<'tcx>),
432 /// Ranges of literal values (`2..=5` and `2..5`).
433 ConstantRange(u128, u128, Ty<'tcx>, RangeEnd),
434 /// Array patterns of length n.
438 impl<'tcx> Constructor<'tcx> {
439 fn variant_index_for_adt<'a>(
441 cx: &MatchCheckCtxt<'a, 'tcx>,
442 adt: &'tcx ty::AdtDef,
445 &Variant(id) => adt.variant_index_with_id(id),
447 assert!(!adt.is_enum());
450 &ConstantValue(c) => crate::const_eval::const_variant_index(cx.tcx, cx.param_env, c),
451 _ => bug!("bad constructor {:?} for adt {:?}", self, adt)
456 #[derive(Clone, Debug)]
457 pub enum Usefulness<'tcx> {
459 UsefulWithWitness(Vec<Witness<'tcx>>),
463 impl<'tcx> Usefulness<'tcx> {
464 fn is_useful(&self) -> bool {
472 #[derive(Copy, Clone, Debug)]
473 pub enum WitnessPreference {
478 #[derive(Copy, Clone, Debug)]
479 struct PatternContext<'tcx> {
481 max_slice_length: u64,
484 /// A witness of non-exhaustiveness for error reporting, represented
485 /// as a list of patterns (in reverse order of construction) with
486 /// wildcards inside to represent elements that can take any inhabitant
487 /// of the type as a value.
489 /// A witness against a list of patterns should have the same types
490 /// and length as the pattern matched against. Because Rust `match`
491 /// is always against a single pattern, at the end the witness will
492 /// have length 1, but in the middle of the algorithm, it can contain
493 /// multiple patterns.
495 /// For example, if we are constructing a witness for the match against
497 /// struct Pair(Option<(u32, u32)>, bool);
499 /// match (p: Pair) {
500 /// Pair(None, _) => {}
501 /// Pair(_, false) => {}
505 /// We'll perform the following steps:
506 /// 1. Start with an empty witness
507 /// `Witness(vec![])`
508 /// 2. Push a witness `Some(_)` against the `None`
509 /// `Witness(vec![Some(_)])`
510 /// 3. Push a witness `true` against the `false`
511 /// `Witness(vec![Some(_), true])`
512 /// 4. Apply the `Pair` constructor to the witnesses
513 /// `Witness(vec![Pair(Some(_), true)])`
515 /// The final `Pair(Some(_), true)` is then the resulting witness.
516 #[derive(Clone, Debug)]
517 pub struct Witness<'tcx>(Vec<Pattern<'tcx>>);
519 impl<'tcx> Witness<'tcx> {
520 pub fn single_pattern(&self) -> &Pattern<'tcx> {
521 assert_eq!(self.0.len(), 1);
525 fn push_wild_constructor<'a>(
527 cx: &MatchCheckCtxt<'a, 'tcx>,
528 ctor: &Constructor<'tcx>,
532 let sub_pattern_tys = constructor_sub_pattern_tys(cx, ctor, ty);
533 self.0.extend(sub_pattern_tys.into_iter().map(|ty| {
537 kind: box PatternKind::Wild,
540 self.apply_constructor(cx, ctor, ty)
543 /// Constructs a partial witness for a pattern given a list of
544 /// patterns expanded by the specialization step.
546 /// When a pattern P is discovered to be useful, this function is used bottom-up
547 /// to reconstruct a complete witness, e.g., a pattern P' that covers a subset
548 /// of values, V, where each value in that set is not covered by any previously
549 /// used patterns and is covered by the pattern P'. Examples:
551 /// left_ty: tuple of 3 elements
552 /// pats: [10, 20, _] => (10, 20, _)
554 /// left_ty: struct X { a: (bool, &'static str), b: usize}
555 /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 }
556 fn apply_constructor<'a>(
558 cx: &MatchCheckCtxt<'a,'tcx>,
559 ctor: &Constructor<'tcx>,
563 let arity = constructor_arity(cx, ctor, ty);
565 let len = self.0.len() as u64;
566 let mut pats = self.0.drain((len - arity) as usize..).rev();
571 let pats = pats.enumerate().map(|(i, p)| {
573 field: Field::new(i),
578 if let ty::Adt(adt, substs) = ty.sty {
580 PatternKind::Variant {
583 variant_index: ctor.variant_index_for_adt(cx, adt),
587 PatternKind::Leaf { subpatterns: pats }
590 PatternKind::Leaf { subpatterns: pats }
595 PatternKind::Deref { subpattern: pats.nth(0).unwrap() }
598 ty::Slice(_) | ty::Array(..) => {
600 prefix: pats.collect(),
608 ConstantValue(value) => PatternKind::Constant { value },
609 ConstantRange(lo, hi, ty, end) => PatternKind::Range(PatternRange {
610 lo: ty::Const::from_bits(cx.tcx, lo, ty::ParamEnv::empty().and(ty)),
611 hi: ty::Const::from_bits(cx.tcx, hi, ty::ParamEnv::empty().and(ty)),
615 _ => PatternKind::Wild,
621 self.0.push(Pattern {
631 /// This determines the set of all possible constructors of a pattern matching
632 /// values of type `left_ty`. For vectors, this would normally be an infinite set
633 /// but is instead bounded by the maximum fixed length of slice patterns in
634 /// the column of patterns being analyzed.
636 /// We make sure to omit constructors that are statically impossible. E.g., for
637 /// `Option<!>`, we do not include `Some(_)` in the returned list of constructors.
638 fn all_constructors<'a, 'tcx>(
639 cx: &mut MatchCheckCtxt<'a, 'tcx>,
640 pcx: PatternContext<'tcx>,
641 ) -> Vec<Constructor<'tcx>> {
642 debug!("all_constructors({:?})", pcx.ty);
643 let ctors = match pcx.ty.sty {
645 [true, false].iter().map(|&b| {
646 ConstantValue(ty::Const::from_bool(cx.tcx, b))
649 ty::Array(ref sub_ty, len) if len.try_eval_usize(cx.tcx, cx.param_env).is_some() => {
650 let len = len.eval_usize(cx.tcx, cx.param_env);
651 if len != 0 && cx.is_uninhabited(sub_ty) {
657 // Treat arrays of a constant but unknown length like slices.
658 ty::Array(ref sub_ty, _) |
659 ty::Slice(ref sub_ty) => {
660 if cx.is_uninhabited(sub_ty) {
663 (0..pcx.max_slice_length+1).map(|length| Slice(length)).collect()
666 ty::Adt(def, substs) if def.is_enum() => {
669 !cx.tcx.features().exhaustive_patterns ||
670 !v.uninhabited_from(cx.tcx, substs, def.adt_kind()).contains(cx.tcx, cx.module)
672 .map(|v| Variant(v.def_id))
677 // The valid Unicode Scalar Value ranges.
678 ConstantRange('\u{0000}' as u128,
683 ConstantRange('\u{E000}' as u128,
684 '\u{10FFFF}' as u128,
691 let bits = Integer::from_attr(&cx.tcx, SignedInt(ity)).size().bits() as u128;
692 let min = 1u128 << (bits - 1);
694 vec![ConstantRange(min, max, pcx.ty, RangeEnd::Included)]
697 let size = Integer::from_attr(&cx.tcx, UnsignedInt(uty)).size();
698 let max = truncate(u128::max_value(), size);
699 vec![ConstantRange(0, max, pcx.ty, RangeEnd::Included)]
702 if cx.is_uninhabited(pcx.ty) {
712 fn max_slice_length<'p, 'a, 'tcx, I>(cx: &mut MatchCheckCtxt<'a, 'tcx>, patterns: I) -> u64
714 I: Iterator<Item = &'p Pattern<'tcx>>,
717 // The exhaustiveness-checking paper does not include any details on
718 // checking variable-length slice patterns. However, they are matched
719 // by an infinite collection of fixed-length array patterns.
721 // Checking the infinite set directly would take an infinite amount
722 // of time. However, it turns out that for each finite set of
723 // patterns `P`, all sufficiently large array lengths are equivalent:
725 // Each slice `s` with a "sufficiently-large" length `l ≥ L` that applies
726 // to exactly the subset `Pₜ` of `P` can be transformed to a slice
727 // `sₘ` for each sufficiently-large length `m` that applies to exactly
728 // the same subset of `P`.
730 // Because of that, each witness for reachability-checking from one
731 // of the sufficiently-large lengths can be transformed to an
732 // equally-valid witness from any other length, so we only have
733 // to check slice lengths from the "minimal sufficiently-large length"
736 // Note that the fact that there is a *single* `sₘ` for each `m`
737 // not depending on the specific pattern in `P` is important: if
738 // you look at the pair of patterns
741 // Then any slice of length ≥1 that matches one of these two
742 // patterns can be trivially turned to a slice of any
743 // other length ≥1 that matches them and vice-versa - for
744 // but the slice from length 2 `[false, true]` that matches neither
745 // of these patterns can't be turned to a slice from length 1 that
746 // matches neither of these patterns, so we have to consider
747 // slices from length 2 there.
749 // Now, to see that that length exists and find it, observe that slice
750 // patterns are either "fixed-length" patterns (`[_, _, _]`) or
751 // "variable-length" patterns (`[_, .., _]`).
753 // For fixed-length patterns, all slices with lengths *longer* than
754 // the pattern's length have the same outcome (of not matching), so
755 // as long as `L` is greater than the pattern's length we can pick
756 // any `sₘ` from that length and get the same result.
758 // For variable-length patterns, the situation is more complicated,
759 // because as seen above the precise value of `sₘ` matters.
761 // However, for each variable-length pattern `p` with a prefix of length
762 // `plₚ` and suffix of length `slₚ`, only the first `plₚ` and the last
763 // `slₚ` elements are examined.
765 // Therefore, as long as `L` is positive (to avoid concerns about empty
766 // types), all elements after the maximum prefix length and before
767 // the maximum suffix length are not examined by any variable-length
768 // pattern, and therefore can be added/removed without affecting
769 // them - creating equivalent patterns from any sufficiently-large
772 // Of course, if fixed-length patterns exist, we must be sure
773 // that our length is large enough to miss them all, so
774 // we can pick `L = max(FIXED_LEN+1 ∪ {max(PREFIX_LEN) + max(SUFFIX_LEN)})`
776 // for example, with the above pair of patterns, all elements
777 // but the first and last can be added/removed, so any
778 // witness of length ≥2 (say, `[false, false, true]`) can be
779 // turned to a witness from any other length ≥2.
781 let mut max_prefix_len = 0;
782 let mut max_suffix_len = 0;
783 let mut max_fixed_len = 0;
785 for row in patterns {
787 PatternKind::Constant { value } => {
788 // extract the length of an array/slice from a constant
789 match (value.val, &value.ty.sty) {
790 (_, ty::Array(_, n)) => max_fixed_len = cmp::max(
792 n.eval_usize(cx.tcx, cx.param_env),
794 (ConstValue::Slice{ start, end, .. }, ty::Slice(_)) => max_fixed_len = cmp::max(
796 (end - start) as u64,
801 PatternKind::Slice { ref prefix, slice: None, ref suffix } => {
802 let fixed_len = prefix.len() as u64 + suffix.len() as u64;
803 max_fixed_len = cmp::max(max_fixed_len, fixed_len);
805 PatternKind::Slice { ref prefix, slice: Some(_), ref suffix } => {
806 max_prefix_len = cmp::max(max_prefix_len, prefix.len() as u64);
807 max_suffix_len = cmp::max(max_suffix_len, suffix.len() as u64);
813 cmp::max(max_fixed_len + 1, max_prefix_len + max_suffix_len)
816 /// An inclusive interval, used for precise integer exhaustiveness checking.
817 /// `IntRange`s always store a contiguous range. This means that values are
818 /// encoded such that `0` encodes the minimum value for the integer,
819 /// regardless of the signedness.
820 /// For example, the pattern `-128..=127i8` is encoded as `0..=255`.
821 /// This makes comparisons and arithmetic on interval endpoints much more
822 /// straightforward. See `signed_bias` for details.
824 /// `IntRange` is never used to encode an empty range or a "range" that wraps
825 /// around the (offset) space: i.e., `range.lo <= range.hi`.
827 struct IntRange<'tcx> {
828 pub range: RangeInclusive<u128>,
832 impl<'tcx> IntRange<'tcx> {
835 param_env: ty::ParamEnv<'tcx>,
836 ctor: &Constructor<'tcx>,
837 ) -> Option<IntRange<'tcx>> {
838 // Floating-point ranges are permitted and we don't want
839 // to consider them when constructing integer ranges.
840 fn is_integral(ty: Ty<'_>) -> bool {
842 ty::Char | ty::Int(_) | ty::Uint(_) => true,
848 ConstantRange(lo, hi, ty, end) if is_integral(ty) => {
849 // Perform a shift if the underlying types are signed,
850 // which makes the interval arithmetic simpler.
851 let bias = IntRange::signed_bias(tcx, ty);
852 let (lo, hi) = (lo ^ bias, hi ^ bias);
853 // Make sure the interval is well-formed.
854 if lo > hi || lo == hi && *end == RangeEnd::Excluded {
857 let offset = (*end == RangeEnd::Excluded) as u128;
858 Some(IntRange { range: lo..=(hi - offset), ty })
861 ConstantValue(val) if is_integral(val.ty) => {
863 if let Some(val) = val.try_eval_bits(tcx, param_env, ty) {
864 let bias = IntRange::signed_bias(tcx, ty);
865 let val = val ^ bias;
866 Some(IntRange { range: val..=val, ty })
877 param_env: ty::ParamEnv<'tcx>,
878 mut pat: &Pattern<'tcx>,
879 ) -> Option<IntRange<'tcx>> {
882 box PatternKind::Constant { value } => break ConstantValue(value),
883 box PatternKind::Range(PatternRange { lo, hi, ty, end }) => break ConstantRange(
884 lo.eval_bits(tcx, param_env, ty),
885 hi.eval_bits(tcx, param_env, ty),
889 box PatternKind::AscribeUserType { ref subpattern, .. } => {
895 Self::from_ctor(tcx, param_env, &range)
898 // The return value of `signed_bias` should be XORed with an endpoint to encode/decode it.
899 fn signed_bias(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> u128 {
902 let bits = Integer::from_attr(&tcx, SignedInt(ity)).size().bits() as u128;
909 /// Converts a `RangeInclusive` to a `ConstantValue` or inclusive `ConstantRange`.
913 r: RangeInclusive<u128>,
914 ) -> Constructor<'tcx> {
915 let bias = IntRange::signed_bias(tcx, ty);
916 let (lo, hi) = r.into_inner();
918 let ty = ty::ParamEnv::empty().and(ty);
919 ConstantValue(ty::Const::from_bits(tcx, lo ^ bias, ty))
921 ConstantRange(lo ^ bias, hi ^ bias, ty, RangeEnd::Included)
925 /// Returns a collection of ranges that spans the values covered by `ranges`, subtracted
926 /// by the values covered by `self`: i.e., `ranges \ self` (in set notation).
930 param_env: ty::ParamEnv<'tcx>,
931 ranges: Vec<Constructor<'tcx>>,
932 ) -> Vec<Constructor<'tcx>> {
933 let ranges = ranges.into_iter().filter_map(|r| {
934 IntRange::from_ctor(tcx, param_env, &r).map(|i| i.range)
936 let mut remaining_ranges = vec![];
938 let (lo, hi) = self.range.into_inner();
939 for subrange in ranges {
940 let (subrange_lo, subrange_hi) = subrange.into_inner();
941 if lo > subrange_hi || subrange_lo > hi {
942 // The pattern doesn't intersect with the subrange at all,
943 // so the subrange remains untouched.
944 remaining_ranges.push(Self::range_to_ctor(tcx, ty, subrange_lo..=subrange_hi));
946 if lo > subrange_lo {
947 // The pattern intersects an upper section of the
948 // subrange, so a lower section will remain.
949 remaining_ranges.push(Self::range_to_ctor(tcx, ty, subrange_lo..=(lo - 1)));
951 if hi < subrange_hi {
952 // The pattern intersects a lower section of the
953 // subrange, so an upper section will remain.
954 remaining_ranges.push(Self::range_to_ctor(tcx, ty, (hi + 1)..=subrange_hi));
961 fn intersection(&self, other: &Self) -> Option<Self> {
963 let (lo, hi) = (*self.range.start(), *self.range.end());
964 let (other_lo, other_hi) = (*other.range.start(), *other.range.end());
965 if lo <= other_hi && other_lo <= hi {
966 Some(IntRange { range: max(lo, other_lo)..=min(hi, other_hi), ty })
973 // A request for missing constructor data in terms of either:
974 // - whether or not there any missing constructors; or
975 // - the actual set of missing constructors.
977 enum MissingCtorsInfo {
982 // Used by `compute_missing_ctors`.
983 #[derive(Debug, PartialEq)]
984 enum MissingCtors<'tcx> {
988 // Note that the Vec can be empty.
989 Ctors(Vec<Constructor<'tcx>>),
992 // When `info` is `MissingCtorsInfo::Ctors`, compute a set of constructors
993 // equivalent to `all_ctors \ used_ctors`. When `info` is
994 // `MissingCtorsInfo::Emptiness`, just determines if that set is empty or not.
995 // (The split logic gives a performance win, because we always need to know if
996 // the set is empty, but we rarely need the full set, and it can be expensive
997 // to compute the full set.)
998 fn compute_missing_ctors<'tcx>(
999 info: MissingCtorsInfo,
1001 param_env: ty::ParamEnv<'tcx>,
1002 all_ctors: &Vec<Constructor<'tcx>>,
1003 used_ctors: &Vec<Constructor<'tcx>>,
1004 ) -> MissingCtors<'tcx> {
1005 let mut missing_ctors = vec![];
1007 for req_ctor in all_ctors {
1008 let mut refined_ctors = vec![req_ctor.clone()];
1009 for used_ctor in used_ctors {
1010 if used_ctor == req_ctor {
1011 // If a constructor appears in a `match` arm, we can
1012 // eliminate it straight away.
1013 refined_ctors = vec![]
1014 } else if let Some(interval) = IntRange::from_ctor(tcx, param_env, used_ctor) {
1015 // Refine the required constructors for the type by subtracting
1016 // the range defined by the current constructor pattern.
1017 refined_ctors = interval.subtract_from(tcx, param_env, refined_ctors);
1020 // If the constructor patterns that have been considered so far
1021 // already cover the entire range of values, then we the
1022 // constructor is not missing, and we can move on to the next one.
1023 if refined_ctors.is_empty() {
1027 // If a constructor has not been matched, then it is missing.
1028 // We add `refined_ctors` instead of `req_ctor`, because then we can
1029 // provide more detailed error information about precisely which
1030 // ranges have been omitted.
1031 if info == MissingCtorsInfo::Emptiness {
1032 if !refined_ctors.is_empty() {
1033 // The set is non-empty; return early.
1034 return MissingCtors::NonEmpty;
1037 missing_ctors.extend(refined_ctors);
1041 if info == MissingCtorsInfo::Emptiness {
1042 // If we reached here, the set is empty.
1045 MissingCtors::Ctors(missing_ctors)
1049 /// Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html.
1050 /// The algorithm from the paper has been modified to correctly handle empty
1051 /// types. The changes are:
1052 /// (0) We don't exit early if the pattern matrix has zero rows. We just
1053 /// continue to recurse over columns.
1054 /// (1) all_constructors will only return constructors that are statically
1055 /// possible. E.g., it will only return `Ok` for `Result<T, !>`.
1057 /// This finds whether a (row) vector `v` of patterns is 'useful' in relation
1058 /// to a set of such vectors `m` - this is defined as there being a set of
1059 /// inputs that will match `v` but not any of the sets in `m`.
1061 /// All the patterns at each column of the `matrix ++ v` matrix must
1062 /// have the same type, except that wildcard (PatternKind::Wild) patterns
1063 /// with type `TyErr` are also allowed, even if the "type of the column"
1064 /// is not `TyErr`. That is used to represent private fields, as using their
1065 /// real type would assert that they are inhabited.
1067 /// This is used both for reachability checking (if a pattern isn't useful in
1068 /// relation to preceding patterns, it is not reachable) and exhaustiveness
1069 /// checking (if a wildcard pattern is useful in relation to a matrix, the
1070 /// matrix isn't exhaustive).
1071 pub fn is_useful<'p, 'a, 'tcx>(
1072 cx: &mut MatchCheckCtxt<'a, 'tcx>,
1073 matrix: &Matrix<'p, 'tcx>,
1074 v: &[&Pattern<'tcx>],
1075 witness: WitnessPreference,
1076 ) -> Usefulness<'tcx> {
1077 let &Matrix(ref rows) = matrix;
1078 debug!("is_useful({:#?}, {:#?})", matrix, v);
1080 // The base case. We are pattern-matching on () and the return value is
1081 // based on whether our matrix has a row or not.
1082 // NOTE: This could potentially be optimized by checking rows.is_empty()
1083 // first and then, if v is non-empty, the return value is based on whether
1084 // the type of the tuple we're checking is inhabited or not.
1086 return if rows.is_empty() {
1088 ConstructWitness => UsefulWithWitness(vec![Witness(vec![])]),
1089 LeaveOutWitness => Useful,
1096 assert!(rows.iter().all(|r| r.len() == v.len()));
1098 let pcx = PatternContext {
1099 // TyErr is used to represent the type of wildcard patterns matching
1100 // against inaccessible (private) fields of structs, so that we won't
1101 // be able to observe whether the types of the struct's fields are
1104 // If the field is truly inaccessible, then all the patterns
1105 // matching against it must be wildcard patterns, so its type
1108 // However, if we are matching against non-wildcard patterns, we
1109 // need to know the real type of the field so we can specialize
1110 // against it. This primarily occurs through constants - they
1111 // can include contents for fields that are inaccessible at the
1112 // location of the match. In that case, the field's type is
1113 // inhabited - by the constant - so we can just use it.
1115 // FIXME: this might lead to "unstable" behavior with macro hygiene
1116 // introducing uninhabited patterns for inaccessible fields. We
1117 // need to figure out how to model that.
1118 ty: rows.iter().map(|r| r[0].ty).find(|ty| !ty.references_error()).unwrap_or(v[0].ty),
1119 max_slice_length: max_slice_length(cx, rows.iter().map(|r| r[0]).chain(Some(v[0])))
1122 debug!("is_useful_expand_first_col: pcx={:#?}, expanding {:#?}", pcx, v[0]);
1124 if let Some(constructors) = pat_constructors(cx, v[0], pcx) {
1125 let is_declared_nonexhaustive = cx.is_non_exhaustive_variant(v[0]) && !cx.is_local(pcx.ty);
1126 debug!("is_useful - expanding constructors: {:#?}, is_declared_nonexhaustive: {:?}",
1127 constructors, is_declared_nonexhaustive);
1129 if is_declared_nonexhaustive {
1132 split_grouped_constructors(
1133 cx.tcx, cx.param_env, constructors, matrix, pcx.ty,
1134 ).into_iter().map(|c|
1135 is_useful_specialized(cx, matrix, v, c, pcx.ty, witness)
1136 ).find(|result| result.is_useful()).unwrap_or(NotUseful)
1139 debug!("is_useful - expanding wildcard");
1141 let used_ctors: Vec<Constructor<'_>> = rows.iter().flat_map(|row| {
1142 pat_constructors(cx, row[0], pcx).unwrap_or(vec![])
1144 debug!("used_ctors = {:#?}", used_ctors);
1145 // `all_ctors` are all the constructors for the given type, which
1146 // should all be represented (or caught with the wild pattern `_`).
1147 let all_ctors = all_constructors(cx, pcx);
1148 debug!("all_ctors = {:#?}", all_ctors);
1150 // `missing_ctors` is the set of constructors from the same type as the
1151 // first column of `matrix` that are matched only by wildcard patterns
1152 // from the first column.
1154 // Therefore, if there is some pattern that is unmatched by `matrix`,
1155 // it will still be unmatched if the first constructor is replaced by
1156 // any of the constructors in `missing_ctors`
1158 // However, if our scrutinee is *privately* an empty enum, we
1159 // must treat it as though it had an "unknown" constructor (in
1160 // that case, all other patterns obviously can't be variants)
1161 // to avoid exposing its emptyness. See the `match_privately_empty`
1162 // test for details.
1164 // FIXME: currently the only way I know of something can
1165 // be a privately-empty enum is when the exhaustive_patterns
1166 // feature flag is not present, so this is only
1167 // needed for that case.
1169 // Missing constructors are those that are not matched by any
1170 // non-wildcard patterns in the current column. We always determine if
1171 // the set is empty, but we only fully construct them on-demand,
1172 // because they're rarely used and can be big.
1173 let cheap_missing_ctors = compute_missing_ctors(
1174 MissingCtorsInfo::Emptiness, cx.tcx, cx.param_env, &all_ctors, &used_ctors,
1177 let is_privately_empty = all_ctors.is_empty() && !cx.is_uninhabited(pcx.ty);
1178 let is_declared_nonexhaustive = cx.is_non_exhaustive_enum(pcx.ty) && !cx.is_local(pcx.ty);
1179 debug!("cheap_missing_ctors={:#?} is_privately_empty={:#?} is_declared_nonexhaustive={:#?}",
1180 cheap_missing_ctors, is_privately_empty, is_declared_nonexhaustive);
1182 // For privately empty and non-exhaustive enums, we work as if there were an "extra"
1183 // `_` constructor for the type, so we can never match over all constructors.
1184 let is_non_exhaustive = is_privately_empty || is_declared_nonexhaustive ||
1185 (pcx.ty.is_ptr_sized_integral() && !cx.tcx.features().precise_pointer_size_matching);
1187 if cheap_missing_ctors == MissingCtors::Empty && !is_non_exhaustive {
1188 split_grouped_constructors(cx.tcx, cx.param_env, all_ctors, matrix, pcx.ty)
1189 .into_iter().map(|c| is_useful_specialized(cx, matrix, v, c, pcx.ty, witness))
1190 .find(|result| result.is_useful())
1191 .unwrap_or(NotUseful)
1193 let matrix = rows.iter().filter_map(|r| {
1194 if r[0].is_wildcard() {
1195 Some(SmallVec::from_slice(&r[1..]))
1200 match is_useful(cx, &matrix, &v[1..], witness) {
1201 UsefulWithWitness(pats) => {
1203 // In this case, there's at least one "free"
1204 // constructor that is only matched against by
1205 // wildcard patterns.
1207 // There are 2 ways we can report a witness here.
1208 // Commonly, we can report all the "free"
1209 // constructors as witnesses, e.g., if we have:
1212 // enum Direction { N, S, E, W }
1213 // let Direction::N = ...;
1216 // we can report 3 witnesses: `S`, `E`, and `W`.
1218 // However, there are 2 cases where we don't want
1219 // to do this and instead report a single `_` witness:
1221 // 1) If the user is matching against a non-exhaustive
1222 // enum, there is no point in enumerating all possible
1223 // variants, because the user can't actually match
1224 // against them himself, e.g., in an example like:
1226 // let err: io::ErrorKind = ...;
1228 // io::ErrorKind::NotFound => {},
1231 // we don't want to show every possible IO error,
1232 // but instead have `_` as the witness (this is
1233 // actually *required* if the user specified *all*
1234 // IO errors, but is probably what we want in every
1237 // 2) If the user didn't actually specify a constructor
1238 // in this arm, e.g., in
1240 // let x: (Direction, Direction, bool) = ...;
1241 // let (_, _, false) = x;
1243 // we don't want to show all 16 possible witnesses
1244 // `(<direction-1>, <direction-2>, true)` - we are
1245 // satisfied with `(_, _, true)`. In this case,
1246 // `used_ctors` is empty.
1247 let new_witnesses = if is_non_exhaustive || used_ctors.is_empty() {
1248 // All constructors are unused. Add wild patterns
1249 // rather than each individual constructor.
1250 pats.into_iter().map(|mut witness| {
1251 witness.0.push(Pattern {
1254 kind: box PatternKind::Wild,
1259 let expensive_missing_ctors = compute_missing_ctors(
1260 MissingCtorsInfo::Ctors, cx.tcx, cx.param_env, &all_ctors, &used_ctors,
1262 if let MissingCtors::Ctors(missing_ctors) = expensive_missing_ctors {
1263 pats.into_iter().flat_map(|witness| {
1264 missing_ctors.iter().map(move |ctor| {
1265 // Extends the witness with a "wild" version of this
1266 // constructor, that matches everything that can be built with
1267 // it. For example, if `ctor` is a `Constructor::Variant` for
1268 // `Option::Some`, this pushes the witness for `Some(_)`.
1269 witness.clone().push_wild_constructor(cx, ctor, pcx.ty)
1273 bug!("cheap missing ctors")
1276 UsefulWithWitness(new_witnesses)
1284 /// A shorthand for the `U(S(c, P), S(c, q))` operation from the paper. I.e., `is_useful` applied
1285 /// to the specialised version of both the pattern matrix `P` and the new pattern `q`.
1286 fn is_useful_specialized<'p, 'a, 'tcx>(
1287 cx: &mut MatchCheckCtxt<'a, 'tcx>,
1288 &Matrix(ref m): &Matrix<'p, 'tcx>,
1289 v: &[&Pattern<'tcx>],
1290 ctor: Constructor<'tcx>,
1292 witness: WitnessPreference,
1293 ) -> Usefulness<'tcx> {
1294 debug!("is_useful_specialized({:#?}, {:#?}, {:?})", v, ctor, lty);
1295 let sub_pat_tys = constructor_sub_pattern_tys(cx, &ctor, lty);
1296 let wild_patterns_owned: Vec<_> = sub_pat_tys.iter().map(|ty| {
1300 kind: box PatternKind::Wild,
1303 let wild_patterns: Vec<_> = wild_patterns_owned.iter().collect();
1304 let matrix = Matrix(m.iter().flat_map(|r| {
1305 specialize(cx, &r, &ctor, &wild_patterns)
1307 match specialize(cx, v, &ctor, &wild_patterns) {
1308 Some(v) => match is_useful(cx, &matrix, &v, witness) {
1309 UsefulWithWitness(witnesses) => UsefulWithWitness(
1310 witnesses.into_iter()
1311 .map(|witness| witness.apply_constructor(cx, &ctor, lty))
1320 /// Determines the constructors that the given pattern can be specialized to.
1322 /// In most cases, there's only one constructor that a specific pattern
1323 /// represents, such as a specific enum variant or a specific literal value.
1324 /// Slice patterns, however, can match slices of different lengths. For instance,
1325 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
1327 /// Returns `None` in case of a catch-all, which can't be specialized.
1328 fn pat_constructors<'tcx>(cx: &mut MatchCheckCtxt<'_, 'tcx>,
1329 pat: &Pattern<'tcx>,
1330 pcx: PatternContext<'tcx>)
1331 -> Option<Vec<Constructor<'tcx>>>
1334 PatternKind::AscribeUserType { ref subpattern, .. } =>
1335 pat_constructors(cx, subpattern, pcx),
1336 PatternKind::Binding { .. } | PatternKind::Wild => None,
1337 PatternKind::Leaf { .. } | PatternKind::Deref { .. } => Some(vec![Single]),
1338 PatternKind::Variant { adt_def, variant_index, .. } => {
1339 Some(vec![Variant(adt_def.variants[variant_index].def_id)])
1341 PatternKind::Constant { value } => Some(vec![ConstantValue(value)]),
1342 PatternKind::Range(PatternRange { lo, hi, ty, end }) =>
1343 Some(vec![ConstantRange(
1344 lo.eval_bits(cx.tcx, cx.param_env, ty),
1345 hi.eval_bits(cx.tcx, cx.param_env, ty),
1349 PatternKind::Array { .. } => match pcx.ty.sty {
1350 ty::Array(_, length) => Some(vec![
1351 Slice(length.eval_usize(cx.tcx, cx.param_env))
1353 _ => span_bug!(pat.span, "bad ty {:?} for array pattern", pcx.ty)
1355 PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
1356 let pat_len = prefix.len() as u64 + suffix.len() as u64;
1357 if slice.is_some() {
1358 Some((pat_len..pcx.max_slice_length+1).map(Slice).collect())
1360 Some(vec![Slice(pat_len)])
1366 /// This computes the arity of a constructor. The arity of a constructor
1367 /// is how many subpattern patterns of that constructor should be expanded to.
1369 /// For instance, a tuple pattern `(_, 42, Some([]))` has the arity of 3.
1370 /// A struct pattern's arity is the number of fields it contains, etc.
1371 fn constructor_arity(cx: &MatchCheckCtxt<'a, 'tcx>, ctor: &Constructor<'tcx>, ty: Ty<'tcx>) -> u64 {
1372 debug!("constructor_arity({:#?}, {:?})", ctor, ty);
1374 ty::Tuple(ref fs) => fs.len() as u64,
1375 ty::Slice(..) | ty::Array(..) => match *ctor {
1376 Slice(length) => length,
1377 ConstantValue(_) => 0,
1378 _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
1381 ty::Adt(adt, _) => {
1382 adt.variants[ctor.variant_index_for_adt(cx, adt)].fields.len() as u64
1388 /// This computes the types of the sub patterns that a constructor should be
1391 /// For instance, a tuple pattern (43u32, 'a') has sub pattern types [u32, char].
1392 fn constructor_sub_pattern_tys<'a, 'tcx>(
1393 cx: &MatchCheckCtxt<'a, 'tcx>,
1394 ctor: &Constructor<'tcx>,
1396 ) -> Vec<Ty<'tcx>> {
1397 debug!("constructor_sub_pattern_tys({:#?}, {:?})", ctor, ty);
1399 ty::Tuple(ref fs) => fs.into_iter().map(|t| t.expect_ty()).collect(),
1400 ty::Slice(ty) | ty::Array(ty, _) => match *ctor {
1401 Slice(length) => (0..length).map(|_| ty).collect(),
1402 ConstantValue(_) => vec![],
1403 _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
1405 ty::Ref(_, rty, _) => vec![rty],
1406 ty::Adt(adt, substs) => {
1408 // Use T as the sub pattern type of Box<T>.
1409 vec![substs.type_at(0)]
1411 adt.variants[ctor.variant_index_for_adt(cx, adt)].fields.iter().map(|field| {
1412 let is_visible = adt.is_enum()
1413 || field.vis.is_accessible_from(cx.module, cx.tcx);
1415 let ty = field.ty(cx.tcx, substs);
1417 // If the field type returned is an array of an unknown
1418 // size return an TyErr.
1420 if len.try_eval_usize(cx.tcx, cx.param_env).is_none() =>
1425 // Treat all non-visible fields as TyErr. They
1426 // can't appear in any other pattern from
1427 // this match (because they are private),
1428 // so their type does not matter - but
1429 // we don't want to know they are
1440 // checks whether a constant is equal to a user-written slice pattern. Only supports byte slices,
1441 // meaning all other types will compare unequal and thus equal patterns often do not cause the
1442 // second pattern to lint about unreachable match arms.
1443 fn slice_pat_covered_by_const<'tcx>(
1446 const_val: &'tcx ty::Const<'tcx>,
1447 prefix: &[Pattern<'tcx>],
1448 slice: &Option<Pattern<'tcx>>,
1449 suffix: &[Pattern<'tcx>],
1450 param_env: ty::ParamEnv<'tcx>,
1451 ) -> Result<bool, ErrorReported> {
1452 let data: &[u8] = match (const_val.val, &const_val.ty.sty) {
1453 (ConstValue::ByRef { offset, alloc, .. }, ty::Array(t, n)) => {
1454 assert_eq!(*t, tcx.types.u8);
1455 let n = n.eval_usize(tcx, param_env);
1456 let ptr = Pointer::new(AllocId(0), offset);
1457 alloc.get_bytes(&tcx, ptr, Size::from_bytes(n)).unwrap()
1459 (ConstValue::Slice { data, start, end }, ty::Slice(t)) => {
1460 assert_eq!(*t, tcx.types.u8);
1461 let ptr = Pointer::new(AllocId(0), Size::from_bytes(start as u64));
1462 data.get_bytes(&tcx, ptr, Size::from_bytes((end - start) as u64)).unwrap()
1464 // FIXME(oli-obk): create a way to extract fat pointers from ByRef
1465 (_, ty::Slice(_)) => return Ok(false),
1467 "slice_pat_covered_by_const: {:#?}, {:#?}, {:#?}, {:#?}",
1468 const_val, prefix, slice, suffix,
1472 let pat_len = prefix.len() + suffix.len();
1473 if data.len() < pat_len || (slice.is_none() && data.len() > pat_len) {
1478 data[..prefix.len()].iter().zip(prefix).chain(
1479 data[data.len()-suffix.len()..].iter().zip(suffix))
1482 box PatternKind::Constant { value } => {
1483 let b = value.eval_bits(tcx, param_env, pat.ty);
1484 assert_eq!(b as u8 as u128, b);
1496 // Whether to evaluate a constructor using exhaustive integer matching. This is true if the
1497 // constructor is a range or constant with an integer type.
1498 fn should_treat_range_exhaustively(tcx: TyCtxt<'tcx>, ctor: &Constructor<'tcx>) -> bool {
1499 let ty = match ctor {
1500 ConstantValue(value) => value.ty,
1501 ConstantRange(_, _, ty, _) => ty,
1504 if let ty::Char | ty::Int(_) | ty::Uint(_) = ty.sty {
1505 !ty.is_ptr_sized_integral() || tcx.features().precise_pointer_size_matching
1511 /// For exhaustive integer matching, some constructors are grouped within other constructors
1512 /// (namely integer typed values are grouped within ranges). However, when specialising these
1513 /// constructors, we want to be specialising for the underlying constructors (the integers), not
1514 /// the groups (the ranges). Thus we need to split the groups up. Splitting them up naïvely would
1515 /// mean creating a separate constructor for every single value in the range, which is clearly
1516 /// impractical. However, observe that for some ranges of integers, the specialisation will be
1517 /// identical across all values in that range (i.e., there are equivalence classes of ranges of
1518 /// constructors based on their `is_useful_specialized` outcome). These classes are grouped by
1519 /// the patterns that apply to them (in the matrix `P`). We can split the range whenever the
1520 /// patterns that apply to that range (specifically: the patterns that *intersect* with that range)
1522 /// Our solution, therefore, is to split the range constructor into subranges at every single point
1523 /// the group of intersecting patterns changes (using the method described below).
1524 /// And voilà! We're testing precisely those ranges that we need to, without any exhaustive matching
1525 /// on actual integers. The nice thing about this is that the number of subranges is linear in the
1526 /// number of rows in the matrix (i.e., the number of cases in the `match` statement), so we don't
1527 /// need to be worried about matching over gargantuan ranges.
1529 /// Essentially, given the first column of a matrix representing ranges, looking like the following:
1531 /// |------| |----------| |-------| ||
1532 /// |-------| |-------| |----| ||
1535 /// We split the ranges up into equivalence classes so the ranges are no longer overlapping:
1537 /// |--|--|||-||||--||---|||-------| |-|||| ||
1539 /// The logic for determining how to split the ranges is fairly straightforward: we calculate
1540 /// boundaries for each interval range, sort them, then create constructors for each new interval
1541 /// between every pair of boundary points. (This essentially sums up to performing the intuitive
1542 /// merging operation depicted above.)
1543 fn split_grouped_constructors<'p, 'tcx>(
1545 param_env: ty::ParamEnv<'tcx>,
1546 ctors: Vec<Constructor<'tcx>>,
1547 &Matrix(ref m): &Matrix<'p, 'tcx>,
1549 ) -> Vec<Constructor<'tcx>> {
1550 let mut split_ctors = Vec::with_capacity(ctors.len());
1552 for ctor in ctors.into_iter() {
1554 // For now, only ranges may denote groups of "subconstructors", so we only need to
1555 // special-case constant ranges.
1556 ConstantRange(..) if should_treat_range_exhaustively(tcx, &ctor) => {
1557 // We only care about finding all the subranges within the range of the constructor
1558 // range. Anything else is irrelevant, because it is guaranteed to result in
1559 // `NotUseful`, which is the default case anyway, and can be ignored.
1560 let ctor_range = IntRange::from_ctor(tcx, param_env, &ctor).unwrap();
1562 /// Represents a border between 2 integers. Because the intervals spanning borders
1563 /// must be able to cover every integer, we need to be able to represent
1564 /// 2^128 + 1 such borders.
1565 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1571 // A function for extracting the borders of an integer interval.
1572 fn range_borders(r: IntRange<'_>) -> impl Iterator<Item = Border> {
1573 let (lo, hi) = r.range.into_inner();
1574 let from = Border::JustBefore(lo);
1575 let to = match hi.checked_add(1) {
1576 Some(m) => Border::JustBefore(m),
1577 None => Border::AfterMax,
1579 vec![from, to].into_iter()
1582 // `borders` is the set of borders between equivalence classes: each equivalence
1583 // class lies between 2 borders.
1584 let row_borders = m.iter()
1585 .flat_map(|row| IntRange::from_pat(tcx, param_env, row[0]))
1586 .flat_map(|range| ctor_range.intersection(&range))
1587 .flat_map(|range| range_borders(range));
1588 let ctor_borders = range_borders(ctor_range.clone());
1589 let mut borders: Vec<_> = row_borders.chain(ctor_borders).collect();
1590 borders.sort_unstable();
1592 // We're going to iterate through every pair of borders, making sure that each
1593 // represents an interval of nonnegative length, and convert each such interval
1594 // into a constructor.
1595 for IntRange { range, .. } in borders.windows(2).filter_map(|window| {
1596 match (window[0], window[1]) {
1597 (Border::JustBefore(n), Border::JustBefore(m)) => {
1599 Some(IntRange { range: n..=(m - 1), ty })
1604 (Border::JustBefore(n), Border::AfterMax) => {
1605 Some(IntRange { range: n..=u128::MAX, ty })
1607 (Border::AfterMax, _) => None,
1610 split_ctors.push(IntRange::range_to_ctor(tcx, ty, range));
1613 // Any other constructor can be used unchanged.
1614 _ => split_ctors.push(ctor),
1621 /// Checks whether there exists any shared value in either `ctor` or `pat` by intersecting them.
1622 fn constructor_intersects_pattern<'p, 'tcx>(
1624 param_env: ty::ParamEnv<'tcx>,
1625 ctor: &Constructor<'tcx>,
1626 pat: &'p Pattern<'tcx>,
1627 ) -> Option<SmallVec<[&'p Pattern<'tcx>; 2]>> {
1628 if should_treat_range_exhaustively(tcx, ctor) {
1629 match (IntRange::from_ctor(tcx, param_env, ctor), IntRange::from_pat(tcx, param_env, pat)) {
1630 (Some(ctor), Some(pat)) => {
1631 ctor.intersection(&pat).map(|_| {
1632 let (pat_lo, pat_hi) = pat.range.into_inner();
1633 let (ctor_lo, ctor_hi) = ctor.range.into_inner();
1634 assert!(pat_lo <= ctor_lo && ctor_hi <= pat_hi);
1641 // Fallback for non-ranges and ranges that involve floating-point numbers, which are not
1642 // conveniently handled by `IntRange`. For these cases, the constructor may not be a range
1643 // so intersection actually devolves into being covered by the pattern.
1644 match constructor_covered_by_range(tcx, param_env, ctor, pat) {
1645 Ok(true) => Some(smallvec![]),
1646 Ok(false) | Err(ErrorReported) => None,
1651 fn constructor_covered_by_range<'tcx>(
1653 param_env: ty::ParamEnv<'tcx>,
1654 ctor: &Constructor<'tcx>,
1655 pat: &Pattern<'tcx>,
1656 ) -> Result<bool, ErrorReported> {
1657 let (from, to, end, ty) = match pat.kind {
1658 box PatternKind::Constant { value } => (value, value, RangeEnd::Included, value.ty),
1659 box PatternKind::Range(PatternRange { lo, hi, end, ty }) => (lo, hi, end, ty),
1660 _ => bug!("`constructor_covered_by_range` called with {:?}", pat),
1662 trace!("constructor_covered_by_range {:#?}, {:#?}, {:#?}, {}", ctor, from, to, ty);
1663 let cmp_from = |c_from| compare_const_vals(tcx, c_from, from, param_env, ty)
1664 .map(|res| res != Ordering::Less);
1665 let cmp_to = |c_to| compare_const_vals(tcx, c_to, to, param_env, ty);
1666 macro_rules! some_or_ok {
1670 None => return Ok(false), // not char or int
1675 ConstantValue(value) => {
1676 let to = some_or_ok!(cmp_to(value));
1677 let end = (to == Ordering::Less) ||
1678 (end == RangeEnd::Included && to == Ordering::Equal);
1679 Ok(some_or_ok!(cmp_from(value)) && end)
1681 ConstantRange(from, to, ty, RangeEnd::Included) => {
1682 let to = some_or_ok!(cmp_to(ty::Const::from_bits(
1685 ty::ParamEnv::empty().and(ty),
1687 let end = (to == Ordering::Less) ||
1688 (end == RangeEnd::Included && to == Ordering::Equal);
1689 Ok(some_or_ok!(cmp_from(ty::Const::from_bits(
1692 ty::ParamEnv::empty().and(ty),
1695 ConstantRange(from, to, ty, RangeEnd::Excluded) => {
1696 let to = some_or_ok!(cmp_to(ty::Const::from_bits(
1699 ty::ParamEnv::empty().and(ty)
1701 let end = (to == Ordering::Less) ||
1702 (end == RangeEnd::Excluded && to == Ordering::Equal);
1703 Ok(some_or_ok!(cmp_from(ty::Const::from_bits(
1706 ty::ParamEnv::empty().and(ty)))
1714 fn patterns_for_variant<'p, 'tcx>(
1715 subpatterns: &'p [FieldPattern<'tcx>],
1716 wild_patterns: &[&'p Pattern<'tcx>])
1717 -> SmallVec<[&'p Pattern<'tcx>; 2]>
1719 let mut result = SmallVec::from_slice(wild_patterns);
1721 for subpat in subpatterns {
1722 result[subpat.field.index()] = &subpat.pattern;
1725 debug!("patterns_for_variant({:#?}, {:#?}) = {:#?}", subpatterns, wild_patterns, result);
1729 /// This is the main specialization step. It expands the first pattern in the given row
1730 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
1731 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
1733 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
1734 /// different patterns.
1735 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
1736 /// fields filled with wild patterns.
1737 fn specialize<'p, 'a: 'p, 'tcx>(
1738 cx: &mut MatchCheckCtxt<'a, 'tcx>,
1739 r: &[&'p Pattern<'tcx>],
1740 constructor: &Constructor<'tcx>,
1741 wild_patterns: &[&'p Pattern<'tcx>],
1742 ) -> Option<SmallVec<[&'p Pattern<'tcx>; 2]>> {
1745 let head = match *pat.kind {
1746 PatternKind::AscribeUserType { ref subpattern, .. } => {
1747 specialize(cx, ::std::slice::from_ref(&subpattern), constructor, wild_patterns)
1750 PatternKind::Binding { .. } | PatternKind::Wild => {
1751 Some(SmallVec::from_slice(wild_patterns))
1754 PatternKind::Variant { adt_def, variant_index, ref subpatterns, .. } => {
1755 let ref variant = adt_def.variants[variant_index];
1756 Some(Variant(variant.def_id))
1757 .filter(|variant_constructor| variant_constructor == constructor)
1758 .map(|_| patterns_for_variant(subpatterns, wild_patterns))
1761 PatternKind::Leaf { ref subpatterns } => {
1762 Some(patterns_for_variant(subpatterns, wild_patterns))
1765 PatternKind::Deref { ref subpattern } => {
1766 Some(smallvec![subpattern])
1769 PatternKind::Constant { value } => {
1770 match *constructor {
1772 // we extract an `Option` for the pointer because slices of zero elements don't
1773 // necessarily point to memory, they are usually just integers. The only time
1774 // they should be pointing to memory is when they are subslices of nonzero
1776 let (alloc, offset, n, ty) = match value.ty.sty {
1777 ty::Array(t, n) => {
1779 ConstValue::ByRef { offset, alloc, .. } => (
1782 n.eval_usize(cx.tcx, cx.param_env),
1787 "array pattern is {:?}", value,
1793 ConstValue::Slice { data, start, end } => (
1795 Size::from_bytes(start as u64),
1796 (end - start) as u64,
1799 ConstValue::ByRef { .. } => {
1800 // FIXME(oli-obk): implement `deref` for `ConstValue`
1805 "slice pattern constant must be scalar pair but is {:?}",
1812 "unexpected const-val {:?} with ctor {:?}",
1817 if wild_patterns.len() as u64 == n {
1818 // convert a constant slice/array pattern to a list of patterns.
1819 let layout = cx.tcx.layout_of(cx.param_env.and(ty)).ok()?;
1820 let ptr = Pointer::new(AllocId(0), offset);
1822 let ptr = ptr.offset(layout.size * i, &cx.tcx).ok()?;
1823 let scalar = alloc.read_scalar(
1824 &cx.tcx, ptr, layout.size,
1826 let scalar = scalar.not_undef().ok()?;
1827 let value = ty::Const::from_scalar(cx.tcx, scalar, ty);
1828 let pattern = Pattern {
1831 kind: box PatternKind::Constant { value },
1833 Some(&*cx.pattern_arena.alloc(pattern))
1840 // If the constructor is a:
1841 // Single value: add a row if the constructor equals the pattern.
1842 // Range: add a row if the constructor contains the pattern.
1843 constructor_intersects_pattern(cx.tcx, cx.param_env, constructor, pat)
1848 PatternKind::Range { .. } => {
1849 // If the constructor is a:
1850 // Single value: add a row if the pattern contains the constructor.
1851 // Range: add a row if the constructor intersects the pattern.
1852 constructor_intersects_pattern(cx.tcx, cx.param_env, constructor, pat)
1855 PatternKind::Array { ref prefix, ref slice, ref suffix } |
1856 PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
1857 match *constructor {
1859 let pat_len = prefix.len() + suffix.len();
1860 if let Some(slice_count) = wild_patterns.len().checked_sub(pat_len) {
1861 if slice_count == 0 || slice.is_some() {
1862 Some(prefix.iter().chain(
1863 wild_patterns.iter().map(|p| *p)
1866 .chain(suffix.iter())
1875 ConstantValue(cv) => {
1876 match slice_pat_covered_by_const(
1877 cx.tcx, pat.span, cv, prefix, slice, suffix, cx.param_env,
1879 Ok(true) => Some(smallvec![]),
1881 Err(ErrorReported) => None
1884 _ => span_bug!(pat.span,
1885 "unexpected ctor {:?} for slice pat", constructor)
1889 debug!("specialize({:#?}, {:#?}) = {:#?}", r[0], wild_patterns, head);
1891 head.map(|mut head| {
1892 head.extend_from_slice(&r[1 ..]);