1 // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 /// This file includes the logic for exhaustiveness and usefulness checking for
12 /// pattern-matching. Specifically, given a list of patterns for a type, we can
14 /// (a) the patterns cover every possible constructor for the type [exhaustiveness]
15 /// (b) each pattern is necessary [usefulness]
17 /// The algorithm implemented here is a modified version of the one described in:
18 /// http://moscova.inria.fr/~maranget/papers/warn/index.html
19 /// However, to save future implementors from reading the original paper, I'm going
20 /// to summarise the algorithm here to hopefully save time and be a little clearer
21 /// (without being so rigorous).
23 /// The core of the algorithm revolves about a "usefulness" check. In particular, we
24 /// are trying to compute a predicate `U(P, p_{m + 1})` where `P` is a list of patterns
25 /// of length `m` for a compound (product) type with `n` components (we refer to this as
26 /// a matrix). `U(P, p_{m + 1})` represents whether, given an existing list of patterns
27 /// `p_1 ..= p_m`, adding a new pattern will be "useful" (that is, cover previously-
28 /// uncovered values of the type).
30 /// If we have this predicate, then we can easily compute both exhaustiveness of an
31 /// entire set of patterns and the individual usefulness of each one.
32 /// (a) the set of patterns is exhaustive iff `U(P, _)` is false (i.e. adding a wildcard
33 /// match doesn't increase the number of values we're matching)
34 /// (b) a pattern `p_i` is not useful if `U(P[0..=(i-1), p_i)` is false (i.e. adding a
35 /// pattern to those that have come before it doesn't increase the number of values
38 /// For example, say we have the following:
40 /// // x: (Option<bool>, Result<()>)
42 /// (Some(true), _) => {}
43 /// (None, Err(())) => {}
44 /// (None, Err(_)) => {}
47 /// Here, the matrix `P` is 3 x 2 (rows x columns).
53 /// We can tell it's not exhaustive, because `U(P, _)` is true (we're not covering
54 /// `[Some(false), _]`, for instance). In addition, row 3 is not useful, because
55 /// all the values it covers are already covered by row 2.
57 /// To compute `U`, we must have two other concepts.
58 /// 1. `S(c, P)` is a "specialised matrix", where `c` is a constructor (like `Some` or
59 /// `None`). You can think of it as filtering `P` to just the rows whose *first* pattern
60 /// can cover `c` (and expanding OR-patterns into distinct patterns), and then expanding
61 /// the constructor into all of its components.
62 /// The specialisation of a row vector is computed by `specialize`.
64 /// It is computed as follows. For each row `p_i` of P, we have four cases:
65 /// 1.1. `p_(i,1)= c(r_1, .., r_a)`. Then `S(c, P)` has a corresponding row:
66 /// r_1, .., r_a, p_(i,2), .., p_(i,n)
67 /// 1.2. `p_(i,1) = c'(r_1, .., r_a')` where `c ≠ c'`. Then `S(c, P)` has no
68 /// corresponding row.
69 /// 1.3. `p_(i,1) = _`. Then `S(c, P)` has a corresponding row:
70 /// _, .., _, p_(i,2), .., p_(i,n)
71 /// 1.4. `p_(i,1) = r_1 | r_2`. Then `S(c, P)` has corresponding rows inlined from:
72 /// S(c, (r_1, p_(i,2), .., p_(i,n)))
73 /// S(c, (r_2, p_(i,2), .., p_(i,n)))
75 /// 2. `D(P)` is a "default matrix". This is used when we know there are missing
76 /// constructor cases, but there might be existing wildcard patterns, so to check the
77 /// usefulness of the matrix, we have to check all its *other* components.
78 /// The default matrix is computed inline in `is_useful`.
80 /// It is computed as follows. For each row `p_i` of P, we have three cases:
81 /// 1.1. `p_(i,1) = c(r_1, .., r_a)`. Then `D(P)` has no corresponding row.
82 /// 1.2. `p_(i,1) = _`. Then `D(P)` has a corresponding row:
83 /// p_(i,2), .., p_(i,n)
84 /// 1.3. `p_(i,1) = r_1 | r_2`. Then `D(P)` has corresponding rows inlined from:
85 /// D((r_1, p_(i,2), .., p_(i,n)))
86 /// D((r_2, p_(i,2), .., p_(i,n)))
88 /// The algorithm for computing `U`
89 /// -------------------------------
90 /// The algorithm is inductive (on the number of columns: i.e. components of tuple patterns).
91 /// That means we're going to check the components from left-to-right, so the algorithm
92 /// operates principally on the first component of the matrix and new pattern `p_{m + 1}`.
93 /// This algorithm is realised in the `is_useful` function.
95 /// Base case. (`n = 0`, i.e. an empty tuple pattern)
96 /// - If `P` already contains an empty pattern (i.e. if the number of patterns `m > 0`),
97 /// then `U(P, p_{m + 1})` is false.
98 /// - Otherwise, `P` must be empty, so `U(P, p_{m + 1})` is true.
100 /// Inductive step. (`n > 0`, i.e. 1 or more tuple pattern components)
101 /// We're going to match on the new pattern, `p_{m + 1}`.
102 /// - If `p_{m + 1} == c(r_1, .., r_a)`, then we have a constructor pattern.
103 /// Thus, the usefulness of `p_{m + 1}` can be reduced to whether it is useful when
104 /// we ignore all the patterns in `P` that involve other constructors. This is where
105 /// `S(c, P)` comes in:
106 /// `U(P, p_{m + 1}) := U(S(c, P), S(c, p_{m + 1}))`
107 /// This special case is handled in `is_useful_specialized`.
108 /// - If `p_{m + 1} == _`, then we have two more cases:
109 /// + All the constructors of the first component of the type exist within
110 /// all the rows (after having expanded OR-patterns). In this case:
111 /// `U(P, p_{m + 1}) := ∨(k ϵ constructors) U(S(k, P), S(k, p_{m + 1}))`
112 /// I.e. the pattern `p_{m + 1}` is only useful when all the constructors are
113 /// present *if* its later components are useful for the respective constructors
114 /// covered by `p_{m + 1}` (usually a single constructor, but all in the case of `_`).
115 /// + Some constructors are not present in the existing rows (after having expanded
116 /// OR-patterns). However, there might be wildcard patterns (`_`) present. Thus, we
117 /// are only really concerned with the other patterns leading with wildcards. This is
118 /// where `D` comes in:
119 /// `U(P, p_{m + 1}) := U(D(P), p_({m + 1},2), .., p_({m + 1},n))`
120 /// - If `p_{m + 1} == r_1 | r_2`, then the usefulness depends on each separately:
121 /// `U(P, p_{m + 1}) := U(P, (r_1, p_({m + 1},2), .., p_({m + 1},n)))
122 /// || U(P, (r_2, p_({m + 1},2), .., p_({m + 1},n)))`
124 /// Modifications to the algorithm
125 /// ------------------------------
126 /// The algorithm in the paper doesn't cover some of the special cases that arise in Rust, for
127 /// example uninhabited types and variable-length slice patterns. These are drawn attention to
128 /// throughout the code below. I'll make a quick note here about how exhaustive integer matching
129 /// is accounted for, though.
131 /// Exhaustive integer matching
132 /// ---------------------------
133 /// An integer type can be thought of as a (huge) sum type: 1 | 2 | 3 | ...
134 /// So to support exhaustive integer matching, we can make use of the logic in the paper for
135 /// OR-patterns. However, we obviously can't just treat ranges x..=y as individual sums, because
136 /// they are likely gigantic. So we instead treat ranges as constructors of the integers. This means
137 /// that we have a constructor *of* constructors (the integers themselves). We then need to work
138 /// through all the inductive step rules above, deriving how the ranges would be treated as
139 /// OR-patterns, and making sure that they're treated in the same way even when they're ranges.
140 /// There are really only four special cases here:
141 /// - When we match on a constructor that's actually a range, we have to treat it as if we would
143 /// + It turns out that we can simply extend the case for single-value patterns in
144 /// `specialize` to either be *equal* to a value constructor, or *contained within* a range
146 /// + When the pattern itself is a range, you just want to tell whether any of the values in
147 /// the pattern range coincide with values in the constructor range, which is precisely
149 /// Since when encountering a range pattern for a value constructor, we also use inclusion, it
150 /// means that whenever the constructor is a value/range and the pattern is also a value/range,
151 /// we can simply use intersection to test usefulness.
152 /// - When we're testing for usefulness of a pattern and the pattern's first component is a
154 /// + If all the constructors appear in the matrix, we have a slight complication. By default,
155 /// the behaviour (i.e. a disjunction over specialised matrices for each constructor) is
156 /// invalid, because we want a disjunction over every *integer* in each range, not just a
157 /// disjunction over every range. This is a bit more tricky to deal with: essentially we need
158 /// to form equivalence classes of subranges of the constructor range for which the behaviour
159 /// of the matrix `P` and new pattern `p_{m + 1}` are the same. This is described in more
160 /// detail in `split_grouped_constructors`.
161 /// + If some constructors are missing from the matrix, it turns out we don't need to do
162 /// anything special (because we know none of the integers are actually wildcards: i.e. we
163 /// can't span wildcards using ranges).
165 use self::Constructor::*;
166 use self::Usefulness::*;
167 use self::WitnessPreference::*;
169 use rustc_data_structures::fx::FxHashMap;
170 use rustc_data_structures::indexed_vec::Idx;
172 use super::{FieldPattern, Pattern, PatternKind};
173 use super::{PatternFoldable, PatternFolder, compare_const_vals};
175 use rustc::hir::def_id::DefId;
176 use rustc::hir::RangeEnd;
177 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
178 use rustc::ty::layout::{Integer, IntegerExt};
180 use rustc::mir::Field;
181 use rustc::mir::interpret::ConstValue;
182 use rustc::util::common::ErrorReported;
184 use syntax::attr::{SignedInt, UnsignedInt};
185 use syntax_pos::{Span, DUMMY_SP};
187 use arena::TypedArena;
189 use std::cmp::{self, Ordering, min, max};
191 use std::iter::{FromIterator, IntoIterator};
192 use std::ops::RangeInclusive;
194 pub fn expand_pattern<'a, 'tcx>(cx: &MatchCheckCtxt<'a, 'tcx>, pat: Pattern<'tcx>)
197 cx.pattern_arena.alloc(LiteralExpander.fold_pattern(&pat))
200 struct LiteralExpander;
201 impl<'tcx> PatternFolder<'tcx> for LiteralExpander {
202 fn fold_pattern(&mut self, pat: &Pattern<'tcx>) -> Pattern<'tcx> {
203 match (&pat.ty.sty, &*pat.kind) {
204 (&ty::TyRef(_, rty, _), &PatternKind::Constant { ref value }) => {
208 kind: box PatternKind::Deref {
209 subpattern: Pattern {
212 kind: box PatternKind::Constant { value: value.clone() },
217 (_, &PatternKind::Binding { subpattern: Some(ref s), .. }) => {
220 _ => pat.super_fold_with(self)
225 impl<'tcx> Pattern<'tcx> {
226 fn is_wildcard(&self) -> bool {
228 PatternKind::Binding { subpattern: None, .. } | PatternKind::Wild =>
235 pub struct Matrix<'a, 'tcx: 'a>(Vec<Vec<&'a Pattern<'tcx>>>);
237 impl<'a, 'tcx> Matrix<'a, 'tcx> {
238 pub fn empty() -> Self {
242 pub fn push(&mut self, row: Vec<&'a Pattern<'tcx>>) {
247 /// Pretty-printer for matrices of patterns, example:
248 /// ++++++++++++++++++++++++++
250 /// ++++++++++++++++++++++++++
251 /// + true + [First] +
252 /// ++++++++++++++++++++++++++
253 /// + true + [Second(true)] +
254 /// ++++++++++++++++++++++++++
256 /// ++++++++++++++++++++++++++
257 /// + _ + [_, _, ..tail] +
258 /// ++++++++++++++++++++++++++
259 impl<'a, 'tcx> fmt::Debug for Matrix<'a, 'tcx> {
260 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
263 let &Matrix(ref m) = self;
264 let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| {
265 row.iter().map(|pat| format!("{:?}", pat)).collect()
268 let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0);
269 assert!(m.iter().all(|row| row.len() == column_count));
270 let column_widths: Vec<usize> = (0..column_count).map(|col| {
271 pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0)
274 let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1;
275 let br = "+".repeat(total_width);
276 write!(f, "{}\n", br)?;
277 for row in pretty_printed_matrix {
279 for (column, pat_str) in row.into_iter().enumerate() {
281 write!(f, "{:1$}", pat_str, column_widths[column])?;
285 write!(f, "{}\n", br)?;
291 impl<'a, 'tcx> FromIterator<Vec<&'a Pattern<'tcx>>> for Matrix<'a, 'tcx> {
292 fn from_iter<T: IntoIterator<Item=Vec<&'a Pattern<'tcx>>>>(iter: T) -> Self
294 Matrix(iter.into_iter().collect())
298 pub struct MatchCheckCtxt<'a, 'tcx: 'a> {
299 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
300 /// The module in which the match occurs. This is necessary for
301 /// checking inhabited-ness of types because whether a type is (visibly)
302 /// inhabited can depend on whether it was defined in the current module or
303 /// not. eg. `struct Foo { _private: ! }` cannot be seen to be empty
304 /// outside it's module and should not be matchable with an empty match
307 pub pattern_arena: &'a TypedArena<Pattern<'tcx>>,
308 pub byte_array_map: FxHashMap<*const Pattern<'tcx>, Vec<&'a Pattern<'tcx>>>,
311 impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> {
312 pub fn create_and_enter<F, R>(
313 tcx: TyCtxt<'a, 'tcx, 'tcx>,
316 where F: for<'b> FnOnce(MatchCheckCtxt<'b, 'tcx>) -> R
318 let pattern_arena = TypedArena::new();
323 pattern_arena: &pattern_arena,
324 byte_array_map: FxHashMap::default(),
328 // convert a byte-string pattern to a list of u8 patterns.
329 fn lower_byte_str_pattern<'p>(&mut self, pat: &'p Pattern<'tcx>) -> Vec<&'p Pattern<'tcx>>
332 let pattern_arena = &*self.pattern_arena;
334 self.byte_array_map.entry(pat).or_insert_with(|| {
336 box PatternKind::Constant {
339 if let Some(ptr) = const_val.to_ptr() {
340 let is_array_ptr = const_val.ty
342 .and_then(|t| t.ty.builtin_index())
343 .map_or(false, |t| t == tcx.types.u8);
344 assert!(is_array_ptr);
345 let alloc = tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
346 assert_eq!(ptr.offset.bytes(), 0);
347 // FIXME: check length
348 alloc.bytes.iter().map(|b| {
349 &*pattern_arena.alloc(Pattern {
352 kind: box PatternKind::Constant {
353 value: ty::Const::from_bits(
356 ty::ParamEnv::empty().and(tcx.types.u8))
361 bug!("not a byte str: {:?}", const_val)
364 _ => span_bug!(pat.span, "unexpected byte array pattern {:?}", pat)
369 fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool {
370 if self.tcx.features().exhaustive_patterns {
371 self.tcx.is_ty_uninhabited_from(self.module, ty)
377 fn is_non_exhaustive_enum(&self, ty: Ty<'tcx>) -> bool {
379 ty::TyAdt(adt_def, ..) => adt_def.is_enum() && adt_def.is_non_exhaustive(),
384 fn is_local(&self, ty: Ty<'tcx>) -> bool {
386 ty::TyAdt(adt_def, ..) => adt_def.did.is_local(),
391 fn is_variant_uninhabited(&self,
392 variant: &'tcx ty::VariantDef,
393 substs: &'tcx ty::subst::Substs<'tcx>)
396 if self.tcx.features().exhaustive_patterns {
397 self.tcx.is_enum_variant_uninhabited_from(self.module, variant, substs)
404 #[derive(Clone, Debug, PartialEq)]
405 pub enum Constructor<'tcx> {
406 /// The constructor of all patterns that don't vary by constructor,
407 /// e.g. struct patterns and fixed-length arrays.
412 ConstantValue(&'tcx ty::Const<'tcx>),
413 /// Ranges of literal values (`2...5` and `2..5`).
414 ConstantRange(&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>, RangeEnd),
415 /// Array patterns of length n.
419 impl<'tcx> Constructor<'tcx> {
420 fn variant_index_for_adt(&self, adt: &'tcx ty::AdtDef) -> usize {
422 &Variant(vid) => adt.variant_index_with_id(vid),
424 assert!(!adt.is_enum());
427 _ => bug!("bad constructor {:?} for adt {:?}", self, adt)
432 #[derive(Clone, Debug)]
433 pub enum Usefulness<'tcx> {
435 UsefulWithWitness(Vec<Witness<'tcx>>),
439 impl<'tcx> Usefulness<'tcx> {
440 fn is_useful(&self) -> bool {
448 #[derive(Copy, Clone, Debug)]
449 pub enum WitnessPreference {
454 #[derive(Copy, Clone, Debug)]
455 struct PatternContext<'tcx> {
457 max_slice_length: u64,
460 /// A witness of non-exhaustiveness for error reporting, represented
461 /// as a list of patterns (in reverse order of construction) with
462 /// wildcards inside to represent elements that can take any inhabitant
463 /// of the type as a value.
465 /// A witness against a list of patterns should have the same types
466 /// and length as the pattern matched against. Because Rust `match`
467 /// is always against a single pattern, at the end the witness will
468 /// have length 1, but in the middle of the algorithm, it can contain
469 /// multiple patterns.
471 /// For example, if we are constructing a witness for the match against
473 /// struct Pair(Option<(u32, u32)>, bool);
475 /// match (p: Pair) {
476 /// Pair(None, _) => {}
477 /// Pair(_, false) => {}
481 /// We'll perform the following steps:
482 /// 1. Start with an empty witness
483 /// `Witness(vec![])`
484 /// 2. Push a witness `Some(_)` against the `None`
485 /// `Witness(vec![Some(_)])`
486 /// 3. Push a witness `true` against the `false`
487 /// `Witness(vec![Some(_), true])`
488 /// 4. Apply the `Pair` constructor to the witnesses
489 /// `Witness(vec![Pair(Some(_), true)])`
491 /// The final `Pair(Some(_), true)` is then the resulting witness.
492 #[derive(Clone, Debug)]
493 pub struct Witness<'tcx>(Vec<Pattern<'tcx>>);
495 impl<'tcx> Witness<'tcx> {
496 pub fn single_pattern(&self) -> &Pattern<'tcx> {
497 assert_eq!(self.0.len(), 1);
501 fn push_wild_constructor<'a>(
503 cx: &MatchCheckCtxt<'a, 'tcx>,
504 ctor: &Constructor<'tcx>,
508 let sub_pattern_tys = constructor_sub_pattern_tys(cx, ctor, ty);
509 self.0.extend(sub_pattern_tys.into_iter().map(|ty| {
513 kind: box PatternKind::Wild,
516 self.apply_constructor(cx, ctor, ty)
520 /// Constructs a partial witness for a pattern given a list of
521 /// patterns expanded by the specialization step.
523 /// When a pattern P is discovered to be useful, this function is used bottom-up
524 /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
525 /// of values, V, where each value in that set is not covered by any previously
526 /// used patterns and is covered by the pattern P'. Examples:
528 /// left_ty: tuple of 3 elements
529 /// pats: [10, 20, _] => (10, 20, _)
531 /// left_ty: struct X { a: (bool, &'static str), b: usize}
532 /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 }
533 fn apply_constructor<'a>(
535 cx: &MatchCheckCtxt<'a,'tcx>,
536 ctor: &Constructor<'tcx>,
540 let arity = constructor_arity(cx, ctor, ty);
542 let len = self.0.len() as u64;
543 let mut pats = self.0.drain((len - arity) as usize..).rev();
548 let pats = pats.enumerate().map(|(i, p)| {
550 field: Field::new(i),
555 if let ty::TyAdt(adt, substs) = ty.sty {
557 PatternKind::Variant {
560 variant_index: ctor.variant_index_for_adt(adt),
564 PatternKind::Leaf { subpatterns: pats }
567 PatternKind::Leaf { subpatterns: pats }
572 PatternKind::Deref { subpattern: pats.nth(0).unwrap() }
575 ty::TySlice(_) | ty::TyArray(..) => {
577 prefix: pats.collect(),
585 ConstantValue(value) => PatternKind::Constant { value },
586 ConstantRange(lo, hi, end) => PatternKind::Range { lo, hi, end },
587 _ => PatternKind::Wild,
593 self.0.push(Pattern {
603 /// This determines the set of all possible constructors of a pattern matching
604 /// values of type `left_ty`. For vectors, this would normally be an infinite set
605 /// but is instead bounded by the maximum fixed length of slice patterns in
606 /// the column of patterns being analyzed.
608 /// We make sure to omit constructors that are statically impossible. eg for
609 /// Option<!> we do not include Some(_) in the returned list of constructors.
610 fn all_constructors<'a, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
611 pcx: PatternContext<'tcx>)
612 -> Vec<Constructor<'tcx>>
614 debug!("all_constructors({:?})", pcx.ty);
615 let exhaustive_integer_patterns = cx.tcx.features().exhaustive_integer_patterns;
616 let ctors = match pcx.ty.sty {
618 [true, false].iter().map(|&b| {
619 ConstantValue(ty::Const::from_bool(cx.tcx, b))
622 ty::TyArray(ref sub_ty, len) if len.assert_usize(cx.tcx).is_some() => {
623 let len = len.unwrap_usize(cx.tcx);
624 if len != 0 && cx.is_uninhabited(sub_ty) {
630 // Treat arrays of a constant but unknown length like slices.
631 ty::TyArray(ref sub_ty, _) |
632 ty::TySlice(ref sub_ty) => {
633 if cx.is_uninhabited(sub_ty) {
636 (0..pcx.max_slice_length+1).map(|length| Slice(length)).collect()
639 ty::TyAdt(def, substs) if def.is_enum() => {
641 .filter(|v| !cx.is_variant_uninhabited(v, substs))
642 .map(|v| Variant(v.did))
645 ty::TyChar if exhaustive_integer_patterns => {
646 let endpoint = |c: char| {
647 let ty = ty::ParamEnv::empty().and(cx.tcx.types.char);
648 ty::Const::from_bits(cx.tcx, c as u128, ty)
651 // The valid Unicode Scalar Value ranges.
652 ConstantRange(endpoint('\u{0000}'), endpoint('\u{D7FF}'), RangeEnd::Included),
653 ConstantRange(endpoint('\u{E000}'), endpoint('\u{10FFFF}'), RangeEnd::Included),
656 ty::TyInt(ity) if exhaustive_integer_patterns => {
657 // FIXME(49937): refactor these bit manipulations into interpret.
658 let bits = Integer::from_attr(cx.tcx, SignedInt(ity)).size().bits() as u128;
659 let min = 1u128 << (bits - 1);
660 let max = (1u128 << (bits - 1)) - 1;
661 let ty = ty::ParamEnv::empty().and(pcx.ty);
662 vec![ConstantRange(ty::Const::from_bits(cx.tcx, min as u128, ty),
663 ty::Const::from_bits(cx.tcx, max as u128, ty),
666 ty::TyUint(uty) if exhaustive_integer_patterns => {
667 // FIXME(49937): refactor these bit manipulations into interpret.
668 let bits = Integer::from_attr(cx.tcx, UnsignedInt(uty)).size().bits() as u128;
669 let max = !0u128 >> (128 - bits);
670 let ty = ty::ParamEnv::empty().and(pcx.ty);
671 vec![ConstantRange(ty::Const::from_bits(cx.tcx, 0, ty),
672 ty::Const::from_bits(cx.tcx, max, ty),
676 if cx.is_uninhabited(pcx.ty) {
686 fn max_slice_length<'p, 'a: 'p, 'tcx: 'a, I>(
687 cx: &mut MatchCheckCtxt<'a, 'tcx>,
689 where I: Iterator<Item=&'p Pattern<'tcx>>
691 // The exhaustiveness-checking paper does not include any details on
692 // checking variable-length slice patterns. However, they are matched
693 // by an infinite collection of fixed-length array patterns.
695 // Checking the infinite set directly would take an infinite amount
696 // of time. However, it turns out that for each finite set of
697 // patterns `P`, all sufficiently large array lengths are equivalent:
699 // Each slice `s` with a "sufficiently-large" length `l ≥ L` that applies
700 // to exactly the subset `Pₜ` of `P` can be transformed to a slice
701 // `sₘ` for each sufficiently-large length `m` that applies to exactly
702 // the same subset of `P`.
704 // Because of that, each witness for reachability-checking from one
705 // of the sufficiently-large lengths can be transformed to an
706 // equally-valid witness from any other length, so we only have
707 // to check slice lengths from the "minimal sufficiently-large length"
710 // Note that the fact that there is a *single* `sₘ` for each `m`
711 // not depending on the specific pattern in `P` is important: if
712 // you look at the pair of patterns
715 // Then any slice of length ≥1 that matches one of these two
716 // patterns can be trivially turned to a slice of any
717 // other length ≥1 that matches them and vice-versa - for
718 // but the slice from length 2 `[false, true]` that matches neither
719 // of these patterns can't be turned to a slice from length 1 that
720 // matches neither of these patterns, so we have to consider
721 // slices from length 2 there.
723 // Now, to see that that length exists and find it, observe that slice
724 // patterns are either "fixed-length" patterns (`[_, _, _]`) or
725 // "variable-length" patterns (`[_, .., _]`).
727 // For fixed-length patterns, all slices with lengths *longer* than
728 // the pattern's length have the same outcome (of not matching), so
729 // as long as `L` is greater than the pattern's length we can pick
730 // any `sₘ` from that length and get the same result.
732 // For variable-length patterns, the situation is more complicated,
733 // because as seen above the precise value of `sₘ` matters.
735 // However, for each variable-length pattern `p` with a prefix of length
736 // `plₚ` and suffix of length `slₚ`, only the first `plₚ` and the last
737 // `slₚ` elements are examined.
739 // Therefore, as long as `L` is positive (to avoid concerns about empty
740 // types), all elements after the maximum prefix length and before
741 // the maximum suffix length are not examined by any variable-length
742 // pattern, and therefore can be added/removed without affecting
743 // them - creating equivalent patterns from any sufficiently-large
746 // Of course, if fixed-length patterns exist, we must be sure
747 // that our length is large enough to miss them all, so
748 // we can pick `L = max(FIXED_LEN+1 ∪ {max(PREFIX_LEN) + max(SUFFIX_LEN)})`
750 // for example, with the above pair of patterns, all elements
751 // but the first and last can be added/removed, so any
752 // witness of length ≥2 (say, `[false, false, true]`) can be
753 // turned to a witness from any other length ≥2.
755 let mut max_prefix_len = 0;
756 let mut max_suffix_len = 0;
757 let mut max_fixed_len = 0;
759 for row in patterns {
761 PatternKind::Constant { value } => {
762 if let Some(ptr) = value.to_ptr() {
763 let is_array_ptr = value.ty
765 .and_then(|t| t.ty.builtin_index())
766 .map_or(false, |t| t == cx.tcx.types.u8);
768 let alloc = cx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
769 max_fixed_len = cmp::max(max_fixed_len, alloc.bytes.len() as u64);
773 PatternKind::Slice { ref prefix, slice: None, ref suffix } => {
774 let fixed_len = prefix.len() as u64 + suffix.len() as u64;
775 max_fixed_len = cmp::max(max_fixed_len, fixed_len);
777 PatternKind::Slice { ref prefix, slice: Some(_), ref suffix } => {
778 max_prefix_len = cmp::max(max_prefix_len, prefix.len() as u64);
779 max_suffix_len = cmp::max(max_suffix_len, suffix.len() as u64);
785 cmp::max(max_fixed_len + 1, max_prefix_len + max_suffix_len)
788 /// An inclusive interval, used for precise integer exhaustiveness checking.
789 /// `IntRange`s always store a contiguous range. This means that values are
790 /// encoded such that `0` encodes the minimum value for the integer,
791 /// regardless of the signedness.
792 /// For example, the pattern `-128...127i8` is encoded as `0..=255`.
793 /// This makes comparisons and arithmetic on interval endpoints much more
794 /// straightforward. See `signed_bias` for details.
795 struct IntRange<'tcx> {
796 pub range: RangeInclusive<u128>,
800 impl<'tcx> IntRange<'tcx> {
801 fn from_ctor(tcx: TyCtxt<'_, 'tcx, 'tcx>,
802 ctor: &Constructor<'tcx>)
803 -> Option<IntRange<'tcx>> {
805 ConstantRange(lo, hi, end) => {
806 assert_eq!(lo.ty, hi.ty);
808 let env_ty = ty::ParamEnv::empty().and(ty);
809 if let Some(lo) = lo.assert_bits(tcx, env_ty) {
810 if let Some(hi) = hi.assert_bits(tcx, env_ty) {
811 // Perform a shift if the underlying types are signed,
812 // which makes the interval arithmetic simpler.
813 let bias = IntRange::signed_bias(tcx, ty);
814 let (lo, hi) = (lo ^ bias, hi ^ bias);
815 // Make sure the interval is well-formed.
816 return if lo > hi || lo == hi && *end == RangeEnd::Excluded {
819 let offset = (*end == RangeEnd::Excluded) as u128;
820 Some(IntRange { range: lo..=(hi - offset), ty })
826 ConstantValue(val) => {
828 if let Some(val) = val.assert_bits(tcx, ty::ParamEnv::empty().and(ty)) {
829 let bias = IntRange::signed_bias(tcx, ty);
830 let val = val ^ bias;
831 Some(IntRange { range: val..=val, ty })
836 Single | Variant(_) | Slice(_) => {
842 fn from_pat(tcx: TyCtxt<'_, 'tcx, 'tcx>,
844 -> Option<IntRange<'tcx>> {
845 Self::from_ctor(tcx, &match pat.kind {
846 box PatternKind::Constant { value } => ConstantValue(value),
847 box PatternKind::Range { lo, hi, end } => ConstantRange(lo, hi, end),
852 // The return value of `signed_bias` should be XORed with an endpoint to encode/decode it.
853 fn signed_bias(tcx: TyCtxt<'_, 'tcx, 'tcx>, ty: Ty<'tcx>) -> u128 {
856 let bits = Integer::from_attr(tcx, SignedInt(ity)).size().bits() as u128;
863 /// Convert a `RangeInclusive` to a `ConstantValue` or inclusive `ConstantRange`.
865 tcx: TyCtxt<'_, 'tcx, 'tcx>,
867 r: RangeInclusive<u128>,
868 ) -> Constructor<'tcx> {
869 let bias = IntRange::signed_bias(tcx, ty);
870 let ty = ty::ParamEnv::empty().and(ty);
871 let (lo, hi) = r.into_inner();
873 ConstantValue(ty::Const::from_bits(tcx, lo ^ bias, ty))
875 ConstantRange(ty::Const::from_bits(tcx, lo ^ bias, ty),
876 ty::Const::from_bits(tcx, hi ^ bias, ty),
881 /// Given an `IntRange` corresponding to a pattern in a `match` and a collection of
882 /// ranges corresponding to the domain of values of a type (say, an integer), return
883 /// a new collection of ranges corresponding to the original ranges minus the ranges
884 /// covered by the `IntRange`.
885 fn subtract_from(self,
886 tcx: TyCtxt<'_, 'tcx, 'tcx>,
887 ranges: Vec<Constructor<'tcx>>)
888 -> Vec<Constructor<'tcx>> {
889 let ranges = ranges.into_iter().filter_map(|r| {
890 IntRange::from_ctor(tcx, &r).map(|i| i.range)
892 let mut remaining_ranges = vec![];
894 let (lo, hi) = self.range.into_inner();
895 for subrange in ranges {
896 let (subrange_lo, subrange_hi) = subrange.into_inner();
897 if lo > subrange_hi || subrange_lo > hi {
898 // The pattern doesn't intersect with the subrange at all,
899 // so the subrange remains untouched.
900 remaining_ranges.push(Self::range_to_ctor(tcx, ty, subrange_lo..=subrange_hi));
902 if lo > subrange_lo {
903 // The pattern intersects an upper section of the
904 // subrange, so a lower section will remain.
905 remaining_ranges.push(Self::range_to_ctor(tcx, ty, subrange_lo..=(lo - 1)));
907 if hi < subrange_hi {
908 // The pattern intersects a lower section of the
909 // subrange, so an upper section will remain.
910 remaining_ranges.push(Self::range_to_ctor(tcx, ty, (hi + 1)..=subrange_hi));
917 fn intersection(&self, other: &Self) -> Option<Self> {
919 let (lo, hi) = (*self.range.start(), *self.range.end());
920 let (other_lo, other_hi) = (*other.range.start(), *other.range.end());
921 if lo <= other_hi && other_lo <= hi {
922 Some(IntRange { range: max(lo, other_lo)..=min(hi, other_hi), ty })
929 /// Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
930 /// The algorithm from the paper has been modified to correctly handle empty
931 /// types. The changes are:
932 /// (0) We don't exit early if the pattern matrix has zero rows. We just
933 /// continue to recurse over columns.
934 /// (1) all_constructors will only return constructors that are statically
935 /// possible. eg. it will only return Ok for Result<T, !>
937 /// This finds whether a (row) vector `v` of patterns is 'useful' in relation
938 /// to a set of such vectors `m` - this is defined as there being a set of
939 /// inputs that will match `v` but not any of the sets in `m`.
941 /// All the patterns at each column of the `matrix ++ v` matrix must
942 /// have the same type, except that wildcard (PatternKind::Wild) patterns
943 /// with type TyErr are also allowed, even if the "type of the column"
944 /// is not TyErr. That is used to represent private fields, as using their
945 /// real type would assert that they are inhabited.
947 /// This is used both for reachability checking (if a pattern isn't useful in
948 /// relation to preceding patterns, it is not reachable) and exhaustiveness
949 /// checking (if a wildcard pattern is useful in relation to a matrix, the
950 /// matrix isn't exhaustive).
951 pub fn is_useful<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
952 matrix: &Matrix<'p, 'tcx>,
953 v: &[&'p Pattern<'tcx>],
954 witness: WitnessPreference)
955 -> Usefulness<'tcx> {
956 let &Matrix(ref rows) = matrix;
957 debug!("is_useful({:#?}, {:#?})", matrix, v);
959 // The base case. We are pattern-matching on () and the return value is
960 // based on whether our matrix has a row or not.
961 // NOTE: This could potentially be optimized by checking rows.is_empty()
962 // first and then, if v is non-empty, the return value is based on whether
963 // the type of the tuple we're checking is inhabited or not.
965 return if rows.is_empty() {
967 ConstructWitness => UsefulWithWitness(vec![Witness(vec![])]),
968 LeaveOutWitness => Useful,
975 assert!(rows.iter().all(|r| r.len() == v.len()));
977 let pcx = PatternContext {
978 // TyErr is used to represent the type of wildcard patterns matching
979 // against inaccessible (private) fields of structs, so that we won't
980 // be able to observe whether the types of the struct's fields are
983 // If the field is truly inaccessible, then all the patterns
984 // matching against it must be wildcard patterns, so its type
987 // However, if we are matching against non-wildcard patterns, we
988 // need to know the real type of the field so we can specialize
989 // against it. This primarily occurs through constants - they
990 // can include contents for fields that are inaccessible at the
991 // location of the match. In that case, the field's type is
992 // inhabited - by the constant - so we can just use it.
994 // FIXME: this might lead to "unstable" behavior with macro hygiene
995 // introducing uninhabited patterns for inaccessible fields. We
996 // need to figure out how to model that.
997 ty: rows.iter().map(|r| r[0].ty).find(|ty| !ty.references_error()).unwrap_or(v[0].ty),
998 max_slice_length: max_slice_length(cx, rows.iter().map(|r| r[0]).chain(Some(v[0])))
1001 debug!("is_useful_expand_first_col: pcx={:#?}, expanding {:#?}", pcx, v[0]);
1003 if let Some(constructors) = pat_constructors(cx, v[0], pcx) {
1004 debug!("is_useful - expanding constructors: {:#?}", constructors);
1005 split_grouped_constructors(cx.tcx, constructors, matrix, v, pcx.ty).into_iter().map(|c|
1006 is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness)
1007 ).find(|result| result.is_useful()).unwrap_or(NotUseful)
1009 debug!("is_useful - expanding wildcard");
1011 let used_ctors: Vec<Constructor> = rows.iter().flat_map(|row| {
1012 pat_constructors(cx, row[0], pcx).unwrap_or(vec![])
1014 debug!("used_ctors = {:#?}", used_ctors);
1015 // `all_ctors` are all the constructors for the given type, which
1016 // should all be represented (or caught with the wild pattern `_`).
1017 let all_ctors = all_constructors(cx, pcx);
1018 debug!("all_ctors = {:#?}", all_ctors);
1020 // `missing_ctors` are those that should have appeared
1021 // as patterns in the `match` expression, but did not.
1022 let mut missing_ctors = vec![];
1023 for req_ctor in &all_ctors {
1024 let mut refined_ctors = vec![req_ctor.clone()];
1025 for used_ctor in &used_ctors {
1026 if used_ctor == req_ctor {
1027 // If a constructor appears in a `match` arm, we can
1028 // eliminate it straight away.
1029 refined_ctors = vec![]
1030 } else if cx.tcx.features().exhaustive_integer_patterns {
1031 if let Some(interval) = IntRange::from_ctor(cx.tcx, used_ctor) {
1032 // Refine the required constructors for the type by subtracting
1033 // the range defined by the current constructor pattern.
1034 refined_ctors = interval.subtract_from(cx.tcx, refined_ctors);
1038 // If the constructor patterns that have been considered so far
1039 // already cover the entire range of values, then we the
1040 // constructor is not missing, and we can move on to the next one.
1041 if refined_ctors.is_empty() {
1045 // If a constructor has not been matched, then it is missing.
1046 // We add `refined_ctors` instead of `req_ctor`, because then we can
1047 // provide more detailed error information about precisely which
1048 // ranges have been omitted.
1049 missing_ctors.extend(refined_ctors);
1052 // `missing_ctors` is the set of constructors from the same type as the
1053 // first column of `matrix` that are matched only by wildcard patterns
1054 // from the first column.
1056 // Therefore, if there is some pattern that is unmatched by `matrix`,
1057 // it will still be unmatched if the first constructor is replaced by
1058 // any of the constructors in `missing_ctors`
1060 // However, if our scrutinee is *privately* an empty enum, we
1061 // must treat it as though it had an "unknown" constructor (in
1062 // that case, all other patterns obviously can't be variants)
1063 // to avoid exposing its emptyness. See the `match_privately_empty`
1064 // test for details.
1066 // FIXME: currently the only way I know of something can
1067 // be a privately-empty enum is when the exhaustive_patterns
1068 // feature flag is not present, so this is only
1069 // needed for that case.
1071 let is_privately_empty =
1072 all_ctors.is_empty() && !cx.is_uninhabited(pcx.ty);
1073 let is_declared_nonexhaustive =
1074 cx.is_non_exhaustive_enum(pcx.ty) && !cx.is_local(pcx.ty);
1075 debug!("missing_ctors={:#?} is_privately_empty={:#?} is_declared_nonexhaustive={:#?}",
1076 missing_ctors, is_privately_empty, is_declared_nonexhaustive);
1078 // For privately empty and non-exhaustive enums, we work as if there were an "extra"
1079 // `_` constructor for the type, so we can never match over all constructors.
1080 let is_non_exhaustive = is_privately_empty || is_declared_nonexhaustive;
1082 if missing_ctors.is_empty() && !is_non_exhaustive {
1083 split_grouped_constructors(cx.tcx, all_ctors, matrix, v, pcx.ty).into_iter().map(|c| {
1084 is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness)
1085 }).find(|result| result.is_useful()).unwrap_or(NotUseful)
1087 let matrix = rows.iter().filter_map(|r| {
1088 if r[0].is_wildcard() {
1089 Some(r[1..].to_vec())
1094 match is_useful(cx, &matrix, &v[1..], witness) {
1095 UsefulWithWitness(pats) => {
1097 // In this case, there's at least one "free"
1098 // constructor that is only matched against by
1099 // wildcard patterns.
1101 // There are 2 ways we can report a witness here.
1102 // Commonly, we can report all the "free"
1103 // constructors as witnesses, e.g. if we have:
1106 // enum Direction { N, S, E, W }
1107 // let Direction::N = ...;
1110 // we can report 3 witnesses: `S`, `E`, and `W`.
1112 // However, there are 2 cases where we don't want
1113 // to do this and instead report a single `_` witness:
1115 // 1) If the user is matching against a non-exhaustive
1116 // enum, there is no point in enumerating all possible
1117 // variants, because the user can't actually match
1118 // against them himself, e.g. in an example like:
1120 // let err: io::ErrorKind = ...;
1122 // io::ErrorKind::NotFound => {},
1125 // we don't want to show every possible IO error,
1126 // but instead have `_` as the witness (this is
1127 // actually *required* if the user specified *all*
1128 // IO errors, but is probably what we want in every
1131 // 2) If the user didn't actually specify a constructor
1132 // in this arm, e.g. in
1134 // let x: (Direction, Direction, bool) = ...;
1135 // let (_, _, false) = x;
1137 // we don't want to show all 16 possible witnesses
1138 // `(<direction-1>, <direction-2>, true)` - we are
1139 // satisfied with `(_, _, true)`. In this case,
1140 // `used_ctors` is empty.
1141 let new_witnesses = if is_non_exhaustive || used_ctors.is_empty() {
1142 // All constructors are unused. Add wild patterns
1143 // rather than each individual constructor.
1144 pats.into_iter().map(|mut witness| {
1145 witness.0.push(Pattern {
1148 kind: box PatternKind::Wild,
1153 pats.into_iter().flat_map(|witness| {
1154 missing_ctors.iter().map(move |ctor| {
1155 // Extends the witness with a "wild" version of this
1156 // constructor, that matches everything that can be built with
1157 // it. For example, if `ctor` is a `Constructor::Variant` for
1158 // `Option::Some`, this pushes the witness for `Some(_)`.
1159 witness.clone().push_wild_constructor(cx, ctor, pcx.ty)
1163 UsefulWithWitness(new_witnesses)
1171 /// A shorthand for the `U(S(c, P), S(c, q))` operation from the paper. I.e. `is_useful` applied
1172 /// to the specialised version of both the pattern matrix `P` and the new pattern `q`.
1173 fn is_useful_specialized<'p, 'a:'p, 'tcx: 'a>(
1174 cx: &mut MatchCheckCtxt<'a, 'tcx>,
1175 &Matrix(ref m): &Matrix<'p, 'tcx>,
1176 v: &[&'p Pattern<'tcx>],
1177 ctor: Constructor<'tcx>,
1179 witness: WitnessPreference,
1180 ) -> Usefulness<'tcx> {
1181 debug!("is_useful_specialized({:#?}, {:#?}, {:?})", v, ctor, lty);
1182 let sub_pat_tys = constructor_sub_pattern_tys(cx, &ctor, lty);
1183 let wild_patterns_owned: Vec<_> = sub_pat_tys.iter().map(|ty| {
1187 kind: box PatternKind::Wild,
1190 let wild_patterns: Vec<_> = wild_patterns_owned.iter().collect();
1191 let matrix = Matrix(m.iter().flat_map(|r| {
1192 specialize(cx, &r, &ctor, &wild_patterns)
1194 match specialize(cx, v, &ctor, &wild_patterns) {
1195 Some(v) => match is_useful(cx, &matrix, &v, witness) {
1196 UsefulWithWitness(witnesses) => UsefulWithWitness(
1197 witnesses.into_iter()
1198 .map(|witness| witness.apply_constructor(cx, &ctor, lty))
1207 /// Determines the constructors that the given pattern can be specialized to.
1209 /// In most cases, there's only one constructor that a specific pattern
1210 /// represents, such as a specific enum variant or a specific literal value.
1211 /// Slice patterns, however, can match slices of different lengths. For instance,
1212 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
1214 /// Returns `None` in case of a catch-all, which can't be specialized.
1215 fn pat_constructors<'tcx>(cx: &mut MatchCheckCtxt,
1216 pat: &Pattern<'tcx>,
1217 pcx: PatternContext)
1218 -> Option<Vec<Constructor<'tcx>>>
1221 PatternKind::Binding { .. } | PatternKind::Wild => None,
1222 PatternKind::Leaf { .. } | PatternKind::Deref { .. } => Some(vec![Single]),
1223 PatternKind::Variant { adt_def, variant_index, .. } => {
1224 Some(vec![Variant(adt_def.variants[variant_index].did)])
1226 PatternKind::Constant { value } => Some(vec![ConstantValue(value)]),
1227 PatternKind::Range { lo, hi, end } => Some(vec![ConstantRange(lo, hi, end)]),
1228 PatternKind::Array { .. } => match pcx.ty.sty {
1229 ty::TyArray(_, length) => Some(vec![
1230 Slice(length.unwrap_usize(cx.tcx))
1232 _ => span_bug!(pat.span, "bad ty {:?} for array pattern", pcx.ty)
1234 PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
1235 let pat_len = prefix.len() as u64 + suffix.len() as u64;
1236 if slice.is_some() {
1237 Some((pat_len..pcx.max_slice_length+1).map(Slice).collect())
1239 Some(vec![Slice(pat_len)])
1245 /// This computes the arity of a constructor. The arity of a constructor
1246 /// is how many subpattern patterns of that constructor should be expanded to.
1248 /// For instance, a tuple pattern (_, 42, Some([])) has the arity of 3.
1249 /// A struct pattern's arity is the number of fields it contains, etc.
1250 fn constructor_arity(_cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> u64 {
1251 debug!("constructor_arity({:#?}, {:?})", ctor, ty);
1253 ty::TyTuple(ref fs) => fs.len() as u64,
1254 ty::TySlice(..) | ty::TyArray(..) => match *ctor {
1255 Slice(length) => length,
1256 ConstantValue(_) => 0,
1257 _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
1260 ty::TyAdt(adt, _) => {
1261 adt.variants[ctor.variant_index_for_adt(adt)].fields.len() as u64
1267 /// This computes the types of the sub patterns that a constructor should be
1270 /// For instance, a tuple pattern (43u32, 'a') has sub pattern types [u32, char].
1271 fn constructor_sub_pattern_tys<'a, 'tcx: 'a>(cx: &MatchCheckCtxt<'a, 'tcx>,
1273 ty: Ty<'tcx>) -> Vec<Ty<'tcx>>
1275 debug!("constructor_sub_pattern_tys({:#?}, {:?})", ctor, ty);
1277 ty::TyTuple(ref fs) => fs.into_iter().map(|t| *t).collect(),
1278 ty::TySlice(ty) | ty::TyArray(ty, _) => match *ctor {
1279 Slice(length) => (0..length).map(|_| ty).collect(),
1280 ConstantValue(_) => vec![],
1281 _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
1283 ty::TyRef(_, rty, _) => vec![rty],
1284 ty::TyAdt(adt, substs) => {
1286 // Use T as the sub pattern type of Box<T>.
1287 vec![substs.type_at(0)]
1289 adt.variants[ctor.variant_index_for_adt(adt)].fields.iter().map(|field| {
1290 let is_visible = adt.is_enum()
1291 || field.vis.is_accessible_from(cx.module, cx.tcx);
1293 field.ty(cx.tcx, substs)
1295 // Treat all non-visible fields as TyErr. They
1296 // can't appear in any other pattern from
1297 // this match (because they are private),
1298 // so their type does not matter - but
1299 // we don't want to know they are
1310 fn slice_pat_covered_by_constructor<'tcx>(
1311 tcx: TyCtxt<'_, 'tcx, '_>,
1314 prefix: &[Pattern<'tcx>],
1315 slice: &Option<Pattern<'tcx>>,
1316 suffix: &[Pattern<'tcx>]
1317 ) -> Result<bool, ErrorReported> {
1318 let data: &[u8] = match *ctor {
1319 ConstantValue(const_val) => {
1320 let val = match const_val.val {
1321 ConstValue::Unevaluated(..) |
1322 ConstValue::ByRef(..) => bug!("unexpected ConstValue: {:?}", const_val),
1323 ConstValue::Scalar(val) | ConstValue::ScalarPair(val, _) => val,
1325 if let Ok(ptr) = val.to_ptr() {
1326 let is_array_ptr = const_val.ty
1327 .builtin_deref(true)
1328 .and_then(|t| t.ty.builtin_index())
1329 .map_or(false, |t| t == tcx.types.u8);
1330 assert!(is_array_ptr);
1331 tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id).bytes.as_ref()
1333 bug!("unexpected non-ptr ConstantValue")
1339 let pat_len = prefix.len() + suffix.len();
1340 if data.len() < pat_len || (slice.is_none() && data.len() > pat_len) {
1345 data[..prefix.len()].iter().zip(prefix).chain(
1346 data[data.len()-suffix.len()..].iter().zip(suffix))
1349 box PatternKind::Constant { value } => {
1350 let b = value.unwrap_bits(tcx, ty::ParamEnv::empty().and(pat.ty));
1351 assert_eq!(b as u8 as u128, b);
1363 // Whether to evaluate a constructor using exhaustive integer matching. This is true if the
1364 // constructor is a range or constant with an integer type.
1365 fn should_treat_range_exhaustively(tcx: TyCtxt<'_, 'tcx, 'tcx>, ctor: &Constructor<'tcx>) -> bool {
1366 if tcx.features().exhaustive_integer_patterns {
1367 if let ConstantValue(value) | ConstantRange(value, _, _) = ctor {
1368 if let ty::TyChar | ty::TyInt(_) | ty::TyUint(_) = value.ty.sty {
1376 /// For exhaustive integer matching, some constructors are grouped within other constructors
1377 /// (namely integer typed values are grouped within ranges). However, when specialising these
1378 /// constructors, we want to be specialising for the underlying constructors (the integers), not
1379 /// the groups (the ranges). Thus we need to split the groups up. Splitting them up naïvely would
1380 /// mean creating a separate constructor for every single value in the range, which is clearly
1381 /// impractical. However, observe that for some ranges of integers, the specialisation will be
1382 /// identical across all values in that range (i.e. there are equivalence classes of ranges of
1383 /// constructors based on their `is_useful_specialised` outcome). These classes are grouped by
1384 /// the patterns that apply to them (both in the matrix `P` and in the new row `p_{m + 1}`). We
1385 /// can split the range whenever the patterns that apply to that range (specifically: the patterns
1386 /// that *intersect* with that range) change.
1387 /// Our solution, therefore, is to split the range constructor into subranges at every single point
1388 /// the group of intersecting patterns changes, which we can compute by converting each pattern to
1389 /// a range and recording its endpoints, then creating subranges between each consecutive pair of
1391 /// And voilà! We're testing precisely those ranges that we need to, without any exhaustive matching
1392 /// on actual integers. The nice thing about this is that the number of subranges is linear in the
1393 /// number of rows in the matrix (i.e. the number of cases in the `match` statement), so we don't
1394 /// need to be worried about matching over gargantuan ranges.
1395 fn split_grouped_constructors<'p, 'a: 'p, 'tcx: 'a>(
1396 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1397 ctors: Vec<Constructor<'tcx>>,
1398 &Matrix(ref m): &Matrix<'p, 'tcx>,
1399 p: &[&'p Pattern<'tcx>],
1401 ) -> Vec<Constructor<'tcx>> {
1404 let mut split_ctors = Vec::with_capacity(ctors.len());
1406 for ctor in ctors.into_iter() {
1408 // For now, only ranges may denote groups of "subconstructors", so we only need to
1409 // special-case constant ranges.
1410 ConstantRange(..) if should_treat_range_exhaustively(tcx, &ctor) => {
1411 // We only care about finding all the subranges within the range of the intersection
1412 // of the new pattern `p_({m + 1},1)` (here `pat`) and the constructor range.
1413 // Anything else is irrelevant, because it is guaranteed to result in `NotUseful`,
1414 // which is the default case anyway, and can be ignored.
1415 let mut ctor_range = IntRange::from_ctor(tcx, &ctor).unwrap();
1416 if let Some(pat_range) = IntRange::from_pat(tcx, pat) {
1417 if let Some(new_range) = ctor_range.intersection(&pat_range) {
1418 ctor_range = new_range;
1420 // If the intersection between `pat` and the constructor is empty, the
1421 // entire range is `NotUseful`.
1426 box PatternKind::Wild => {
1427 // A wild pattern matches the entire range of values,
1428 // so the current values are fine.
1430 // If the pattern is not a value (i.e. a degenerate range), a range or a
1431 // wildcard (which stands for the entire range), then it's guaranteed to
1436 // We're going to collect all the endpoints in the new pattern so we can create
1437 // subranges between them.
1438 // If there's a single point, we need to identify it as belonging
1439 // to a length-1 range, so it can be treated as an individual
1440 // constructor, rather than as an endpoint. To do this, we keep track of which
1441 // endpoint a point corresponds to. Whenever a point corresponds to both a start
1442 // and an end, then we create a unit range for it.
1443 #[derive(PartialEq, Clone, Copy, Debug)]
1449 let mut points = FxHashMap::default();
1450 let add_endpoint = |points: &mut FxHashMap<_, _>, x, endpoint| {
1451 points.entry(x).and_modify(|ex_x| {
1452 if *ex_x != endpoint {
1453 *ex_x = Endpoint::Both
1455 }).or_insert(endpoint);
1457 let add_endpoints = |points: &mut FxHashMap<_, _>, lo, hi| {
1458 // Insert the endpoints, taking care to keep track of to
1459 // which endpoints a point corresponds.
1460 add_endpoint(points, lo, Endpoint::Start);
1461 add_endpoint(points, hi, Endpoint::End);
1463 let (lo, hi) = (*ctor_range.range.start(), *ctor_range.range.end());
1464 add_endpoints(&mut points, lo, hi);
1465 // We're going to iterate through every row pattern, adding endpoints in.
1466 for row in m.iter() {
1467 if let Some(r) = IntRange::from_pat(tcx, row[0]) {
1468 // We're only interested in endpoints that lie (at least partially)
1469 // within the subrange domain.
1470 if let Some(r) = ctor_range.intersection(&r) {
1471 let (r_lo, r_hi) = r.range.into_inner();
1472 add_endpoints(&mut points, r_lo, r_hi);
1477 // The patterns were iterated in an arbitrary order (i.e. in the order the user
1478 // wrote them), so we need to make sure our endpoints are sorted.
1479 let mut points: Vec<(u128, Endpoint)> = points.into_iter().collect();
1480 points.sort_unstable_by_key(|(x, _)| *x);
1481 let mut points = points.into_iter();
1482 let mut a = points.next().unwrap();
1484 // Iterate through pairs of points, adding the subranges to `split_ctors`.
1485 // We have to be careful about the orientation of the points as endpoints, to make
1486 // sure we're enumerating precisely the correct ranges. Too few and the matching is
1487 // actually incorrect. Too many and our diagnostics are poorer. This involves some
1489 while let Some(b) = points.next() {
1491 if let Endpoint::Both = a.1 {
1492 split_ctors.push(IntRange::range_to_ctor(tcx, ty, a.0..=a.0));
1495 Endpoint::Start => a.0,
1496 Endpoint::End | Endpoint::Both => a.0 + 1,
1499 Endpoint::Start | Endpoint::Both => b.0 - 1,
1500 Endpoint::End => b.0,
1502 // In some cases, we won't need an intermediate range between two ranges
1503 // lie immediately adjacent to one another.
1505 split_ctors.push(IntRange::range_to_ctor(tcx, ty, c..=d));
1511 // Any other constructor can be used unchanged.
1512 _ => split_ctors.push(ctor),
1519 /// Check whether there exists any shared value in either `ctor` or `pat` by intersecting them.
1520 fn constructor_intersects_pattern<'p, 'a: 'p, 'tcx: 'a>(
1521 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1522 ctor: &Constructor<'tcx>,
1523 pat: &'p Pattern<'tcx>,
1524 ) -> Option<Vec<&'p Pattern<'tcx>>> {
1525 if should_treat_range_exhaustively(tcx, ctor) {
1526 match (IntRange::from_ctor(tcx, ctor), IntRange::from_pat(tcx, pat)) {
1527 (Some(ctor), Some(pat)) => ctor.intersection(&pat).map(|_| vec![]),
1531 // Fallback for non-ranges and ranges that involve floating-point numbers, which are not
1532 // conveniently handled by `IntRange`. For these cases, the constructor may not be a range
1533 // so intersection actually devolves into being covered by the pattern.
1534 match constructor_covered_by_range(tcx, ctor, pat) {
1535 Ok(true) => Some(vec![]),
1536 Ok(false) | Err(ErrorReported) => None,
1541 fn constructor_covered_by_range<'a, 'tcx>(
1542 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1543 ctor: &Constructor<'tcx>,
1544 pat: &Pattern<'tcx>,
1545 ) -> Result<bool, ErrorReported> {
1546 let (from, to, end, ty) = match pat.kind {
1547 box PatternKind::Constant { value } => (value, value, RangeEnd::Included, value.ty),
1548 box PatternKind::Range { lo, hi, end } => (lo, hi, end, lo.ty),
1549 _ => bug!("`constructor_covered_by_range` called with {:?}", pat),
1551 trace!("constructor_covered_by_range {:#?}, {:#?}, {:#?}, {}", ctor, from, to, ty);
1552 let cmp_from = |c_from| compare_const_vals(tcx, c_from, from, ty::ParamEnv::empty().and(ty))
1553 .map(|res| res != Ordering::Less);
1554 let cmp_to = |c_to| compare_const_vals(tcx, c_to, to, ty::ParamEnv::empty().and(ty));
1555 macro_rules! some_or_ok {
1559 None => return Ok(false), // not char or int
1564 ConstantValue(value) => {
1565 let to = some_or_ok!(cmp_to(value));
1566 let end = (to == Ordering::Less) ||
1567 (end == RangeEnd::Included && to == Ordering::Equal);
1568 Ok(some_or_ok!(cmp_from(value)) && end)
1570 ConstantRange(from, to, RangeEnd::Included) => {
1571 let to = some_or_ok!(cmp_to(to));
1572 let end = (to == Ordering::Less) ||
1573 (end == RangeEnd::Included && to == Ordering::Equal);
1574 Ok(some_or_ok!(cmp_from(from)) && end)
1576 ConstantRange(from, to, RangeEnd::Excluded) => {
1577 let to = some_or_ok!(cmp_to(to));
1578 let end = (to == Ordering::Less) ||
1579 (end == RangeEnd::Excluded && to == Ordering::Equal);
1580 Ok(some_or_ok!(cmp_from(from)) && end)
1587 fn patterns_for_variant<'p, 'a: 'p, 'tcx: 'a>(
1588 subpatterns: &'p [FieldPattern<'tcx>],
1589 wild_patterns: &[&'p Pattern<'tcx>])
1590 -> Vec<&'p Pattern<'tcx>>
1592 let mut result = wild_patterns.to_owned();
1594 for subpat in subpatterns {
1595 result[subpat.field.index()] = &subpat.pattern;
1598 debug!("patterns_for_variant({:#?}, {:#?}) = {:#?}", subpatterns, wild_patterns, result);
1602 /// This is the main specialization step. It expands the first pattern in the given row
1603 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
1604 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
1606 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
1607 /// different patterns.
1608 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
1609 /// fields filled with wild patterns.
1610 fn specialize<'p, 'a: 'p, 'tcx: 'a>(
1611 cx: &mut MatchCheckCtxt<'a, 'tcx>,
1612 r: &[&'p Pattern<'tcx>],
1613 constructor: &Constructor<'tcx>,
1614 wild_patterns: &[&'p Pattern<'tcx>],
1615 ) -> Option<Vec<&'p Pattern<'tcx>>> {
1618 let head: Option<Vec<&Pattern>> = match *pat.kind {
1619 PatternKind::Binding { .. } | PatternKind::Wild => {
1620 Some(wild_patterns.to_owned())
1623 PatternKind::Variant { adt_def, variant_index, ref subpatterns, .. } => {
1624 let ref variant = adt_def.variants[variant_index];
1625 if *constructor == Variant(variant.did) {
1626 Some(patterns_for_variant(subpatterns, wild_patterns))
1632 PatternKind::Leaf { ref subpatterns } => {
1633 Some(patterns_for_variant(subpatterns, wild_patterns))
1636 PatternKind::Deref { ref subpattern } => {
1637 Some(vec![subpattern])
1640 PatternKind::Constant { value } => {
1641 match *constructor {
1643 if let Some(ptr) = value.to_ptr() {
1644 let is_array_ptr = value.ty
1645 .builtin_deref(true)
1646 .and_then(|t| t.ty.builtin_index())
1647 .map_or(false, |t| t == cx.tcx.types.u8);
1648 assert!(is_array_ptr);
1649 let data_len = cx.tcx
1652 .unwrap_memory(ptr.alloc_id)
1655 if wild_patterns.len() == data_len {
1656 Some(cx.lower_byte_str_pattern(pat))
1662 "unexpected const-val {:?} with ctor {:?}", value, constructor)
1666 // If the constructor is a single value, we add a row to the specialised matrix
1667 // if the pattern is equal to the constructor. If the constructor is a range of
1668 // values, we add a row to the specialised matrix if the pattern is contained
1669 // within the constructor. These two cases (for a single value pattern) can be
1670 // treated as intersection.
1671 constructor_intersects_pattern(cx.tcx, constructor, pat)
1676 PatternKind::Range { .. } => {
1677 // If the constructor is a single value, we add a row to the specialised matrix if the
1678 // pattern contains the constructor. If the constructor is a range of values, we add a
1679 // row to the specialised matrix if there exists any value that lies both within the
1680 // pattern and the constructor. These two cases reduce to intersection.
1681 constructor_intersects_pattern(cx.tcx, constructor, pat)
1684 PatternKind::Array { ref prefix, ref slice, ref suffix } |
1685 PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
1686 match *constructor {
1688 let pat_len = prefix.len() + suffix.len();
1689 if let Some(slice_count) = wild_patterns.len().checked_sub(pat_len) {
1690 if slice_count == 0 || slice.is_some() {
1691 Some(prefix.iter().chain(
1692 wild_patterns.iter().map(|p| *p)
1695 .chain(suffix.iter())
1704 ConstantValue(..) => {
1705 match slice_pat_covered_by_constructor(
1706 cx.tcx, pat.span, constructor, prefix, slice, suffix
1708 Ok(true) => Some(vec![]),
1710 Err(ErrorReported) => None
1713 _ => span_bug!(pat.span,
1714 "unexpected ctor {:?} for slice pat", constructor)
1718 debug!("specialize({:#?}, {:#?}) = {:#?}", r[0], wild_patterns, head);
1720 head.map(|mut head| {
1721 head.extend_from_slice(&r[1 ..]);