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 use self::Constructor::*;
12 use self::Usefulness::*;
13 use self::WitnessPreference::*;
15 use rustc_data_structures::fx::FxHashMap;
16 use rustc_data_structures::indexed_vec::Idx;
18 use super::{FieldPattern, Pattern, PatternKind};
19 use super::{PatternFoldable, PatternFolder, compare_const_vals};
21 use rustc::hir::def_id::DefId;
22 use rustc::hir::RangeEnd;
23 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
24 use rustc::ty::layout::{Integer, IntegerExt};
26 use rustc::mir::Field;
27 use rustc::mir::interpret::ConstValue;
28 use rustc::util::common::ErrorReported;
30 use syntax::attr::{SignedInt, UnsignedInt};
31 use syntax_pos::{Span, DUMMY_SP};
33 use arena::TypedArena;
35 use std::cmp::{self, Ordering};
37 use std::iter::{FromIterator, IntoIterator};
39 pub fn expand_pattern<'a, 'tcx>(cx: &MatchCheckCtxt<'a, 'tcx>, pat: Pattern<'tcx>)
42 cx.pattern_arena.alloc(LiteralExpander.fold_pattern(&pat))
45 struct LiteralExpander;
46 impl<'tcx> PatternFolder<'tcx> for LiteralExpander {
47 fn fold_pattern(&mut self, pat: &Pattern<'tcx>) -> Pattern<'tcx> {
48 match (&pat.ty.sty, &*pat.kind) {
49 (&ty::TyRef(_, rty, _), &PatternKind::Constant { ref value }) => {
53 kind: box PatternKind::Deref {
57 kind: box PatternKind::Constant { value: value.clone() },
62 (_, &PatternKind::Binding { subpattern: Some(ref s), .. }) => {
65 _ => pat.super_fold_with(self)
70 impl<'tcx> Pattern<'tcx> {
71 fn is_wildcard(&self) -> bool {
73 PatternKind::Binding { subpattern: None, .. } | PatternKind::Wild =>
80 pub struct Matrix<'a, 'tcx: 'a>(Vec<Vec<&'a Pattern<'tcx>>>);
82 impl<'a, 'tcx> Matrix<'a, 'tcx> {
83 pub fn empty() -> Self {
87 pub fn push(&mut self, row: Vec<&'a Pattern<'tcx>>) {
92 /// Pretty-printer for matrices of patterns, example:
93 /// ++++++++++++++++++++++++++
95 /// ++++++++++++++++++++++++++
96 /// + true + [First] +
97 /// ++++++++++++++++++++++++++
98 /// + true + [Second(true)] +
99 /// ++++++++++++++++++++++++++
101 /// ++++++++++++++++++++++++++
102 /// + _ + [_, _, ..tail] +
103 /// ++++++++++++++++++++++++++
104 impl<'a, 'tcx> fmt::Debug for Matrix<'a, 'tcx> {
105 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
108 let &Matrix(ref m) = self;
109 let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| {
110 row.iter().map(|pat| format!("{:?}", pat)).collect()
113 let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0);
114 assert!(m.iter().all(|row| row.len() == column_count));
115 let column_widths: Vec<usize> = (0..column_count).map(|col| {
116 pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0)
119 let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1;
120 let br = "+".repeat(total_width);
121 write!(f, "{}\n", br)?;
122 for row in pretty_printed_matrix {
124 for (column, pat_str) in row.into_iter().enumerate() {
126 write!(f, "{:1$}", pat_str, column_widths[column])?;
130 write!(f, "{}\n", br)?;
136 impl<'a, 'tcx> FromIterator<Vec<&'a Pattern<'tcx>>> for Matrix<'a, 'tcx> {
137 fn from_iter<T: IntoIterator<Item=Vec<&'a Pattern<'tcx>>>>(iter: T) -> Self
139 Matrix(iter.into_iter().collect())
143 pub struct MatchCheckCtxt<'a, 'tcx: 'a> {
144 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
145 /// The module in which the match occurs. This is necessary for
146 /// checking inhabited-ness of types because whether a type is (visibly)
147 /// inhabited can depend on whether it was defined in the current module or
148 /// not. eg. `struct Foo { _private: ! }` cannot be seen to be empty
149 /// outside it's module and should not be matchable with an empty match
152 pub pattern_arena: &'a TypedArena<Pattern<'tcx>>,
153 pub byte_array_map: FxHashMap<*const Pattern<'tcx>, Vec<&'a Pattern<'tcx>>>,
156 impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> {
157 pub fn create_and_enter<F, R>(
158 tcx: TyCtxt<'a, 'tcx, 'tcx>,
161 where F: for<'b> FnOnce(MatchCheckCtxt<'b, 'tcx>) -> R
163 let pattern_arena = TypedArena::new();
168 pattern_arena: &pattern_arena,
169 byte_array_map: FxHashMap(),
173 // convert a byte-string pattern to a list of u8 patterns.
174 fn lower_byte_str_pattern<'p>(&mut self, pat: &'p Pattern<'tcx>) -> Vec<&'p Pattern<'tcx>>
177 let pattern_arena = &*self.pattern_arena;
179 self.byte_array_map.entry(pat).or_insert_with(|| {
181 box PatternKind::Constant {
184 if let Some(ptr) = const_val.to_ptr() {
185 let is_array_ptr = const_val.ty
187 .and_then(|t| t.ty.builtin_index())
188 .map_or(false, |t| t == tcx.types.u8);
189 assert!(is_array_ptr);
190 let alloc = tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
191 assert_eq!(ptr.offset.bytes(), 0);
192 // FIXME: check length
193 alloc.bytes.iter().map(|b| {
194 &*pattern_arena.alloc(Pattern {
197 kind: box PatternKind::Constant {
198 value: ty::Const::from_bits(
201 ty::ParamEnv::empty().and(tcx.types.u8))
206 bug!("not a byte str: {:?}", const_val)
209 _ => span_bug!(pat.span, "unexpected byte array pattern {:?}", pat)
214 fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool {
215 if self.tcx.features().exhaustive_patterns {
216 self.tcx.is_ty_uninhabited_from(self.module, ty)
222 fn is_non_exhaustive_enum(&self, ty: Ty<'tcx>) -> bool {
224 ty::TyAdt(adt_def, ..) => adt_def.is_enum() && adt_def.is_non_exhaustive(),
229 fn is_local(&self, ty: Ty<'tcx>) -> bool {
231 ty::TyAdt(adt_def, ..) => adt_def.did.is_local(),
236 fn is_variant_uninhabited(&self,
237 variant: &'tcx ty::VariantDef,
238 substs: &'tcx ty::subst::Substs<'tcx>)
241 if self.tcx.features().exhaustive_patterns {
242 self.tcx.is_enum_variant_uninhabited_from(self.module, variant, substs)
249 #[derive(Clone, Debug, PartialEq)]
250 pub enum Constructor<'tcx> {
251 /// The constructor of all patterns that don't vary by constructor,
252 /// e.g. struct patterns and fixed-length arrays.
257 ConstantValue(&'tcx ty::Const<'tcx>),
258 /// Ranges of literal values (`2...5` and `2..5`).
259 ConstantRange(&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>, RangeEnd),
260 /// Array patterns of length n.
264 impl<'tcx> Constructor<'tcx> {
265 fn variant_index_for_adt(&self, adt: &'tcx ty::AdtDef) -> usize {
267 &Variant(vid) => adt.variant_index_with_id(vid),
269 assert!(!adt.is_enum());
272 _ => bug!("bad constructor {:?} for adt {:?}", self, adt)
278 pub enum Usefulness<'tcx> {
280 UsefulWithWitness(Vec<Witness<'tcx>>),
284 impl<'tcx> Usefulness<'tcx> {
285 fn is_useful(&self) -> bool {
293 #[derive(Copy, Clone)]
294 pub enum WitnessPreference {
299 #[derive(Copy, Clone, Debug)]
300 struct PatternContext<'tcx> {
302 max_slice_length: u64,
305 /// A stack of patterns in reverse order of construction
307 pub struct Witness<'tcx>(Vec<Pattern<'tcx>>);
309 impl<'tcx> Witness<'tcx> {
310 pub fn single_pattern(&self) -> &Pattern<'tcx> {
311 assert_eq!(self.0.len(), 1);
315 fn push_wild_constructor<'a>(
317 cx: &MatchCheckCtxt<'a, 'tcx>,
318 ctor: &Constructor<'tcx>,
322 let sub_pattern_tys = constructor_sub_pattern_tys(cx, ctor, ty);
323 self.0.extend(sub_pattern_tys.into_iter().map(|ty| {
327 kind: box PatternKind::Wild,
330 self.apply_constructor(cx, ctor, ty)
334 /// Constructs a partial witness for a pattern given a list of
335 /// patterns expanded by the specialization step.
337 /// When a pattern P is discovered to be useful, this function is used bottom-up
338 /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
339 /// of values, V, where each value in that set is not covered by any previously
340 /// used patterns and is covered by the pattern P'. Examples:
342 /// left_ty: tuple of 3 elements
343 /// pats: [10, 20, _] => (10, 20, _)
345 /// left_ty: struct X { a: (bool, &'static str), b: usize}
346 /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 }
347 fn apply_constructor<'a>(
349 cx: &MatchCheckCtxt<'a,'tcx>,
350 ctor: &Constructor<'tcx>,
354 let arity = constructor_arity(cx, ctor, ty);
356 let len = self.0.len() as u64;
357 let mut pats = self.0.drain((len-arity) as usize..).rev();
362 let pats = pats.enumerate().map(|(i, p)| {
364 field: Field::new(i),
369 if let ty::TyAdt(adt, substs) = ty.sty {
371 PatternKind::Variant {
374 variant_index: ctor.variant_index_for_adt(adt),
378 PatternKind::Leaf { subpatterns: pats }
381 PatternKind::Leaf { subpatterns: pats }
386 PatternKind::Deref { subpattern: pats.nth(0).unwrap() }
389 ty::TySlice(_) | ty::TyArray(..) => {
391 prefix: pats.collect(),
399 ConstantValue(value) => PatternKind::Constant { value },
400 _ => PatternKind::Wild,
406 self.0.push(Pattern {
416 /// This determines the set of all possible constructors of a pattern matching
417 /// values of type `left_ty`. For vectors, this would normally be an infinite set
418 /// but is instead bounded by the maximum fixed length of slice patterns in
419 /// the column of patterns being analyzed.
421 /// This intentionally does not list ConstantValue specializations for
422 /// non-booleans, because we currently assume that there is always a
423 /// "non-standard constant" that matches. See issue #12483.
425 /// We make sure to omit constructors that are statically impossible. eg for
426 /// Option<!> we do not include Some(_) in the returned list of constructors.
427 fn all_constructors<'a, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
428 pcx: PatternContext<'tcx>)
429 -> Vec<Constructor<'tcx>>
431 debug!("all_constructors({:?})", pcx.ty);
432 let exhaustive_integer_patterns = cx.tcx.features().exhaustive_integer_patterns;
433 let ctors = match pcx.ty.sty {
435 [true, false].iter().map(|&b| {
436 ConstantValue(ty::Const::from_bool(cx.tcx, b))
439 ty::TyArray(ref sub_ty, len) if len.assert_usize(cx.tcx).is_some() => {
440 let len = len.unwrap_usize(cx.tcx);
441 if len != 0 && cx.is_uninhabited(sub_ty) {
447 // Treat arrays of a constant but unknown length like slices.
448 ty::TyArray(ref sub_ty, _) |
449 ty::TySlice(ref sub_ty) => {
450 if cx.is_uninhabited(sub_ty) {
453 (0..pcx.max_slice_length+1).map(|length| Slice(length)).collect()
456 ty::TyAdt(def, substs) if def.is_enum() => {
458 .filter(|v| !cx.is_variant_uninhabited(v, substs))
459 .map(|v| Variant(v.did))
462 ty::TyChar if exhaustive_integer_patterns => {
463 let endpoint = |c: char| {
464 let ty = ty::ParamEnv::empty().and(cx.tcx.types.char);
465 ty::Const::from_bits(cx.tcx, c as u128, ty)
468 // The valid Unicode Scalar Value ranges.
469 ConstantRange(endpoint('\u{0000}'), endpoint('\u{D7FF}'), RangeEnd::Included),
470 ConstantRange(endpoint('\u{E000}'), endpoint('\u{10FFFF}'), RangeEnd::Included),
473 ty::TyInt(ity) if exhaustive_integer_patterns => {
474 // FIXME(49937): refactor these bit manipulations into interpret.
475 let bits = Integer::from_attr(cx.tcx, SignedInt(ity)).size().bits() as u128;
476 let min = 1u128 << (bits - 1);
477 let max = (1u128 << (bits - 1)) - 1;
478 let ty = ty::ParamEnv::empty().and(pcx.ty);
479 vec![ConstantRange(ty::Const::from_bits(cx.tcx, min as u128, ty),
480 ty::Const::from_bits(cx.tcx, max as u128, ty),
483 ty::TyUint(uty) if exhaustive_integer_patterns => {
484 // FIXME(49937): refactor these bit manipulations into interpret.
485 let bits = Integer::from_attr(cx.tcx, UnsignedInt(uty)).size().bits() as u128;
486 let max = !0u128 >> (128 - bits);
487 let ty = ty::ParamEnv::empty().and(pcx.ty);
488 vec![ConstantRange(ty::Const::from_bits(cx.tcx, 0, ty),
489 ty::Const::from_bits(cx.tcx, max, ty),
493 if cx.is_uninhabited(pcx.ty) {
503 fn max_slice_length<'p, 'a: 'p, 'tcx: 'a, I>(
504 cx: &mut MatchCheckCtxt<'a, 'tcx>,
506 where I: Iterator<Item=&'p Pattern<'tcx>>
508 // The exhaustiveness-checking paper does not include any details on
509 // checking variable-length slice patterns. However, they are matched
510 // by an infinite collection of fixed-length array patterns.
512 // Checking the infinite set directly would take an infinite amount
513 // of time. However, it turns out that for each finite set of
514 // patterns `P`, all sufficiently large array lengths are equivalent:
516 // Each slice `s` with a "sufficiently-large" length `l ≥ L` that applies
517 // to exactly the subset `Pₜ` of `P` can be transformed to a slice
518 // `sₘ` for each sufficiently-large length `m` that applies to exactly
519 // the same subset of `P`.
521 // Because of that, each witness for reachability-checking from one
522 // of the sufficiently-large lengths can be transformed to an
523 // equally-valid witness from any other length, so we only have
524 // to check slice lengths from the "minimal sufficiently-large length"
527 // Note that the fact that there is a *single* `sₘ` for each `m`
528 // not depending on the specific pattern in `P` is important: if
529 // you look at the pair of patterns
532 // Then any slice of length ≥1 that matches one of these two
533 // patterns can be be trivially turned to a slice of any
534 // other length ≥1 that matches them and vice-versa - for
535 // but the slice from length 2 `[false, true]` that matches neither
536 // of these patterns can't be turned to a slice from length 1 that
537 // matches neither of these patterns, so we have to consider
538 // slices from length 2 there.
540 // Now, to see that that length exists and find it, observe that slice
541 // patterns are either "fixed-length" patterns (`[_, _, _]`) or
542 // "variable-length" patterns (`[_, .., _]`).
544 // For fixed-length patterns, all slices with lengths *longer* than
545 // the pattern's length have the same outcome (of not matching), so
546 // as long as `L` is greater than the pattern's length we can pick
547 // any `sₘ` from that length and get the same result.
549 // For variable-length patterns, the situation is more complicated,
550 // because as seen above the precise value of `sₘ` matters.
552 // However, for each variable-length pattern `p` with a prefix of length
553 // `plâ‚š` and suffix of length `slâ‚š`, only the first `plâ‚š` and the last
554 // `slâ‚š` elements are examined.
556 // Therefore, as long as `L` is positive (to avoid concerns about empty
557 // types), all elements after the maximum prefix length and before
558 // the maximum suffix length are not examined by any variable-length
559 // pattern, and therefore can be added/removed without affecting
560 // them - creating equivalent patterns from any sufficiently-large
563 // Of course, if fixed-length patterns exist, we must be sure
564 // that our length is large enough to miss them all, so
565 // we can pick `L = max(FIXED_LEN+1 ∪ {max(PREFIX_LEN) + max(SUFFIX_LEN)})`
567 // for example, with the above pair of patterns, all elements
568 // but the first and last can be added/removed, so any
569 // witness of length ≥2 (say, `[false, false, true]`) can be
570 // turned to a witness from any other length ≥2.
572 let mut max_prefix_len = 0;
573 let mut max_suffix_len = 0;
574 let mut max_fixed_len = 0;
576 for row in patterns {
578 PatternKind::Constant { value } => {
579 if let Some(ptr) = value.to_ptr() {
580 let is_array_ptr = value.ty
582 .and_then(|t| t.ty.builtin_index())
583 .map_or(false, |t| t == cx.tcx.types.u8);
585 let alloc = cx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
586 max_fixed_len = cmp::max(max_fixed_len, alloc.bytes.len() as u64);
590 PatternKind::Slice { ref prefix, slice: None, ref suffix } => {
591 let fixed_len = prefix.len() as u64 + suffix.len() as u64;
592 max_fixed_len = cmp::max(max_fixed_len, fixed_len);
594 PatternKind::Slice { ref prefix, slice: Some(_), ref suffix } => {
595 max_prefix_len = cmp::max(max_prefix_len, prefix.len() as u64);
596 max_suffix_len = cmp::max(max_suffix_len, suffix.len() as u64);
602 cmp::max(max_fixed_len + 1, max_prefix_len + max_suffix_len)
605 /// An inclusive interval, used for precise integer exhaustiveness checking.
606 /// `IntRange`s always store a contiguous range. This means that values are
607 /// encoded such that `0` encodes the minimum value for the integer,
608 /// regardless of the signedness.
609 /// For example, the pattern `-128...127i8` is encoded as `0..=255`.
610 /// This makes comparisons and arithmetic on interval endpoints much more
611 /// straightforward. See `signed_bias` for details.
612 struct IntRange<'tcx> {
613 pub range: RangeInclusive<u128>,
617 impl<'tcx> IntRange<'tcx> {
618 fn from_ctor(tcx: TyCtxt<'_, 'tcx, 'tcx>,
619 ctor: &Constructor<'tcx>)
620 -> Option<IntRange<'tcx>> {
622 ConstantRange(lo, hi, end) => {
623 assert_eq!(lo.ty, hi.ty);
625 let env_ty = ty::ParamEnv::empty().and(ty);
626 if let Some(lo) = lo.assert_bits(tcx, env_ty) {
627 if let Some(hi) = hi.assert_bits(tcx, env_ty) {
628 // Perform a shift if the underlying types are signed,
629 // which makes the interval arithmetic simpler.
630 let bias = IntRange::signed_bias(tcx, ty);
631 let (lo, hi) = (lo ^ bias, hi ^ bias);
632 // Make sure the interval is well-formed.
633 return if lo > hi || lo == hi && *end == RangeEnd::Excluded {
636 let offset = (*end == RangeEnd::Excluded) as u128;
637 Some(IntRange { range: lo..=(hi - offset), ty })
643 ConstantValue(val) => {
645 if let Some(val) = val.assert_bits(tcx, ty::ParamEnv::empty().and(ty)) {
646 let bias = IntRange::signed_bias(tcx, ty);
647 let val = val ^ bias;
648 Some(IntRange { range: val..=val, ty })
653 Single | Variant(_) | Slice(_) => {
659 // The return value of `signed_bias` should be
660 // XORed with an endpoint to encode/decode it.
661 fn signed_bias(tcx: TyCtxt<'_, 'tcx, 'tcx>, ty: Ty<'tcx>) -> u128 {
664 let bits = Integer::from_attr(tcx, SignedInt(ity)).size().bits() as u128;
671 /// Given an `IntRange` corresponding to a pattern in a `match` and a collection of
672 /// ranges corresponding to the domain of values of a type (say, an integer), return
673 /// a new collection of ranges corresponding to the original ranges minus the ranges
674 /// covered by the `IntRange`.
675 fn subtract_from(self,
676 tcx: TyCtxt<'_, 'tcx, 'tcx>,
677 ranges: Vec<Constructor<'tcx>>)
678 -> Vec<Constructor<'tcx>> {
679 let ranges = ranges.into_iter().filter_map(|r| {
680 IntRange::from_ctor(tcx, &r).map(|i| i.range)
682 // Convert a `RangeInclusive` to a `ConstantValue` or inclusive `ConstantRange`.
683 let bias = IntRange::signed_bias(tcx, self.ty);
684 let ty = ty::ParamEnv::empty().and(self.ty);
685 let range_to_constant = |r: RangeInclusive<u128>| {
686 let (lo, hi) = r.into_inner();
688 ConstantValue(ty::Const::from_bits(tcx, lo ^ bias, ty))
690 ConstantRange(ty::Const::from_bits(tcx, lo ^ bias, ty),
691 ty::Const::from_bits(tcx, hi ^ bias, ty),
695 let mut remaining_ranges = vec![];
696 let (lo, hi) = self.range.into_inner();
697 for subrange in ranges {
698 let (subrange_lo, subrange_hi) = subrange.into_inner();
699 if lo > subrange_hi || subrange_lo > hi {
700 // The pattern doesn't intersect with the subrange at all,
701 // so the subrange remains untouched.
702 remaining_ranges.push(range_to_constant(subrange_lo..=subrange_hi));
704 if lo > subrange_lo {
705 // The pattern intersects an upper section of the
706 // subrange, so a lower section will remain.
707 remaining_ranges.push(range_to_constant(subrange_lo..=(lo - 1)));
709 if hi < subrange_hi {
710 // The pattern intersects a lower section of the
711 // subrange, so an upper section will remain.
712 remaining_ranges.push(range_to_constant((hi + 1)..=subrange_hi));
720 /// Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
721 /// The algorithm from the paper has been modified to correctly handle empty
722 /// types. The changes are:
723 /// (0) We don't exit early if the pattern matrix has zero rows. We just
724 /// continue to recurse over columns.
725 /// (1) all_constructors will only return constructors that are statically
726 /// possible. eg. it will only return Ok for Result<T, !>
728 /// This finds whether a (row) vector `v` of patterns is 'useful' in relation
729 /// to a set of such vectors `m` - this is defined as there being a set of
730 /// inputs that will match `v` but not any of the sets in `m`.
732 /// All the patterns at each column of the `matrix ++ v` matrix must
733 /// have the same type, except that wildcard (PatternKind::Wild) patterns
734 /// with type TyErr are also allowed, even if the "type of the column"
735 /// is not TyErr. That is used to represent private fields, as using their
736 /// real type would assert that they are inhabited.
738 /// This is used both for reachability checking (if a pattern isn't useful in
739 /// relation to preceding patterns, it is not reachable) and exhaustiveness
740 /// checking (if a wildcard pattern is useful in relation to a matrix, the
741 /// matrix isn't exhaustive).
742 pub fn is_useful<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
743 matrix: &Matrix<'p, 'tcx>,
744 v: &[&'p Pattern<'tcx>],
745 witness: WitnessPreference)
746 -> Usefulness<'tcx> {
747 let &Matrix(ref rows) = matrix;
748 debug!("is_useful({:#?}, {:#?})", matrix, v);
750 // The base case. We are pattern-matching on () and the return value is
751 // based on whether our matrix has a row or not.
752 // NOTE: This could potentially be optimized by checking rows.is_empty()
753 // first and then, if v is non-empty, the return value is based on whether
754 // the type of the tuple we're checking is inhabited or not.
756 return if rows.is_empty() {
758 ConstructWitness => UsefulWithWitness(vec![Witness(vec![])]),
759 LeaveOutWitness => Useful,
766 assert!(rows.iter().all(|r| r.len() == v.len()));
768 let pcx = PatternContext {
769 // TyErr is used to represent the type of wildcard patterns matching
770 // against inaccessible (private) fields of structs, so that we won't
771 // be able to observe whether the types of the struct's fields are
774 // If the field is truly inaccessible, then all the patterns
775 // matching against it must be wildcard patterns, so its type
778 // However, if we are matching against non-wildcard patterns, we
779 // need to know the real type of the field so we can specialize
780 // against it. This primarily occurs through constants - they
781 // can include contents for fields that are inaccessible at the
782 // location of the match. In that case, the field's type is
783 // inhabited - by the constant - so we can just use it.
785 // FIXME: this might lead to "unstable" behavior with macro hygiene
786 // introducing uninhabited patterns for inaccessible fields. We
787 // need to figure out how to model that.
788 ty: rows.iter().map(|r| r[0].ty).find(|ty| !ty.references_error())
790 max_slice_length: max_slice_length(cx, rows.iter().map(|r| r[0]).chain(Some(v[0])))
793 debug!("is_useful_expand_first_col: pcx={:#?}, expanding {:#?}", pcx, v[0]);
795 if let Some(constructors) = pat_constructors(cx, v[0], pcx) {
796 debug!("is_useful - expanding constructors: {:#?}", constructors);
797 constructors.into_iter().map(|c|
798 is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness)
799 ).find(|result| result.is_useful()).unwrap_or(NotUseful)
801 debug!("is_useful - expanding wildcard");
803 let used_ctors: Vec<Constructor> = rows.iter().flat_map(|row| {
804 pat_constructors(cx, row[0], pcx).unwrap_or(vec![])
806 debug!("used_ctors = {:#?}", used_ctors);
807 // `all_ctors` are all the constructors for the given type, which
808 // should all be represented (or caught with the wild pattern `_`).
809 let all_ctors = all_constructors(cx, pcx);
810 debug!("all_ctors = {:#?}", all_ctors);
812 // The only constructor patterns for which it is valid to
813 // treat the values as constructors are ranges (see
814 // `all_constructors` for details).
815 let exhaustive_integer_patterns = cx.tcx.features().exhaustive_integer_patterns;
816 let consider_value_constructors = exhaustive_integer_patterns
817 && all_ctors.iter().all(|ctor| match ctor {
818 ConstantRange(..) => true,
822 // `missing_ctors` are those that should have appeared
823 // as patterns in the `match` expression, but did not.
824 let mut missing_ctors = vec![];
825 for req_ctor in &all_ctors {
826 if consider_value_constructors {
827 let mut refined_ctors = vec![req_ctor.clone()];
828 for used_ctor in &used_ctors {
829 // Refine the required constructors for the type by subtracting
830 // the range defined by the current constructor pattern.
831 refined_ctors = match IntRange::from_ctor(cx.tcx, used_ctor) {
832 Some(interval) => interval.subtract_from(cx.tcx, refined_ctors),
833 None => refined_ctors,
835 // If the constructor patterns that have been considered so far
836 // already cover the entire range of values, then we the
837 // constructor is not missing, and we can move on to the next one.
838 if refined_ctors.is_empty() {
842 // If a constructor has not been matched, then it is missing.
843 // We add `refined_ctors` instead of `req_ctor`, because then we can
844 // provide more detailed error information about precisely which
845 // ranges have been omitted.
846 missing_ctors.extend(refined_ctors);
848 // A constructor is missing if it never appears in a `match` arm.
849 if !used_ctors.iter().any(|used_ctor| used_ctor == req_ctor) {
850 missing_ctors.push(req_ctor.clone());
855 // `missing_ctors` is the set of constructors from the same type as the
856 // first column of `matrix` that are matched only by wildcard patterns
857 // from the first column.
859 // Therefore, if there is some pattern that is unmatched by `matrix`,
860 // it will still be unmatched if the first constructor is replaced by
861 // any of the constructors in `missing_ctors`
863 // However, if our scrutinee is *privately* an empty enum, we
864 // must treat it as though it had an "unknown" constructor (in
865 // that case, all other patterns obviously can't be variants)
866 // to avoid exposing its emptyness. See the `match_privately_empty`
869 // FIXME: currently the only way I know of something can
870 // be a privately-empty enum is when the exhaustive_patterns
871 // feature flag is not present, so this is only
872 // needed for that case.
874 let is_privately_empty =
875 all_ctors.is_empty() && !cx.is_uninhabited(pcx.ty);
876 let is_declared_nonexhaustive =
877 cx.is_non_exhaustive_enum(pcx.ty) && !cx.is_local(pcx.ty);
878 debug!("missing_ctors={:#?} is_privately_empty={:#?} is_declared_nonexhaustive={:#?}",
879 missing_ctors, is_privately_empty, is_declared_nonexhaustive);
881 // For privately empty and non-exhaustive enums, we work as if there were an "extra"
882 // `_` constructor for the type, so we can never match over all constructors.
883 let is_non_exhaustive = is_privately_empty || is_declared_nonexhaustive;
885 if missing_ctors.is_empty() && !is_non_exhaustive {
886 if consider_value_constructors {
887 // If we've successfully matched every value
888 // of the type, then we're done.
891 all_ctors.into_iter().map(|c| {
892 is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness)
893 }).find(|result| result.is_useful()).unwrap_or(NotUseful)
896 let matrix = rows.iter().filter_map(|r| {
897 if r[0].is_wildcard() {
898 Some(r[1..].to_vec())
903 match is_useful(cx, &matrix, &v[1..], witness) {
904 UsefulWithWitness(pats) => {
906 // In this case, there's at least one "free"
907 // constructor that is only matched against by
908 // wildcard patterns.
910 // There are 2 ways we can report a witness here.
911 // Commonly, we can report all the "free"
912 // constructors as witnesses, e.g. if we have:
915 // enum Direction { N, S, E, W }
916 // let Direction::N = ...;
919 // we can report 3 witnesses: `S`, `E`, and `W`.
921 // However, there are 2 cases where we don't want
922 // to do this and instead report a single `_` witness:
924 // 1) If the user is matching against a non-exhaustive
925 // enum, there is no point in enumerating all possible
926 // variants, because the user can't actually match
927 // against them himself, e.g. in an example like:
929 // let err: io::ErrorKind = ...;
931 // io::ErrorKind::NotFound => {},
934 // we don't want to show every possible IO error,
935 // but instead have `_` as the witness (this is
936 // actually *required* if the user specified *all*
937 // IO errors, but is probably what we want in every
940 // 2) If the user didn't actually specify a constructor
941 // in this arm, e.g. in
943 // let x: (Direction, Direction, bool) = ...;
944 // let (_, _, false) = x;
946 // we don't want to show all 16 possible witnesses
947 // `(<direction-1>, <direction-2>, true)` - we are
948 // satisfied with `(_, _, true)`. In this case,
949 // `used_ctors` is empty.
950 let new_witnesses = if is_non_exhaustive || used_ctors.is_empty() {
951 // All constructors are unused. Add wild patterns
952 // rather than each individual constructor
953 pats.into_iter().map(|mut witness| {
954 witness.0.push(Pattern {
957 kind: box PatternKind::Wild,
962 if consider_value_constructors {
963 // If we've been trying to exhaustively match
964 // over the domain of values for a type,
965 // then we can provide better diagnostics
966 // regarding which values were missing.
967 missing_ctors.into_iter().map(|ctor| {
969 // A constant range of length 1 is simply
971 ConstantValue(value) => {
972 Witness(vec![Pattern {
975 kind: box PatternKind::Constant { value },
978 // We always report missing intervals
979 // in terms of inclusive ranges.
980 ConstantRange(lo, hi, end) => {
981 Witness(vec![Pattern {
984 kind: box PatternKind::Range { lo, hi, end },
987 _ => bug!("`ranges_subtract_pattern` should only produce \
992 pats.into_iter().flat_map(|witness| {
993 missing_ctors.iter().map(move |ctor| {
994 witness.clone().push_wild_constructor(cx, ctor, pcx.ty)
999 UsefulWithWitness(new_witnesses)
1007 fn is_useful_specialized<'p, 'a:'p, 'tcx: 'a>(
1008 cx: &mut MatchCheckCtxt<'a, 'tcx>,
1009 &Matrix(ref m): &Matrix<'p, 'tcx>,
1010 v: &[&'p Pattern<'tcx>],
1011 ctor: Constructor<'tcx>,
1013 witness: WitnessPreference) -> Usefulness<'tcx>
1015 debug!("is_useful_specialized({:#?}, {:#?}, {:?})", v, ctor, lty);
1016 let sub_pat_tys = constructor_sub_pattern_tys(cx, &ctor, lty);
1017 let wild_patterns_owned: Vec<_> = sub_pat_tys.iter().map(|ty| {
1021 kind: box PatternKind::Wild,
1024 let wild_patterns: Vec<_> = wild_patterns_owned.iter().collect();
1025 let matrix = Matrix(m.iter().flat_map(|r| {
1026 specialize(cx, &r, &ctor, &wild_patterns)
1028 match specialize(cx, v, &ctor, &wild_patterns) {
1029 Some(v) => match is_useful(cx, &matrix, &v, witness) {
1030 UsefulWithWitness(witnesses) => UsefulWithWitness(
1031 witnesses.into_iter()
1032 .map(|witness| witness.apply_constructor(cx, &ctor, lty))
1041 /// Determines the constructors that the given pattern can be specialized to.
1043 /// In most cases, there's only one constructor that a specific pattern
1044 /// represents, such as a specific enum variant or a specific literal value.
1045 /// Slice patterns, however, can match slices of different lengths. For instance,
1046 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
1048 /// Returns None in case of a catch-all, which can't be specialized.
1049 fn pat_constructors<'tcx>(cx: &mut MatchCheckCtxt,
1050 pat: &Pattern<'tcx>,
1051 pcx: PatternContext)
1052 -> Option<Vec<Constructor<'tcx>>>
1055 PatternKind::Binding { .. } | PatternKind::Wild =>
1057 PatternKind::Leaf { .. } | PatternKind::Deref { .. } =>
1059 PatternKind::Variant { adt_def, variant_index, .. } =>
1060 Some(vec![Variant(adt_def.variants[variant_index].did)]),
1061 PatternKind::Constant { value } =>
1062 Some(vec![ConstantValue(value)]),
1063 PatternKind::Range { lo, hi, end } =>
1064 Some(vec![ConstantRange(lo, hi, end)]),
1065 PatternKind::Array { .. } => match pcx.ty.sty {
1066 ty::TyArray(_, length) => Some(vec![
1067 Slice(length.unwrap_usize(cx.tcx))
1069 _ => span_bug!(pat.span, "bad ty {:?} for array pattern", pcx.ty)
1071 PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
1072 let pat_len = prefix.len() as u64 + suffix.len() as u64;
1073 if slice.is_some() {
1074 Some((pat_len..pcx.max_slice_length+1).map(Slice).collect())
1076 Some(vec![Slice(pat_len)])
1082 /// This computes the arity of a constructor. The arity of a constructor
1083 /// is how many subpattern patterns of that constructor should be expanded to.
1085 /// For instance, a tuple pattern (_, 42, Some([])) has the arity of 3.
1086 /// A struct pattern's arity is the number of fields it contains, etc.
1087 fn constructor_arity(_cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> u64 {
1088 debug!("constructor_arity({:#?}, {:?})", ctor, ty);
1090 ty::TyTuple(ref fs) => fs.len() as u64,
1091 ty::TySlice(..) | ty::TyArray(..) => match *ctor {
1092 Slice(length) => length,
1093 ConstantValue(_) => 0,
1094 _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
1097 ty::TyAdt(adt, _) => {
1098 adt.variants[ctor.variant_index_for_adt(adt)].fields.len() as u64
1104 /// This computes the types of the sub patterns that a constructor should be
1107 /// For instance, a tuple pattern (43u32, 'a') has sub pattern types [u32, char].
1108 fn constructor_sub_pattern_tys<'a, 'tcx: 'a>(cx: &MatchCheckCtxt<'a, 'tcx>,
1110 ty: Ty<'tcx>) -> Vec<Ty<'tcx>>
1112 debug!("constructor_sub_pattern_tys({:#?}, {:?})", ctor, ty);
1114 ty::TyTuple(ref fs) => fs.into_iter().map(|t| *t).collect(),
1115 ty::TySlice(ty) | ty::TyArray(ty, _) => match *ctor {
1116 Slice(length) => (0..length).map(|_| ty).collect(),
1117 ConstantValue(_) => vec![],
1118 _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
1120 ty::TyRef(_, rty, _) => vec![rty],
1121 ty::TyAdt(adt, substs) => {
1123 // Use T as the sub pattern type of Box<T>.
1124 vec![substs.type_at(0)]
1126 adt.variants[ctor.variant_index_for_adt(adt)].fields.iter().map(|field| {
1127 let is_visible = adt.is_enum()
1128 || field.vis.is_accessible_from(cx.module, cx.tcx);
1130 field.ty(cx.tcx, substs)
1132 // Treat all non-visible fields as TyErr. They
1133 // can't appear in any other pattern from
1134 // this match (because they are private),
1135 // so their type does not matter - but
1136 // we don't want to know they are
1147 fn slice_pat_covered_by_constructor<'tcx>(
1148 tcx: TyCtxt<'_, 'tcx, '_>,
1151 prefix: &[Pattern<'tcx>],
1152 slice: &Option<Pattern<'tcx>>,
1153 suffix: &[Pattern<'tcx>]
1154 ) -> Result<bool, ErrorReported> {
1155 let data: &[u8] = match *ctor {
1156 ConstantValue(const_val) => {
1157 let val = match const_val.val {
1158 ConstValue::Unevaluated(..) |
1159 ConstValue::ByRef(..) => bug!("unexpected ConstValue: {:?}", const_val),
1160 ConstValue::Scalar(val) | ConstValue::ScalarPair(val, _) => val,
1162 if let Ok(ptr) = val.to_ptr() {
1163 let is_array_ptr = const_val.ty
1164 .builtin_deref(true)
1165 .and_then(|t| t.ty.builtin_index())
1166 .map_or(false, |t| t == tcx.types.u8);
1167 assert!(is_array_ptr);
1168 tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id).bytes.as_ref()
1170 bug!("unexpected non-ptr ConstantValue")
1176 let pat_len = prefix.len() + suffix.len();
1177 if data.len() < pat_len || (slice.is_none() && data.len() > pat_len) {
1182 data[..prefix.len()].iter().zip(prefix).chain(
1183 data[data.len()-suffix.len()..].iter().zip(suffix))
1186 box PatternKind::Constant { value } => {
1187 let b = value.unwrap_bits(tcx, ty::ParamEnv::empty().and(pat.ty));
1188 assert_eq!(b as u8 as u128, b);
1200 fn constructor_covered_by_range<'a, 'tcx>(
1201 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1202 ctor: &Constructor<'tcx>,
1203 from: &'tcx ty::Const<'tcx>, to: &'tcx ty::Const<'tcx>,
1206 ) -> Result<bool, ErrorReported> {
1207 trace!("constructor_covered_by_range {:#?}, {:#?}, {:#?}, {}", ctor, from, to, ty);
1208 let cmp_from = |c_from| compare_const_vals(tcx, c_from, from, ty::ParamEnv::empty().and(ty))
1209 .map(|res| res != Ordering::Less);
1210 let cmp_to = |c_to| compare_const_vals(tcx, c_to, to, ty::ParamEnv::empty().and(ty));
1211 macro_rules! some_or_ok {
1215 None => return Ok(false), // not char or int
1220 ConstantValue(value) => {
1221 let to = some_or_ok!(cmp_to(value));
1222 let end = (to == Ordering::Less) ||
1223 (end == RangeEnd::Included && to == Ordering::Equal);
1224 Ok(some_or_ok!(cmp_from(value)) && end)
1226 ConstantRange(from, to, RangeEnd::Included) => {
1227 let to = some_or_ok!(cmp_to(to));
1228 let end = (to == Ordering::Less) ||
1229 (end == RangeEnd::Included && to == Ordering::Equal);
1230 Ok(some_or_ok!(cmp_from(from)) && end)
1232 ConstantRange(from, to, RangeEnd::Excluded) => {
1233 let to = some_or_ok!(cmp_to(to));
1234 let end = (to == Ordering::Less) ||
1235 (end == RangeEnd::Excluded && to == Ordering::Equal);
1236 Ok(some_or_ok!(cmp_from(from)) && end)
1243 fn patterns_for_variant<'p, 'a: 'p, 'tcx: 'a>(
1244 subpatterns: &'p [FieldPattern<'tcx>],
1245 wild_patterns: &[&'p Pattern<'tcx>])
1246 -> Vec<&'p Pattern<'tcx>>
1248 let mut result = wild_patterns.to_owned();
1250 for subpat in subpatterns {
1251 result[subpat.field.index()] = &subpat.pattern;
1254 debug!("patterns_for_variant({:#?}, {:#?}) = {:#?}", subpatterns, wild_patterns, result);
1258 /// This is the main specialization step. It expands the first pattern in the given row
1259 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
1260 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
1262 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
1263 /// different patterns.
1264 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
1265 /// fields filled with wild patterns.
1266 fn specialize<'p, 'a: 'p, 'tcx: 'a>(
1267 cx: &mut MatchCheckCtxt<'a, 'tcx>,
1268 r: &[&'p Pattern<'tcx>],
1269 constructor: &Constructor<'tcx>,
1270 wild_patterns: &[&'p Pattern<'tcx>])
1271 -> Option<Vec<&'p Pattern<'tcx>>>
1275 let head: Option<Vec<&Pattern>> = match *pat.kind {
1276 PatternKind::Binding { .. } | PatternKind::Wild => {
1277 Some(wild_patterns.to_owned())
1280 PatternKind::Variant { adt_def, variant_index, ref subpatterns, .. } => {
1281 let ref variant = adt_def.variants[variant_index];
1282 if *constructor == Variant(variant.did) {
1283 Some(patterns_for_variant(subpatterns, wild_patterns))
1289 PatternKind::Leaf { ref subpatterns } => {
1290 Some(patterns_for_variant(subpatterns, wild_patterns))
1293 PatternKind::Deref { ref subpattern } => {
1294 Some(vec![subpattern])
1297 PatternKind::Constant { value } => {
1298 match *constructor {
1300 if let Some(ptr) = value.to_ptr() {
1301 let is_array_ptr = value.ty
1302 .builtin_deref(true)
1303 .and_then(|t| t.ty.builtin_index())
1304 .map_or(false, |t| t == cx.tcx.types.u8);
1305 assert!(is_array_ptr);
1306 let data_len = cx.tcx
1309 .unwrap_memory(ptr.alloc_id)
1312 if wild_patterns.len() == data_len {
1313 Some(cx.lower_byte_str_pattern(pat))
1319 "unexpected const-val {:?} with ctor {:?}", value, constructor)
1323 match constructor_covered_by_range(
1325 constructor, value, value, RangeEnd::Included,
1328 Ok(true) => Some(vec![]),
1330 Err(ErrorReported) => None,
1336 PatternKind::Range { lo, hi, ref end } => {
1337 match constructor_covered_by_range(
1339 constructor, lo, hi, end.clone(), lo.ty,
1341 Ok(true) => Some(vec![]),
1343 Err(ErrorReported) => None,
1347 PatternKind::Array { ref prefix, ref slice, ref suffix } |
1348 PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
1349 match *constructor {
1351 let pat_len = prefix.len() + suffix.len();
1352 if let Some(slice_count) = wild_patterns.len().checked_sub(pat_len) {
1353 if slice_count == 0 || slice.is_some() {
1355 prefix.iter().chain(
1356 wild_patterns.iter().map(|p| *p)
1369 ConstantValue(..) => {
1370 match slice_pat_covered_by_constructor(
1371 cx.tcx, pat.span, constructor, prefix, slice, suffix
1373 Ok(true) => Some(vec![]),
1375 Err(ErrorReported) => None
1378 _ => span_bug!(pat.span,
1379 "unexpected ctor {:?} for slice pat", constructor)
1383 debug!("specialize({:#?}, {:#?}) = {:#?}", r[0], wild_patterns, head);
1385 head.map(|mut head| {
1386 head.extend_from_slice(&r[1 ..]);