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.
63 /// It is computed as follows. For each row `p_i` of P, we have four cases:
64 /// 1.1. `p_(i,1)= c(r_1, .., r_a)`. Then `S(c, P)` has a corresponding row:
65 /// r_1, .., r_a, p_(i,2), .., p_(i,n)
66 /// 1.2. `p_(i,1) = c'(r_1, .., r_a')` where `c ≠ c'`. Then `S(c, P)` has no
67 /// corresponding row.
68 /// 1.3. `p_(i,1) = _`. Then `S(c, P)` has a corresponding row:
69 /// _, .., _, p_(i,2), .., p_(i,n)
70 /// 1.4. `p_(i,1) = r_1 | r_2`. Then `S(c, P)` has corresponding rows inlined from:
71 /// S(c, (r_1, p_(i,2), .., p_(i,n)))
72 /// S(c, (r_2, p_(i,2), .., p_(i,n)))
74 /// 2. `D(P)` is a "default matrix". This is used when we know there are missing
75 /// constructor cases, but there might be existing wildcard patterns, so to check the
76 /// usefulness of the matrix, we have to check all its *other* components.
78 /// It is computed as follows. For each row `p_i` of P, we have three cases:
79 /// 1.1. `p_(i,1)= c(r_1, .., r_a)`. Then `D(P)` has no corresponding row.
80 /// 1.2. `p_(i,1) = _`. Then `D(P)` has a corresponding row:
81 /// p_(i,2), .., p_(i,n)
82 /// 1.3. `p_(i,1) = r_1 | r_2`. Then `D(P)` has corresponding rows inlined from:
83 /// D((r_1, p_(i,2), .., p_(i,n)))
84 /// D((r_2, p_(i,2), .., p_(i,n)))
86 /// The algorithm for computing `U`
87 /// -------------------------------
88 /// The algorithm is inductive (on the number of columns: i.e. components of tuple patterns).
89 /// That means we're going to check the components from left-to-right, so the algorithm
90 /// operates principally on the first component of the matrix and new pattern `p_{m + 1}`.
92 /// Base case. (`n = 0`, i.e. an empty tuple pattern)
93 /// - If `P` already contains an empty pattern (i.e. if the number of patterns `m > 0`),
94 /// then `U(P, p_{m + 1})` is false.
95 /// - Otherwise, `P` must be empty, so `U(P, p_{m + 1})` is true.
97 /// Inductive step. (`n > 0`, i.e. 1 or more tuple pattern components)
98 /// We're going to match on the new pattern, `p_{m + 1}`.
99 /// - If `p_{m + 1} == c(r_1, .., r_a)`, then we have a constructor pattern.
100 /// Thus, the usefulness of `p_{m + 1}` can be reduced to whether it is useful when
101 /// we ignore all the patterns in `P` that involve other constructors. This is where
102 /// `S(c, P)` comes in:
103 /// `U(P, p_{m + 1}) := U(S(c, P), S(c, p_{m + 1}))`
104 /// - If `p_{m + 1} == _`, then we have two more cases:
105 /// + All the constructors of the first component of the type exist within
106 /// all the rows (after having expanded OR-patterns). In this case:
107 /// `U(P, p_{m + 1}) := ∨(k ϵ constructors) U(S(k, P), S(k, p_{m + 1}))`
108 /// I.e. the pattern `p_{m + 1}` is only useful when all the constructors are
109 /// present *if* its later components are useful for the respective constructors
110 /// covered by `p_{m + 1}` (usually a single constructor, but all in the case of `_`).
111 /// + Some constructors are not present in the existing rows (after having expanded
112 /// OR-patterns). However, there might be wildcard patterns (`_`) present. Thus, we
113 /// are only really concerned with the other patterns leading with wildcards. This is
114 /// where `D` comes in:
115 /// `U(P, p_{m + 1}) := U(D(P), p_({m + 1},2), .., p_({m + 1},n))`
116 /// - If `p_{m + 1} == r_1 | r_2`, then the usefulness depends on each separately:
117 /// `U(P, p_{m + 1}) := U(P, (r_1, p_({m + 1},2), .., p_({m + 1},n)))
118 /// || U(P, (r_2, p_({m + 1},2), .., p_({m + 1},n)))`
120 /// Modifications to the algorithm
121 /// ------------------------------
122 /// The algorithm in the paper doesn't cover some of the special cases that arise in Rust, for
123 /// example uninhabited types and variable-length slice patterns. These are drawn attention to
124 /// throughout the code below.
126 use self::Constructor::*;
127 use self::Usefulness::*;
128 use self::WitnessPreference::*;
130 use rustc_data_structures::fx::FxHashMap;
131 use rustc_data_structures::indexed_vec::Idx;
133 use super::{FieldPattern, Pattern, PatternKind};
134 use super::{PatternFoldable, PatternFolder, compare_const_vals};
136 use rustc::hir::def_id::DefId;
137 use rustc::hir::RangeEnd;
138 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
139 use rustc::ty::layout::{Integer, IntegerExt};
141 use rustc::mir::Field;
142 use rustc::mir::interpret::ConstValue;
143 use rustc::util::common::ErrorReported;
145 use syntax::attr::{SignedInt, UnsignedInt};
146 use syntax_pos::{Span, DUMMY_SP};
148 use arena::TypedArena;
150 use std::cmp::{self, Ordering};
152 use std::iter::{FromIterator, IntoIterator};
153 use std::ops::RangeInclusive;
155 pub fn expand_pattern<'a, 'tcx>(cx: &MatchCheckCtxt<'a, 'tcx>, pat: Pattern<'tcx>)
158 cx.pattern_arena.alloc(LiteralExpander.fold_pattern(&pat))
161 struct LiteralExpander;
162 impl<'tcx> PatternFolder<'tcx> for LiteralExpander {
163 fn fold_pattern(&mut self, pat: &Pattern<'tcx>) -> Pattern<'tcx> {
164 match (&pat.ty.sty, &*pat.kind) {
165 (&ty::TyRef(_, rty, _), &PatternKind::Constant { ref value }) => {
169 kind: box PatternKind::Deref {
170 subpattern: Pattern {
173 kind: box PatternKind::Constant { value: value.clone() },
178 (_, &PatternKind::Binding { subpattern: Some(ref s), .. }) => {
181 _ => pat.super_fold_with(self)
186 impl<'tcx> Pattern<'tcx> {
187 fn is_wildcard(&self) -> bool {
189 PatternKind::Binding { subpattern: None, .. } | PatternKind::Wild =>
196 pub struct Matrix<'a, 'tcx: 'a>(Vec<Vec<&'a Pattern<'tcx>>>);
198 impl<'a, 'tcx> Matrix<'a, 'tcx> {
199 pub fn empty() -> Self {
203 pub fn push(&mut self, row: Vec<&'a Pattern<'tcx>>) {
208 /// Pretty-printer for matrices of patterns, example:
209 /// ++++++++++++++++++++++++++
211 /// ++++++++++++++++++++++++++
212 /// + true + [First] +
213 /// ++++++++++++++++++++++++++
214 /// + true + [Second(true)] +
215 /// ++++++++++++++++++++++++++
217 /// ++++++++++++++++++++++++++
218 /// + _ + [_, _, ..tail] +
219 /// ++++++++++++++++++++++++++
220 impl<'a, 'tcx> fmt::Debug for Matrix<'a, 'tcx> {
221 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
224 let &Matrix(ref m) = self;
225 let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| {
226 row.iter().map(|pat| format!("{:?}", pat)).collect()
229 let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0);
230 assert!(m.iter().all(|row| row.len() == column_count));
231 let column_widths: Vec<usize> = (0..column_count).map(|col| {
232 pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0)
235 let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1;
236 let br = "+".repeat(total_width);
237 write!(f, "{}\n", br)?;
238 for row in pretty_printed_matrix {
240 for (column, pat_str) in row.into_iter().enumerate() {
242 write!(f, "{:1$}", pat_str, column_widths[column])?;
246 write!(f, "{}\n", br)?;
252 impl<'a, 'tcx> FromIterator<Vec<&'a Pattern<'tcx>>> for Matrix<'a, 'tcx> {
253 fn from_iter<T: IntoIterator<Item=Vec<&'a Pattern<'tcx>>>>(iter: T) -> Self
255 Matrix(iter.into_iter().collect())
259 pub struct MatchCheckCtxt<'a, 'tcx: 'a> {
260 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
261 /// The module in which the match occurs. This is necessary for
262 /// checking inhabited-ness of types because whether a type is (visibly)
263 /// inhabited can depend on whether it was defined in the current module or
264 /// not. eg. `struct Foo { _private: ! }` cannot be seen to be empty
265 /// outside it's module and should not be matchable with an empty match
268 pub pattern_arena: &'a TypedArena<Pattern<'tcx>>,
269 pub byte_array_map: FxHashMap<*const Pattern<'tcx>, Vec<&'a Pattern<'tcx>>>,
272 impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> {
273 pub fn create_and_enter<F, R>(
274 tcx: TyCtxt<'a, 'tcx, 'tcx>,
277 where F: for<'b> FnOnce(MatchCheckCtxt<'b, 'tcx>) -> R
279 let pattern_arena = TypedArena::new();
284 pattern_arena: &pattern_arena,
285 byte_array_map: FxHashMap(),
289 // convert a byte-string pattern to a list of u8 patterns.
290 fn lower_byte_str_pattern<'p>(&mut self, pat: &'p Pattern<'tcx>) -> Vec<&'p Pattern<'tcx>>
293 let pattern_arena = &*self.pattern_arena;
295 self.byte_array_map.entry(pat).or_insert_with(|| {
297 box PatternKind::Constant {
300 if let Some(ptr) = const_val.to_ptr() {
301 let is_array_ptr = const_val.ty
303 .and_then(|t| t.ty.builtin_index())
304 .map_or(false, |t| t == tcx.types.u8);
305 assert!(is_array_ptr);
306 let alloc = tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
307 assert_eq!(ptr.offset.bytes(), 0);
308 // FIXME: check length
309 alloc.bytes.iter().map(|b| {
310 &*pattern_arena.alloc(Pattern {
313 kind: box PatternKind::Constant {
314 value: ty::Const::from_bits(
317 ty::ParamEnv::empty().and(tcx.types.u8))
322 bug!("not a byte str: {:?}", const_val)
325 _ => span_bug!(pat.span, "unexpected byte array pattern {:?}", pat)
330 fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool {
331 if self.tcx.features().exhaustive_patterns {
332 self.tcx.is_ty_uninhabited_from(self.module, ty)
338 fn is_non_exhaustive_enum(&self, ty: Ty<'tcx>) -> bool {
340 ty::TyAdt(adt_def, ..) => adt_def.is_enum() && adt_def.is_non_exhaustive(),
345 fn is_local(&self, ty: Ty<'tcx>) -> bool {
347 ty::TyAdt(adt_def, ..) => adt_def.did.is_local(),
352 fn is_variant_uninhabited(&self,
353 variant: &'tcx ty::VariantDef,
354 substs: &'tcx ty::subst::Substs<'tcx>)
357 if self.tcx.features().exhaustive_patterns {
358 self.tcx.is_enum_variant_uninhabited_from(self.module, variant, substs)
365 #[derive(Clone, Debug, PartialEq)]
366 pub enum Constructor<'tcx> {
367 /// The constructor of all patterns that don't vary by constructor,
368 /// e.g. struct patterns and fixed-length arrays.
373 ConstantValue(&'tcx ty::Const<'tcx>),
374 /// Ranges of literal values (`2...5` and `2..5`).
375 ConstantRange(&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>, RangeEnd),
376 /// Array patterns of length n.
380 impl<'tcx> Constructor<'tcx> {
381 fn variant_index_for_adt(&self, adt: &'tcx ty::AdtDef) -> usize {
383 &Variant(vid) => adt.variant_index_with_id(vid),
385 assert!(!adt.is_enum());
388 _ => bug!("bad constructor {:?} for adt {:?}", self, adt)
393 #[derive(Clone, Debug)]
394 pub enum Usefulness<'tcx> {
396 UsefulWithWitness(Vec<Witness<'tcx>>),
400 impl<'tcx> Usefulness<'tcx> {
401 fn is_useful(&self) -> bool {
409 #[derive(Copy, Clone, Debug)]
410 pub enum WitnessPreference {
415 #[derive(Copy, Clone, Debug)]
416 struct PatternContext<'tcx> {
418 max_slice_length: u64,
421 /// A witness of non-exhaustiveness for error reporting, represented
422 /// as a list of patterns (in reverse order of construction) with
423 /// wildcards inside to represent elements that can take any inhabitant
424 /// of the type as a value.
426 /// A witness against a list of patterns should have the same types
427 /// and length as the pattern matched against. Because Rust `match`
428 /// is always against a single pattern, at the end the witness will
429 /// have length 1, but in the middle of the algorithm, it can contain
430 /// multiple patterns.
432 /// For example, if we are constructing a witness for the match against
434 /// struct Pair(Option<(u32, u32)>, bool);
436 /// match (p: Pair) {
437 /// Pair(None, _) => {}
438 /// Pair(_, false) => {}
442 /// We'll perform the following steps:
443 /// 1. Start with an empty witness
444 /// `Witness(vec![])`
445 /// 2. Push a witness `Some(_)` against the `None`
446 /// `Witness(vec![Some(_)])`
447 /// 3. Push a witness `true` against the `false`
448 /// `Witness(vec![Some(_), true])`
449 /// 4. Apply the `Pair` constructor to the witnesses
450 /// `Witness(vec![Pair(Some(_), true)])`
452 /// The final `Pair(Some(_), true)` is then the resulting witness.
453 #[derive(Clone, Debug)]
454 pub struct Witness<'tcx>(Vec<Pattern<'tcx>>);
456 impl<'tcx> Witness<'tcx> {
457 pub fn single_pattern(&self) -> &Pattern<'tcx> {
458 assert_eq!(self.0.len(), 1);
462 fn push_wild_constructor<'a>(
464 cx: &MatchCheckCtxt<'a, 'tcx>,
465 ctor: &Constructor<'tcx>,
469 let sub_pattern_tys = constructor_sub_pattern_tys(cx, ctor, ty);
470 self.0.extend(sub_pattern_tys.into_iter().map(|ty| {
474 kind: box PatternKind::Wild,
477 self.apply_constructor(cx, ctor, ty)
481 /// Constructs a partial witness for a pattern given a list of
482 /// patterns expanded by the specialization step.
484 /// When a pattern P is discovered to be useful, this function is used bottom-up
485 /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
486 /// of values, V, where each value in that set is not covered by any previously
487 /// used patterns and is covered by the pattern P'. Examples:
489 /// left_ty: tuple of 3 elements
490 /// pats: [10, 20, _] => (10, 20, _)
492 /// left_ty: struct X { a: (bool, &'static str), b: usize}
493 /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 }
494 fn apply_constructor<'a>(
496 cx: &MatchCheckCtxt<'a,'tcx>,
497 ctor: &Constructor<'tcx>,
501 let arity = constructor_arity(cx, ctor, ty);
503 let len = self.0.len() as u64;
504 let mut pats = self.0.drain((len - arity) as usize..).rev();
509 let pats = pats.enumerate().map(|(i, p)| {
511 field: Field::new(i),
516 if let ty::TyAdt(adt, substs) = ty.sty {
518 PatternKind::Variant {
521 variant_index: ctor.variant_index_for_adt(adt),
525 PatternKind::Leaf { subpatterns: pats }
528 PatternKind::Leaf { subpatterns: pats }
533 PatternKind::Deref { subpattern: pats.nth(0).unwrap() }
536 ty::TySlice(_) | ty::TyArray(..) => {
538 prefix: pats.collect(),
546 ConstantValue(value) => PatternKind::Constant { value },
547 ConstantRange(lo, hi, end) => PatternKind::Range { lo, hi, end },
548 _ => PatternKind::Wild,
554 self.0.push(Pattern {
564 /// This determines the set of all possible constructors of a pattern matching
565 /// values of type `left_ty`. For vectors, this would normally be an infinite set
566 /// but is instead bounded by the maximum fixed length of slice patterns in
567 /// the column of patterns being analyzed.
569 /// We make sure to omit constructors that are statically impossible. eg for
570 /// Option<!> we do not include Some(_) in the returned list of constructors.
571 fn all_constructors<'a, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
572 pcx: PatternContext<'tcx>)
573 -> Vec<Constructor<'tcx>>
575 debug!("all_constructors({:?})", pcx.ty);
576 let exhaustive_integer_patterns = cx.tcx.features().exhaustive_integer_patterns;
577 let ctors = match pcx.ty.sty {
579 [true, false].iter().map(|&b| {
580 ConstantValue(ty::Const::from_bool(cx.tcx, b))
583 ty::TyArray(ref sub_ty, len) if len.assert_usize(cx.tcx).is_some() => {
584 let len = len.unwrap_usize(cx.tcx);
585 if len != 0 && cx.is_uninhabited(sub_ty) {
591 // Treat arrays of a constant but unknown length like slices.
592 ty::TyArray(ref sub_ty, _) |
593 ty::TySlice(ref sub_ty) => {
594 if cx.is_uninhabited(sub_ty) {
597 (0..pcx.max_slice_length+1).map(|length| Slice(length)).collect()
600 ty::TyAdt(def, substs) if def.is_enum() => {
602 .filter(|v| !cx.is_variant_uninhabited(v, substs))
603 .map(|v| Variant(v.did))
606 ty::TyChar if exhaustive_integer_patterns => {
607 let endpoint = |c: char| {
608 let ty = ty::ParamEnv::empty().and(cx.tcx.types.char);
609 ty::Const::from_bits(cx.tcx, c as u128, ty)
612 // The valid Unicode Scalar Value ranges.
613 ConstantRange(endpoint('\u{0000}'), endpoint('\u{D7FF}'), RangeEnd::Included),
614 ConstantRange(endpoint('\u{E000}'), endpoint('\u{10FFFF}'), RangeEnd::Included),
617 ty::TyInt(ity) if exhaustive_integer_patterns => {
618 // FIXME(49937): refactor these bit manipulations into interpret.
619 let bits = Integer::from_attr(cx.tcx, SignedInt(ity)).size().bits() as u128;
620 let min = 1u128 << (bits - 1);
621 let max = (1u128 << (bits - 1)) - 1;
622 let ty = ty::ParamEnv::empty().and(pcx.ty);
623 vec![ConstantRange(ty::Const::from_bits(cx.tcx, min as u128, ty),
624 ty::Const::from_bits(cx.tcx, max as u128, ty),
627 ty::TyUint(uty) if exhaustive_integer_patterns => {
628 // FIXME(49937): refactor these bit manipulations into interpret.
629 let bits = Integer::from_attr(cx.tcx, UnsignedInt(uty)).size().bits() as u128;
630 let max = !0u128 >> (128 - bits);
631 let ty = ty::ParamEnv::empty().and(pcx.ty);
632 vec![ConstantRange(ty::Const::from_bits(cx.tcx, 0, ty),
633 ty::Const::from_bits(cx.tcx, max, ty),
637 if cx.is_uninhabited(pcx.ty) {
647 fn max_slice_length<'p, 'a: 'p, 'tcx: 'a, I>(
648 cx: &mut MatchCheckCtxt<'a, 'tcx>,
650 where I: Iterator<Item=&'p Pattern<'tcx>>
652 // The exhaustiveness-checking paper does not include any details on
653 // checking variable-length slice patterns. However, they are matched
654 // by an infinite collection of fixed-length array patterns.
656 // Checking the infinite set directly would take an infinite amount
657 // of time. However, it turns out that for each finite set of
658 // patterns `P`, all sufficiently large array lengths are equivalent:
660 // Each slice `s` with a "sufficiently-large" length `l ≥ L` that applies
661 // to exactly the subset `Pₜ` of `P` can be transformed to a slice
662 // `sₘ` for each sufficiently-large length `m` that applies to exactly
663 // the same subset of `P`.
665 // Because of that, each witness for reachability-checking from one
666 // of the sufficiently-large lengths can be transformed to an
667 // equally-valid witness from any other length, so we only have
668 // to check slice lengths from the "minimal sufficiently-large length"
671 // Note that the fact that there is a *single* `sₘ` for each `m`
672 // not depending on the specific pattern in `P` is important: if
673 // you look at the pair of patterns
676 // Then any slice of length ≥1 that matches one of these two
677 // patterns can be trivially turned to a slice of any
678 // other length ≥1 that matches them and vice-versa - for
679 // but the slice from length 2 `[false, true]` that matches neither
680 // of these patterns can't be turned to a slice from length 1 that
681 // matches neither of these patterns, so we have to consider
682 // slices from length 2 there.
684 // Now, to see that that length exists and find it, observe that slice
685 // patterns are either "fixed-length" patterns (`[_, _, _]`) or
686 // "variable-length" patterns (`[_, .., _]`).
688 // For fixed-length patterns, all slices with lengths *longer* than
689 // the pattern's length have the same outcome (of not matching), so
690 // as long as `L` is greater than the pattern's length we can pick
691 // any `sₘ` from that length and get the same result.
693 // For variable-length patterns, the situation is more complicated,
694 // because as seen above the precise value of `sₘ` matters.
696 // However, for each variable-length pattern `p` with a prefix of length
697 // `plₚ` and suffix of length `slₚ`, only the first `plₚ` and the last
698 // `slₚ` elements are examined.
700 // Therefore, as long as `L` is positive (to avoid concerns about empty
701 // types), all elements after the maximum prefix length and before
702 // the maximum suffix length are not examined by any variable-length
703 // pattern, and therefore can be added/removed without affecting
704 // them - creating equivalent patterns from any sufficiently-large
707 // Of course, if fixed-length patterns exist, we must be sure
708 // that our length is large enough to miss them all, so
709 // we can pick `L = max(FIXED_LEN+1 ∪ {max(PREFIX_LEN) + max(SUFFIX_LEN)})`
711 // for example, with the above pair of patterns, all elements
712 // but the first and last can be added/removed, so any
713 // witness of length ≥2 (say, `[false, false, true]`) can be
714 // turned to a witness from any other length ≥2.
716 let mut max_prefix_len = 0;
717 let mut max_suffix_len = 0;
718 let mut max_fixed_len = 0;
720 for row in patterns {
722 PatternKind::Constant { value } => {
723 if let Some(ptr) = value.to_ptr() {
724 let is_array_ptr = value.ty
726 .and_then(|t| t.ty.builtin_index())
727 .map_or(false, |t| t == cx.tcx.types.u8);
729 let alloc = cx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
730 max_fixed_len = cmp::max(max_fixed_len, alloc.bytes.len() as u64);
734 PatternKind::Slice { ref prefix, slice: None, ref suffix } => {
735 let fixed_len = prefix.len() as u64 + suffix.len() as u64;
736 max_fixed_len = cmp::max(max_fixed_len, fixed_len);
738 PatternKind::Slice { ref prefix, slice: Some(_), ref suffix } => {
739 max_prefix_len = cmp::max(max_prefix_len, prefix.len() as u64);
740 max_suffix_len = cmp::max(max_suffix_len, suffix.len() as u64);
746 cmp::max(max_fixed_len + 1, max_prefix_len + max_suffix_len)
749 /// An inclusive interval, used for precise integer exhaustiveness checking.
750 /// `IntRange`s always store a contiguous range. This means that values are
751 /// encoded such that `0` encodes the minimum value for the integer,
752 /// regardless of the signedness.
753 /// For example, the pattern `-128...127i8` is encoded as `0..=255`.
754 /// This makes comparisons and arithmetic on interval endpoints much more
755 /// straightforward. See `signed_bias` for details.
756 struct IntRange<'tcx> {
757 pub range: RangeInclusive<u128>,
761 impl<'tcx> IntRange<'tcx> {
762 fn from_ctor(tcx: TyCtxt<'_, 'tcx, 'tcx>,
763 ctor: &Constructor<'tcx>)
764 -> Option<IntRange<'tcx>> {
766 ConstantRange(lo, hi, end) => {
767 assert_eq!(lo.ty, hi.ty);
769 let env_ty = ty::ParamEnv::empty().and(ty);
770 if let Some(lo) = lo.assert_bits(tcx, env_ty) {
771 if let Some(hi) = hi.assert_bits(tcx, env_ty) {
772 // Perform a shift if the underlying types are signed,
773 // which makes the interval arithmetic simpler.
774 let bias = IntRange::signed_bias(tcx, ty);
775 let (lo, hi) = (lo ^ bias, hi ^ bias);
776 // Make sure the interval is well-formed.
777 return if lo > hi || lo == hi && *end == RangeEnd::Excluded {
780 let offset = (*end == RangeEnd::Excluded) as u128;
781 Some(IntRange { range: lo..=(hi - offset), ty })
787 ConstantValue(val) => {
789 if let Some(val) = val.assert_bits(tcx, ty::ParamEnv::empty().and(ty)) {
790 let bias = IntRange::signed_bias(tcx, ty);
791 let val = val ^ bias;
792 Some(IntRange { range: val..=val, ty })
797 Single | Variant(_) | Slice(_) => {
803 // The return value of `signed_bias` should be
804 // XORed with an endpoint to encode/decode it.
805 fn signed_bias(tcx: TyCtxt<'_, 'tcx, 'tcx>, ty: Ty<'tcx>) -> u128 {
808 let bits = Integer::from_attr(tcx, SignedInt(ity)).size().bits() as u128;
815 /// Given an `IntRange` corresponding to a pattern in a `match` and a collection of
816 /// ranges corresponding to the domain of values of a type (say, an integer), return
817 /// a new collection of ranges corresponding to the original ranges minus the ranges
818 /// covered by the `IntRange`.
819 fn subtract_from(self,
820 tcx: TyCtxt<'_, 'tcx, 'tcx>,
821 ranges: Vec<Constructor<'tcx>>)
822 -> Vec<Constructor<'tcx>> {
823 let ranges = ranges.into_iter().filter_map(|r| {
824 IntRange::from_ctor(tcx, &r).map(|i| i.range)
826 // Convert a `RangeInclusive` to a `ConstantValue` or inclusive `ConstantRange`.
827 let bias = IntRange::signed_bias(tcx, self.ty);
828 let ty = ty::ParamEnv::empty().and(self.ty);
829 let range_to_constant = |r: RangeInclusive<u128>| {
830 let (lo, hi) = r.into_inner();
832 ConstantValue(ty::Const::from_bits(tcx, lo ^ bias, ty))
834 ConstantRange(ty::Const::from_bits(tcx, lo ^ bias, ty),
835 ty::Const::from_bits(tcx, hi ^ bias, ty),
839 let mut remaining_ranges = vec![];
840 let (lo, hi) = self.range.into_inner();
841 for subrange in ranges {
842 let (subrange_lo, subrange_hi) = subrange.into_inner();
843 if lo > subrange_hi || subrange_lo > hi {
844 // The pattern doesn't intersect with the subrange at all,
845 // so the subrange remains untouched.
846 remaining_ranges.push(range_to_constant(subrange_lo..=subrange_hi));
848 if lo > subrange_lo {
849 // The pattern intersects an upper section of the
850 // subrange, so a lower section will remain.
851 remaining_ranges.push(range_to_constant(subrange_lo..=(lo - 1)));
853 if hi < subrange_hi {
854 // The pattern intersects a lower section of the
855 // subrange, so an upper section will remain.
856 remaining_ranges.push(range_to_constant((hi + 1)..=subrange_hi));
864 /// Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
865 /// The algorithm from the paper has been modified to correctly handle empty
866 /// types. The changes are:
867 /// (0) We don't exit early if the pattern matrix has zero rows. We just
868 /// continue to recurse over columns.
869 /// (1) all_constructors will only return constructors that are statically
870 /// possible. eg. it will only return Ok for Result<T, !>
872 /// This finds whether a (row) vector `v` of patterns is 'useful' in relation
873 /// to a set of such vectors `m` - this is defined as there being a set of
874 /// inputs that will match `v` but not any of the sets in `m`.
876 /// All the patterns at each column of the `matrix ++ v` matrix must
877 /// have the same type, except that wildcard (PatternKind::Wild) patterns
878 /// with type TyErr are also allowed, even if the "type of the column"
879 /// is not TyErr. That is used to represent private fields, as using their
880 /// real type would assert that they are inhabited.
882 /// This is used both for reachability checking (if a pattern isn't useful in
883 /// relation to preceding patterns, it is not reachable) and exhaustiveness
884 /// checking (if a wildcard pattern is useful in relation to a matrix, the
885 /// matrix isn't exhaustive).
886 pub fn is_useful<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
887 matrix: &Matrix<'p, 'tcx>,
888 v: &[&'p Pattern<'tcx>],
889 witness: WitnessPreference)
890 -> Usefulness<'tcx> {
891 let &Matrix(ref rows) = matrix;
892 debug!("is_useful({:#?}, {:#?})", matrix, v);
894 // The base case. We are pattern-matching on () and the return value is
895 // based on whether our matrix has a row or not.
896 // NOTE: This could potentially be optimized by checking rows.is_empty()
897 // first and then, if v is non-empty, the return value is based on whether
898 // the type of the tuple we're checking is inhabited or not.
900 return if rows.is_empty() {
902 ConstructWitness => UsefulWithWitness(vec![Witness(vec![])]),
903 LeaveOutWitness => Useful,
910 assert!(rows.iter().all(|r| r.len() == v.len()));
912 let pcx = PatternContext {
913 // TyErr is used to represent the type of wildcard patterns matching
914 // against inaccessible (private) fields of structs, so that we won't
915 // be able to observe whether the types of the struct's fields are
918 // If the field is truly inaccessible, then all the patterns
919 // matching against it must be wildcard patterns, so its type
922 // However, if we are matching against non-wildcard patterns, we
923 // need to know the real type of the field so we can specialize
924 // against it. This primarily occurs through constants - they
925 // can include contents for fields that are inaccessible at the
926 // location of the match. In that case, the field's type is
927 // inhabited - by the constant - so we can just use it.
929 // FIXME: this might lead to "unstable" behavior with macro hygiene
930 // introducing uninhabited patterns for inaccessible fields. We
931 // need to figure out how to model that.
932 ty: rows.iter().map(|r| r[0].ty).find(|ty| !ty.references_error()).unwrap_or(v[0].ty),
933 max_slice_length: max_slice_length(cx, rows.iter().map(|r| r[0]).chain(Some(v[0])))
936 debug!("is_useful_expand_first_col: pcx={:#?}, expanding {:#?}", pcx, v[0]);
938 if let Some(constructors) = pat_constructors(cx, v[0], pcx) {
939 debug!("is_useful - expanding constructors: {:#?}", constructors);
940 constructors.into_iter().map(|c|
941 is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness)
942 ).find(|result| result.is_useful()).unwrap_or(NotUseful)
944 debug!("is_useful - expanding wildcard");
946 let used_ctors: Vec<Constructor> = rows.iter().flat_map(|row| {
947 pat_constructors(cx, row[0], pcx).unwrap_or(vec![])
949 debug!("used_ctors = {:#?}", used_ctors);
950 // `all_ctors` are all the constructors for the given type, which
951 // should all be represented (or caught with the wild pattern `_`).
952 let all_ctors = all_constructors(cx, pcx);
953 debug!("all_ctors = {:#?}", all_ctors);
955 // The only constructor patterns for which it is valid to
956 // treat the values as constructors are ranges (see
957 // `all_constructors` for details).
958 let exhaustive_integer_patterns = cx.tcx.features().exhaustive_integer_patterns;
959 let consider_value_constructors = exhaustive_integer_patterns
960 && all_ctors.iter().all(|ctor| match ctor {
961 ConstantRange(..) => true,
965 // `missing_ctors` are those that should have appeared
966 // as patterns in the `match` expression, but did not.
967 let mut missing_ctors = vec![];
968 for req_ctor in &all_ctors {
969 let mut refined_ctors = vec![req_ctor.clone()];
970 for used_ctor in &used_ctors {
971 if used_ctor == req_ctor {
972 // If a constructor appears in a `match` arm, we can
973 // eliminate it straight away.
974 refined_ctors = vec![]
975 } else if exhaustive_integer_patterns {
976 if let Some(interval) = IntRange::from_ctor(cx.tcx, used_ctor) {
977 // Refine the required constructors for the type by subtracting
978 // the range defined by the current constructor pattern.
979 refined_ctors = interval.subtract_from(cx.tcx, refined_ctors);
983 // If the constructor patterns that have been considered so far
984 // already cover the entire range of values, then we the
985 // constructor is not missing, and we can move on to the next one.
986 if refined_ctors.is_empty() {
990 // If a constructor has not been matched, then it is missing.
991 // We add `refined_ctors` instead of `req_ctor`, because then we can
992 // provide more detailed error information about precisely which
993 // ranges have been omitted.
994 missing_ctors.extend(refined_ctors);
997 // `missing_ctors` is the set of constructors from the same type as the
998 // first column of `matrix` that are matched only by wildcard patterns
999 // from the first column.
1001 // Therefore, if there is some pattern that is unmatched by `matrix`,
1002 // it will still be unmatched if the first constructor is replaced by
1003 // any of the constructors in `missing_ctors`
1005 // However, if our scrutinee is *privately* an empty enum, we
1006 // must treat it as though it had an "unknown" constructor (in
1007 // that case, all other patterns obviously can't be variants)
1008 // to avoid exposing its emptyness. See the `match_privately_empty`
1009 // test for details.
1011 // FIXME: currently the only way I know of something can
1012 // be a privately-empty enum is when the exhaustive_patterns
1013 // feature flag is not present, so this is only
1014 // needed for that case.
1016 let is_privately_empty =
1017 all_ctors.is_empty() && !cx.is_uninhabited(pcx.ty);
1018 let is_declared_nonexhaustive =
1019 cx.is_non_exhaustive_enum(pcx.ty) && !cx.is_local(pcx.ty);
1020 debug!("missing_ctors={:#?} is_privately_empty={:#?} is_declared_nonexhaustive={:#?}",
1021 missing_ctors, is_privately_empty, is_declared_nonexhaustive);
1023 // For privately empty and non-exhaustive enums, we work as if there were an "extra"
1024 // `_` constructor for the type, so we can never match over all constructors.
1025 let is_non_exhaustive = is_privately_empty || is_declared_nonexhaustive;
1027 if missing_ctors.is_empty() && !is_non_exhaustive {
1028 if consider_value_constructors {
1029 // If we've successfully matched every value
1030 // of the type, then we're done.
1033 all_ctors.into_iter().map(|c| {
1034 is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness)
1035 }).find(|result| result.is_useful()).unwrap_or(NotUseful)
1038 let matrix = rows.iter().filter_map(|r| {
1039 if r[0].is_wildcard() {
1040 Some(r[1..].to_vec())
1045 match is_useful(cx, &matrix, &v[1..], witness) {
1046 UsefulWithWitness(pats) => {
1048 // In this case, there's at least one "free"
1049 // constructor that is only matched against by
1050 // wildcard patterns.
1052 // There are 2 ways we can report a witness here.
1053 // Commonly, we can report all the "free"
1054 // constructors as witnesses, e.g. if we have:
1057 // enum Direction { N, S, E, W }
1058 // let Direction::N = ...;
1061 // we can report 3 witnesses: `S`, `E`, and `W`.
1063 // However, there are 2 cases where we don't want
1064 // to do this and instead report a single `_` witness:
1066 // 1) If the user is matching against a non-exhaustive
1067 // enum, there is no point in enumerating all possible
1068 // variants, because the user can't actually match
1069 // against them himself, e.g. in an example like:
1071 // let err: io::ErrorKind = ...;
1073 // io::ErrorKind::NotFound => {},
1076 // we don't want to show every possible IO error,
1077 // but instead have `_` as the witness (this is
1078 // actually *required* if the user specified *all*
1079 // IO errors, but is probably what we want in every
1082 // 2) If the user didn't actually specify a constructor
1083 // in this arm, e.g. in
1085 // let x: (Direction, Direction, bool) = ...;
1086 // let (_, _, false) = x;
1088 // we don't want to show all 16 possible witnesses
1089 // `(<direction-1>, <direction-2>, true)` - we are
1090 // satisfied with `(_, _, true)`. In this case,
1091 // `used_ctors` is empty.
1092 let new_witnesses = if is_non_exhaustive || used_ctors.is_empty() {
1093 // All constructors are unused. Add wild patterns
1094 // rather than each individual constructor.
1095 pats.into_iter().map(|mut witness| {
1096 witness.0.push(Pattern {
1099 kind: box PatternKind::Wild,
1104 pats.into_iter().flat_map(|witness| {
1105 missing_ctors.iter().map(move |ctor| {
1106 // Extends the witness with a "wild" version of this
1107 // constructor, that matches everything that can be built with
1108 // it. For example, if `ctor` is a `Constructor::Variant` for
1109 // `Option::Some`, this pushes the witness for `Some(_)`.
1110 witness.clone().push_wild_constructor(cx, ctor, pcx.ty)
1114 UsefulWithWitness(new_witnesses)
1122 fn is_useful_specialized<'p, 'a:'p, 'tcx: 'a>(
1123 cx: &mut MatchCheckCtxt<'a, 'tcx>,
1124 &Matrix(ref m): &Matrix<'p, 'tcx>,
1125 v: &[&'p Pattern<'tcx>],
1126 ctor: Constructor<'tcx>,
1128 witness: WitnessPreference) -> Usefulness<'tcx>
1130 debug!("is_useful_specialized({:#?}, {:#?}, {:?})", v, ctor, lty);
1131 let sub_pat_tys = constructor_sub_pattern_tys(cx, &ctor, lty);
1132 let wild_patterns_owned: Vec<_> = sub_pat_tys.iter().map(|ty| {
1136 kind: box PatternKind::Wild,
1139 let wild_patterns: Vec<_> = wild_patterns_owned.iter().collect();
1140 let matrix = Matrix(m.iter().flat_map(|r| {
1141 specialize(cx, &r, &ctor, &wild_patterns)
1143 match specialize(cx, v, &ctor, &wild_patterns) {
1144 Some(v) => match is_useful(cx, &matrix, &v, witness) {
1145 UsefulWithWitness(witnesses) => UsefulWithWitness(
1146 witnesses.into_iter()
1147 .map(|witness| witness.apply_constructor(cx, &ctor, lty))
1156 /// Determines the constructors that the given pattern can be specialized to.
1158 /// In most cases, there's only one constructor that a specific pattern
1159 /// represents, such as a specific enum variant or a specific literal value.
1160 /// Slice patterns, however, can match slices of different lengths. For instance,
1161 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
1163 /// Returns `None` in case of a catch-all, which can't be specialized.
1164 fn pat_constructors<'tcx>(cx: &mut MatchCheckCtxt,
1165 pat: &Pattern<'tcx>,
1166 pcx: PatternContext)
1167 -> Option<Vec<Constructor<'tcx>>>
1170 PatternKind::Binding { .. } | PatternKind::Wild =>
1172 PatternKind::Leaf { .. } | PatternKind::Deref { .. } =>
1174 PatternKind::Variant { adt_def, variant_index, .. } =>
1175 Some(vec![Variant(adt_def.variants[variant_index].did)]),
1176 PatternKind::Constant { value } =>
1177 Some(vec![ConstantValue(value)]),
1178 PatternKind::Range { lo, hi, end } =>
1179 Some(vec![ConstantRange(lo, hi, end)]),
1180 PatternKind::Array { .. } => match pcx.ty.sty {
1181 ty::TyArray(_, length) => Some(vec![
1182 Slice(length.unwrap_usize(cx.tcx))
1184 _ => span_bug!(pat.span, "bad ty {:?} for array pattern", pcx.ty)
1186 PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
1187 let pat_len = prefix.len() as u64 + suffix.len() as u64;
1188 if slice.is_some() {
1189 Some((pat_len..pcx.max_slice_length+1).map(Slice).collect())
1191 Some(vec![Slice(pat_len)])
1197 /// This computes the arity of a constructor. The arity of a constructor
1198 /// is how many subpattern patterns of that constructor should be expanded to.
1200 /// For instance, a tuple pattern (_, 42, Some([])) has the arity of 3.
1201 /// A struct pattern's arity is the number of fields it contains, etc.
1202 fn constructor_arity(_cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> u64 {
1203 debug!("constructor_arity({:#?}, {:?})", ctor, ty);
1205 ty::TyTuple(ref fs) => fs.len() as u64,
1206 ty::TySlice(..) | ty::TyArray(..) => match *ctor {
1207 Slice(length) => length,
1208 ConstantValue(_) => 0,
1209 _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
1212 ty::TyAdt(adt, _) => {
1213 adt.variants[ctor.variant_index_for_adt(adt)].fields.len() as u64
1219 /// This computes the types of the sub patterns that a constructor should be
1222 /// For instance, a tuple pattern (43u32, 'a') has sub pattern types [u32, char].
1223 fn constructor_sub_pattern_tys<'a, 'tcx: 'a>(cx: &MatchCheckCtxt<'a, 'tcx>,
1225 ty: Ty<'tcx>) -> Vec<Ty<'tcx>>
1227 debug!("constructor_sub_pattern_tys({:#?}, {:?})", ctor, ty);
1229 ty::TyTuple(ref fs) => fs.into_iter().map(|t| *t).collect(),
1230 ty::TySlice(ty) | ty::TyArray(ty, _) => match *ctor {
1231 Slice(length) => (0..length).map(|_| ty).collect(),
1232 ConstantValue(_) => vec![],
1233 _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
1235 ty::TyRef(_, rty, _) => vec![rty],
1236 ty::TyAdt(adt, substs) => {
1238 // Use T as the sub pattern type of Box<T>.
1239 vec![substs.type_at(0)]
1241 adt.variants[ctor.variant_index_for_adt(adt)].fields.iter().map(|field| {
1242 let is_visible = adt.is_enum()
1243 || field.vis.is_accessible_from(cx.module, cx.tcx);
1245 field.ty(cx.tcx, substs)
1247 // Treat all non-visible fields as TyErr. They
1248 // can't appear in any other pattern from
1249 // this match (because they are private),
1250 // so their type does not matter - but
1251 // we don't want to know they are
1262 fn slice_pat_covered_by_constructor<'tcx>(
1263 tcx: TyCtxt<'_, 'tcx, '_>,
1266 prefix: &[Pattern<'tcx>],
1267 slice: &Option<Pattern<'tcx>>,
1268 suffix: &[Pattern<'tcx>]
1269 ) -> Result<bool, ErrorReported> {
1270 let data: &[u8] = match *ctor {
1271 ConstantValue(const_val) => {
1272 let val = match const_val.val {
1273 ConstValue::Unevaluated(..) |
1274 ConstValue::ByRef(..) => bug!("unexpected ConstValue: {:?}", const_val),
1275 ConstValue::Scalar(val) | ConstValue::ScalarPair(val, _) => val,
1277 if let Ok(ptr) = val.to_ptr() {
1278 let is_array_ptr = const_val.ty
1279 .builtin_deref(true)
1280 .and_then(|t| t.ty.builtin_index())
1281 .map_or(false, |t| t == tcx.types.u8);
1282 assert!(is_array_ptr);
1283 tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id).bytes.as_ref()
1285 bug!("unexpected non-ptr ConstantValue")
1291 let pat_len = prefix.len() + suffix.len();
1292 if data.len() < pat_len || (slice.is_none() && data.len() > pat_len) {
1297 data[..prefix.len()].iter().zip(prefix).chain(
1298 data[data.len()-suffix.len()..].iter().zip(suffix))
1301 box PatternKind::Constant { value } => {
1302 let b = value.unwrap_bits(tcx, ty::ParamEnv::empty().and(pat.ty));
1303 assert_eq!(b as u8 as u128, b);
1315 fn constructor_covered_by_range<'a, 'tcx>(
1316 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1317 ctor: &Constructor<'tcx>,
1318 from: &'tcx ty::Const<'tcx>, to: &'tcx ty::Const<'tcx>,
1321 ) -> Result<bool, ErrorReported> {
1322 trace!("constructor_covered_by_range {:#?}, {:#?}, {:#?}, {}", ctor, from, to, ty);
1323 let cmp_from = |c_from| compare_const_vals(tcx, c_from, from, ty::ParamEnv::empty().and(ty))
1324 .map(|res| res != Ordering::Less);
1325 let cmp_to = |c_to| compare_const_vals(tcx, c_to, to, ty::ParamEnv::empty().and(ty));
1326 macro_rules! some_or_ok {
1330 None => return Ok(false), // not char or int
1335 ConstantValue(value) => {
1336 let to = some_or_ok!(cmp_to(value));
1337 let end = (to == Ordering::Less) ||
1338 (end == RangeEnd::Included && to == Ordering::Equal);
1339 Ok(some_or_ok!(cmp_from(value)) && end)
1341 ConstantRange(from, to, RangeEnd::Included) => {
1342 let to = some_or_ok!(cmp_to(to));
1343 let end = (to == Ordering::Less) ||
1344 (end == RangeEnd::Included && to == Ordering::Equal);
1345 Ok(some_or_ok!(cmp_from(from)) && end)
1347 ConstantRange(from, to, RangeEnd::Excluded) => {
1348 let to = some_or_ok!(cmp_to(to));
1349 let end = (to == Ordering::Less) ||
1350 (end == RangeEnd::Excluded && to == Ordering::Equal);
1351 Ok(some_or_ok!(cmp_from(from)) && end)
1358 fn patterns_for_variant<'p, 'a: 'p, 'tcx: 'a>(
1359 subpatterns: &'p [FieldPattern<'tcx>],
1360 wild_patterns: &[&'p Pattern<'tcx>])
1361 -> Vec<&'p Pattern<'tcx>>
1363 let mut result = wild_patterns.to_owned();
1365 for subpat in subpatterns {
1366 result[subpat.field.index()] = &subpat.pattern;
1369 debug!("patterns_for_variant({:#?}, {:#?}) = {:#?}", subpatterns, wild_patterns, result);
1373 /// This is the main specialization step. It expands the first pattern in the given row
1374 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
1375 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
1377 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
1378 /// different patterns.
1379 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
1380 /// fields filled with wild patterns.
1381 fn specialize<'p, 'a: 'p, 'tcx: 'a>(
1382 cx: &mut MatchCheckCtxt<'a, 'tcx>,
1383 r: &[&'p Pattern<'tcx>],
1384 constructor: &Constructor<'tcx>,
1385 wild_patterns: &[&'p Pattern<'tcx>])
1386 -> Option<Vec<&'p Pattern<'tcx>>>
1390 let head: Option<Vec<&Pattern>> = match *pat.kind {
1391 PatternKind::Binding { .. } | PatternKind::Wild => {
1392 Some(wild_patterns.to_owned())
1395 PatternKind::Variant { adt_def, variant_index, ref subpatterns, .. } => {
1396 let ref variant = adt_def.variants[variant_index];
1397 if *constructor == Variant(variant.did) {
1398 Some(patterns_for_variant(subpatterns, wild_patterns))
1404 PatternKind::Leaf { ref subpatterns } => {
1405 Some(patterns_for_variant(subpatterns, wild_patterns))
1408 PatternKind::Deref { ref subpattern } => {
1409 Some(vec![subpattern])
1412 PatternKind::Constant { value } => {
1413 match *constructor {
1415 if let Some(ptr) = value.to_ptr() {
1416 let is_array_ptr = value.ty
1417 .builtin_deref(true)
1418 .and_then(|t| t.ty.builtin_index())
1419 .map_or(false, |t| t == cx.tcx.types.u8);
1420 assert!(is_array_ptr);
1421 let data_len = cx.tcx
1424 .unwrap_memory(ptr.alloc_id)
1427 if wild_patterns.len() == data_len {
1428 Some(cx.lower_byte_str_pattern(pat))
1434 "unexpected const-val {:?} with ctor {:?}", value, constructor)
1438 match constructor_covered_by_range(
1440 constructor, value, value, RangeEnd::Included,
1443 Ok(true) => Some(vec![]),
1445 Err(ErrorReported) => None,
1451 PatternKind::Range { lo, hi, ref end } => {
1452 match constructor_covered_by_range(
1454 constructor, lo, hi, end.clone(), lo.ty,
1456 Ok(true) => Some(vec![]),
1458 Err(ErrorReported) => None,
1462 PatternKind::Array { ref prefix, ref slice, ref suffix } |
1463 PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
1464 match *constructor {
1466 let pat_len = prefix.len() + suffix.len();
1467 if let Some(slice_count) = wild_patterns.len().checked_sub(pat_len) {
1468 if slice_count == 0 || slice.is_some() {
1470 prefix.iter().chain(
1471 wild_patterns.iter().map(|p| *p)
1484 ConstantValue(..) => {
1485 match slice_pat_covered_by_constructor(
1486 cx.tcx, pat.span, constructor, prefix, slice, suffix
1488 Ok(true) => Some(vec![]),
1490 Err(ErrorReported) => None
1493 _ => span_bug!(pat.span,
1494 "unexpected ctor {:?} for slice pat", constructor)
1498 debug!("specialize({:#?}, {:#?}) = {:#?}", r[0], wild_patterns, head);
1500 head.map(|mut head| {
1501 head.extend_from_slice(&r[1 ..]);