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};
25 use rustc::mir::Field;
26 use rustc::mir::interpret::ConstValue;
27 use rustc::util::common::ErrorReported;
29 use syntax_pos::{Span, DUMMY_SP};
31 use arena::TypedArena;
33 use std::cmp::{self, Ordering};
35 use std::iter::{FromIterator, IntoIterator};
37 pub fn expand_pattern<'a, 'tcx>(cx: &MatchCheckCtxt<'a, 'tcx>, pat: Pattern<'tcx>)
40 cx.pattern_arena.alloc(LiteralExpander.fold_pattern(&pat))
43 struct LiteralExpander;
44 impl<'tcx> PatternFolder<'tcx> for LiteralExpander {
45 fn fold_pattern(&mut self, pat: &Pattern<'tcx>) -> Pattern<'tcx> {
46 match (&pat.ty.sty, &*pat.kind) {
47 (&ty::TyRef(_, rty, _), &PatternKind::Constant { ref value }) => {
51 kind: box PatternKind::Deref {
55 kind: box PatternKind::Constant { value: value.clone() },
60 (_, &PatternKind::Binding { subpattern: Some(ref s), .. }) => {
63 _ => pat.super_fold_with(self)
68 impl<'tcx> Pattern<'tcx> {
69 fn is_wildcard(&self) -> bool {
71 PatternKind::Binding { subpattern: None, .. } | PatternKind::Wild =>
78 pub struct Matrix<'a, 'tcx: 'a>(Vec<Vec<&'a Pattern<'tcx>>>);
80 impl<'a, 'tcx> Matrix<'a, 'tcx> {
81 pub fn empty() -> Self {
85 pub fn push(&mut self, row: Vec<&'a Pattern<'tcx>>) {
90 /// Pretty-printer for matrices of patterns, example:
91 /// ++++++++++++++++++++++++++
93 /// ++++++++++++++++++++++++++
94 /// + true + [First] +
95 /// ++++++++++++++++++++++++++
96 /// + true + [Second(true)] +
97 /// ++++++++++++++++++++++++++
99 /// ++++++++++++++++++++++++++
100 /// + _ + [_, _, ..tail] +
101 /// ++++++++++++++++++++++++++
102 impl<'a, 'tcx> fmt::Debug for Matrix<'a, 'tcx> {
103 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
106 let &Matrix(ref m) = self;
107 let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| {
108 row.iter().map(|pat| format!("{:?}", pat)).collect()
111 let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0);
112 assert!(m.iter().all(|row| row.len() == column_count));
113 let column_widths: Vec<usize> = (0..column_count).map(|col| {
114 pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0)
117 let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1;
118 let br = "+".repeat(total_width);
119 write!(f, "{}\n", br)?;
120 for row in pretty_printed_matrix {
122 for (column, pat_str) in row.into_iter().enumerate() {
124 write!(f, "{:1$}", pat_str, column_widths[column])?;
128 write!(f, "{}\n", br)?;
134 impl<'a, 'tcx> FromIterator<Vec<&'a Pattern<'tcx>>> for Matrix<'a, 'tcx> {
135 fn from_iter<T: IntoIterator<Item=Vec<&'a Pattern<'tcx>>>>(iter: T) -> Self
137 Matrix(iter.into_iter().collect())
141 pub struct MatchCheckCtxt<'a, 'tcx: 'a> {
142 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
143 /// The module in which the match occurs. This is necessary for
144 /// checking inhabited-ness of types because whether a type is (visibly)
145 /// inhabited can depend on whether it was defined in the current module or
146 /// not. eg. `struct Foo { _private: ! }` cannot be seen to be empty
147 /// outside it's module and should not be matchable with an empty match
150 pub pattern_arena: &'a TypedArena<Pattern<'tcx>>,
151 pub byte_array_map: FxHashMap<*const Pattern<'tcx>, Vec<&'a Pattern<'tcx>>>,
154 impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> {
155 pub fn create_and_enter<F, R>(
156 tcx: TyCtxt<'a, 'tcx, 'tcx>,
159 where F: for<'b> FnOnce(MatchCheckCtxt<'b, 'tcx>) -> R
161 let pattern_arena = TypedArena::new();
166 pattern_arena: &pattern_arena,
167 byte_array_map: FxHashMap(),
171 // convert a byte-string pattern to a list of u8 patterns.
172 fn lower_byte_str_pattern<'p>(&mut self, pat: &'p Pattern<'tcx>) -> Vec<&'p Pattern<'tcx>>
175 let pattern_arena = &*self.pattern_arena;
177 self.byte_array_map.entry(pat).or_insert_with(|| {
179 box PatternKind::Constant {
182 if let Some(ptr) = const_val.to_ptr() {
183 let is_array_ptr = const_val.ty
185 .and_then(|t| t.ty.builtin_index())
186 .map_or(false, |t| t == tcx.types.u8);
187 assert!(is_array_ptr);
188 let alloc = tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
189 assert_eq!(ptr.offset.bytes(), 0);
190 // FIXME: check length
191 alloc.bytes.iter().map(|b| {
192 &*pattern_arena.alloc(Pattern {
195 kind: box PatternKind::Constant {
196 value: ty::Const::from_bits(
199 ty::ParamEnv::empty().and(tcx.types.u8))
204 bug!("not a byte str: {:?}", const_val)
207 _ => span_bug!(pat.span, "unexpected byte array pattern {:?}", pat)
212 fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool {
213 if self.tcx.features().exhaustive_patterns {
214 self.tcx.is_ty_uninhabited_from(self.module, ty)
220 fn is_non_exhaustive_enum(&self, ty: Ty<'tcx>) -> bool {
222 ty::TyAdt(adt_def, ..) => adt_def.is_enum() && adt_def.is_non_exhaustive(),
227 fn is_local(&self, ty: Ty<'tcx>) -> bool {
229 ty::TyAdt(adt_def, ..) => adt_def.did.is_local(),
234 fn is_variant_uninhabited(&self,
235 variant: &'tcx ty::VariantDef,
236 substs: &'tcx ty::subst::Substs<'tcx>)
239 if self.tcx.features().exhaustive_patterns {
240 self.tcx.is_enum_variant_uninhabited_from(self.module, variant, substs)
247 #[derive(Clone, Debug, PartialEq)]
248 pub enum Constructor<'tcx> {
249 /// The constructor of all patterns that don't vary by constructor,
250 /// e.g. struct patterns and fixed-length arrays.
255 ConstantValue(&'tcx ty::Const<'tcx>),
256 /// Ranges of literal values (`2...5` and `2..5`).
257 ConstantRange(&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>, RangeEnd),
258 /// Array patterns of length n.
262 impl<'tcx> Constructor<'tcx> {
263 fn variant_index_for_adt(&self, adt: &'tcx ty::AdtDef) -> usize {
265 &Variant(vid) => adt.variant_index_with_id(vid),
267 assert!(!adt.is_enum());
270 _ => bug!("bad constructor {:?} for adt {:?}", self, adt)
276 pub enum Usefulness<'tcx> {
278 UsefulWithWitness(Vec<Witness<'tcx>>),
282 impl<'tcx> Usefulness<'tcx> {
283 fn is_useful(&self) -> bool {
291 #[derive(Copy, Clone)]
292 pub enum WitnessPreference {
297 #[derive(Copy, Clone, Debug)]
298 struct PatternContext<'tcx> {
300 max_slice_length: u64,
303 /// A stack of patterns in reverse order of construction
305 pub struct Witness<'tcx>(Vec<Pattern<'tcx>>);
307 impl<'tcx> Witness<'tcx> {
308 pub fn single_pattern(&self) -> &Pattern<'tcx> {
309 assert_eq!(self.0.len(), 1);
313 fn push_wild_constructor<'a>(
315 cx: &MatchCheckCtxt<'a, 'tcx>,
316 ctor: &Constructor<'tcx>,
320 let sub_pattern_tys = constructor_sub_pattern_tys(cx, ctor, ty);
321 self.0.extend(sub_pattern_tys.into_iter().map(|ty| {
325 kind: box PatternKind::Wild,
328 self.apply_constructor(cx, ctor, ty)
332 /// Constructs a partial witness for a pattern given a list of
333 /// patterns expanded by the specialization step.
335 /// When a pattern P is discovered to be useful, this function is used bottom-up
336 /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
337 /// of values, V, where each value in that set is not covered by any previously
338 /// used patterns and is covered by the pattern P'. Examples:
340 /// left_ty: tuple of 3 elements
341 /// pats: [10, 20, _] => (10, 20, _)
343 /// left_ty: struct X { a: (bool, &'static str), b: usize}
344 /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 }
345 fn apply_constructor<'a>(
347 cx: &MatchCheckCtxt<'a,'tcx>,
348 ctor: &Constructor<'tcx>,
352 let arity = constructor_arity(cx, ctor, ty);
354 let len = self.0.len() as u64;
355 let mut pats = self.0.drain((len-arity) as usize..).rev();
360 let pats = pats.enumerate().map(|(i, p)| {
362 field: Field::new(i),
367 if let ty::TyAdt(adt, substs) = ty.sty {
369 PatternKind::Variant {
372 variant_index: ctor.variant_index_for_adt(adt),
376 PatternKind::Leaf { subpatterns: pats }
379 PatternKind::Leaf { subpatterns: pats }
384 PatternKind::Deref { subpattern: pats.nth(0).unwrap() }
387 ty::TySlice(_) | ty::TyArray(..) => {
389 prefix: pats.collect(),
397 ConstantValue(value) => PatternKind::Constant { value },
398 _ => PatternKind::Wild,
404 self.0.push(Pattern {
414 /// This determines the set of all possible constructors of a pattern matching
415 /// values of type `left_ty`. For vectors, this would normally be an infinite set
416 /// but is instead bounded by the maximum fixed length of slice patterns in
417 /// the column of patterns being analyzed.
419 /// This intentionally does not list ConstantValue specializations for
420 /// non-booleans, because we currently assume that there is always a
421 /// "non-standard constant" that matches. See issue #12483.
423 /// We make sure to omit constructors that are statically impossible. eg for
424 /// Option<!> we do not include Some(_) in the returned list of constructors.
425 fn all_constructors<'a, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
426 pcx: PatternContext<'tcx>)
427 -> (Vec<Constructor<'tcx>>, bool)
429 debug!("all_constructors({:?})", pcx.ty);
430 let exhaustive_integer_patterns = cx.tcx.features().exhaustive_integer_patterns;
431 let mut value_constructors = false;
432 let ctors = match pcx.ty.sty {
434 [true, false].iter().map(|&b| {
435 ConstantValue(ty::Const::from_bool(cx.tcx, b))
438 ty::TyArray(ref sub_ty, len) if len.assert_usize(cx.tcx).is_some() => {
439 let len = len.unwrap_usize(cx.tcx);
440 if len != 0 && cx.is_uninhabited(sub_ty) {
446 // Treat arrays of a constant but unknown length like slices.
447 ty::TyArray(ref sub_ty, _) |
448 ty::TySlice(ref sub_ty) => {
449 if cx.is_uninhabited(sub_ty) {
452 (0..pcx.max_slice_length+1).map(|length| Slice(length)).collect()
455 ty::TyAdt(def, substs) if def.is_enum() => {
457 .filter(|v| !cx.is_variant_uninhabited(v, substs))
458 .map(|v| Variant(v.did))
461 ty::TyChar if exhaustive_integer_patterns => {
462 let endpoint = |c: char| {
463 ty::Const::from_bits(cx.tcx, c as u128, cx.tcx.types.char)
465 value_constructors = true;
467 // The valid Unicode Scalar Value ranges.
468 ConstantRange(endpoint('\u{0000}'), endpoint('\u{D7FF}'), RangeEnd::Included),
469 ConstantRange(endpoint('\u{E000}'), endpoint('\u{10FFFF}'), RangeEnd::Included),
472 ty::TyInt(_) if exhaustive_integer_patterns => {
473 let size = cx.tcx.layout_of(ty::ParamEnv::reveal_all().and(pcx.ty))
474 .unwrap().size.bits() as u128;
475 let min = (1u128 << (size - 1)).wrapping_neg();
476 let max = (1u128 << (size - 1)).wrapping_sub(1);
477 value_constructors = true;
478 vec![ConstantRange(ty::Const::from_bits(cx.tcx, min as u128, pcx.ty),
479 ty::Const::from_bits(cx.tcx, max as u128, pcx.ty),
482 ty::TyUint(_) if exhaustive_integer_patterns => {
483 let size = cx.tcx.layout_of(ty::ParamEnv::reveal_all().and(pcx.ty))
484 .unwrap().size.bits() as u32;
485 let shift = 1u128.overflowing_shl(size);
486 let max = shift.0.wrapping_sub(1 + (shift.1 as u128));
487 value_constructors = true;
488 vec![ConstantRange(ty::Const::from_bits(cx.tcx, 0u128, pcx.ty),
489 ty::Const::from_bits(cx.tcx, max as u128, pcx.ty),
493 if cx.is_uninhabited(pcx.ty) {
500 (ctors, value_constructors)
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 /// `Interval`s always store a contiguous range of integers. That means that
607 /// signed integers are offset (see `offset_sign`) by their minimum value.
608 struct Interval<'tcx> {
609 pub range: RangeInclusive<u128>,
613 impl<'tcx> Interval<'tcx> {
614 fn from_ctor(tcx: TyCtxt<'_, 'tcx, 'tcx>,
615 ctor: &Constructor<'tcx>)
616 -> Option<Interval<'tcx>> {
618 ConstantRange(lo, hi, end) => {
619 assert_eq!(lo.ty, hi.ty);
621 if let Some(lo) = lo.assert_bits(ty) {
622 if let Some(hi) = hi.assert_bits(ty) {
623 // Perform a shift if the underlying types are signed,
624 // which makes the interval arithmetic simpler.
625 let (lo, hi) = Self::offset_sign(tcx, ty, lo..=hi, true);
626 // Make sure the interval is well-formed.
627 return if lo > hi || lo == hi && *end == RangeEnd::Excluded {
630 let offset = (*end == RangeEnd::Excluded) as u128;
631 Some(Interval { range: lo..=(hi - offset), ty })
637 ConstantValue(val) => {
639 if let Some(val) = val.assert_bits(ty) {
640 let (lo, hi) = Self::offset_sign(tcx, ty, val..=val, true);
641 Some(Interval { range: lo..=hi, ty })
646 Single | Variant(_) | Slice(_) => {
652 fn offset_sign(tcx: TyCtxt<'_, 'tcx, 'tcx>,
654 range: RangeInclusive<u128>,
657 // We ensure that all integer values are contiguous: that is, that their
658 // minimum value is represented by 0, so that comparisons and increments/
659 // decrements on interval endpoints work consistently whether the endpoints
660 // are signed or unsigned.
661 let (lo, hi) = range.into_inner();
664 let size = tcx.layout_of(ty::ParamEnv::reveal_all().and(ty))
665 .unwrap().size.bits() as u128;
666 let min = (1u128 << (size - 1)).wrapping_neg();
667 let shift = 1u128.overflowing_shl(size as u32);
668 let mask = shift.0.wrapping_sub(1 + (shift.1 as u128));
670 let offset = |x: u128| x.wrapping_sub(min) & mask;
671 (offset(lo), offset(hi))
673 let offset = |x: u128| {
674 interpret::sign_extend(tcx, x.wrapping_add(min) & mask, ty)
675 .expect("layout error for TyInt")
677 (offset(lo), offset(hi))
680 ty::TyUint(_) | ty::TyChar => {
683 _ => bug!("`Interval` should only contain integer types")
687 fn into_inner(self) -> (u128, u128) {
688 self.range.into_inner()
692 /// Given a pattern in a `match` and a collection of ranges corresponding to the
693 /// domain of values of a type (say, an integer), return a new collection of ranges
694 /// corresponding to those ranges minus the ranges covered by the pattern.
695 fn ranges_subtract_pattern<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
696 pat_ctor: &Constructor<'tcx>,
697 ranges: Vec<Constructor<'tcx>>)
698 -> Vec<Constructor<'tcx>> {
699 if let Some(pat_interval) = Interval::from_ctor(cx.tcx, pat_ctor) {
700 let mut remaining_ranges = vec![];
701 let mut ranges: Vec<_> = ranges.into_iter().filter_map(|r| {
702 Interval::from_ctor(cx.tcx, &r).map(|i| i.into_inner())
704 let ty = pat_interval.ty;
705 let (pat_interval_lo, pat_interval_hi) = pat_interval.into_inner();
706 for (subrange_lo, subrange_hi) in ranges {
707 if pat_interval_lo > subrange_hi || subrange_lo > pat_interval_hi {
708 // The pattern doesn't intersect with the subrange at all,
709 // so the subrange remains untouched.
710 remaining_ranges.push(subrange_lo..=subrange_hi);
712 if pat_interval_lo > subrange_lo {
713 // The pattern intersects an upper section of the
714 // subrange, so a lower section will remain.
715 remaining_ranges.push(subrange_lo..=(pat_interval_lo - 1));
717 if pat_interval_hi < subrange_hi {
718 // The pattern intersects a lower section of the
719 // subrange, so an upper section will remain.
720 remaining_ranges.push((pat_interval_hi + 1)..=subrange_hi);
724 // Convert the remaining ranges from pairs to inclusive `ConstantRange`s.
725 remaining_ranges.into_iter().map(|r| {
726 let (lo, hi) = Interval::offset_sign(cx.tcx, ty, r, false);
727 ConstantRange(ty::Const::from_bits(cx.tcx, lo, ty),
728 ty::Const::from_bits(cx.tcx, hi, ty),
736 /// Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
737 /// The algorithm from the paper has been modified to correctly handle empty
738 /// types. The changes are:
739 /// (0) We don't exit early if the pattern matrix has zero rows. We just
740 /// continue to recurse over columns.
741 /// (1) all_constructors will only return constructors that are statically
742 /// possible. eg. it will only return Ok for Result<T, !>
744 /// This finds whether a (row) vector `v` of patterns is 'useful' in relation
745 /// to a set of such vectors `m` - this is defined as there being a set of
746 /// inputs that will match `v` but not any of the sets in `m`.
748 /// All the patterns at each column of the `matrix ++ v` matrix must
749 /// have the same type, except that wildcard (PatternKind::Wild) patterns
750 /// with type TyErr are also allowed, even if the "type of the column"
751 /// is not TyErr. That is used to represent private fields, as using their
752 /// real type would assert that they are inhabited.
754 /// This is used both for reachability checking (if a pattern isn't useful in
755 /// relation to preceding patterns, it is not reachable) and exhaustiveness
756 /// checking (if a wildcard pattern is useful in relation to a matrix, the
757 /// matrix isn't exhaustive).
758 pub fn is_useful<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
759 matrix: &Matrix<'p, 'tcx>,
760 v: &[&'p Pattern<'tcx>],
761 witness: WitnessPreference)
762 -> Usefulness<'tcx> {
763 let &Matrix(ref rows) = matrix;
764 debug!("is_useful({:#?}, {:#?})", matrix, v);
766 // The base case. We are pattern-matching on () and the return value is
767 // based on whether our matrix has a row or not.
768 // NOTE: This could potentially be optimized by checking rows.is_empty()
769 // first and then, if v is non-empty, the return value is based on whether
770 // the type of the tuple we're checking is inhabited or not.
772 return if rows.is_empty() {
774 ConstructWitness => UsefulWithWitness(vec![Witness(vec![])]),
775 LeaveOutWitness => Useful,
782 assert!(rows.iter().all(|r| r.len() == v.len()));
784 let pcx = PatternContext {
785 // TyErr is used to represent the type of wildcard patterns matching
786 // against inaccessible (private) fields of structs, so that we won't
787 // be able to observe whether the types of the struct's fields are
790 // If the field is truly inaccessible, then all the patterns
791 // matching against it must be wildcard patterns, so its type
794 // However, if we are matching against non-wildcard patterns, we
795 // need to know the real type of the field so we can specialize
796 // against it. This primarily occurs through constants - they
797 // can include contents for fields that are inaccessible at the
798 // location of the match. In that case, the field's type is
799 // inhabited - by the constant - so we can just use it.
801 // FIXME: this might lead to "unstable" behavior with macro hygiene
802 // introducing uninhabited patterns for inaccessible fields. We
803 // need to figure out how to model that.
804 ty: rows.iter().map(|r| r[0].ty).find(|ty| !ty.references_error())
806 max_slice_length: max_slice_length(cx, rows.iter().map(|r| r[0]).chain(Some(v[0])))
809 debug!("is_useful_expand_first_col: pcx={:#?}, expanding {:#?}", pcx, v[0]);
811 if let Some(constructors) = pat_constructors(cx, v[0], pcx) {
812 debug!("is_useful - expanding constructors: {:#?}", constructors);
813 constructors.into_iter().map(|c|
814 is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness)
815 ).find(|result| result.is_useful()).unwrap_or(NotUseful)
817 debug!("is_useful - expanding wildcard");
819 let used_ctors: Vec<Constructor> = rows.iter().flat_map(|row| {
820 pat_constructors(cx, row[0], pcx).unwrap_or(vec![])
822 debug!("used_ctors = {:#?}", used_ctors);
823 // `all_ctors` are all the constructors for the given type, which
824 // should all be represented (or caught with the wild pattern `_`).
825 // `value_constructors` is true if we may exhaustively consider all
826 // the possible values (e.g. integers) of a type as its constructors.
827 let (all_ctors, value_constructors) = all_constructors(cx, pcx);
828 debug!("all_ctors = {:#?}", all_ctors);
830 // `missing_ctors` are those that should have appeared
831 // as patterns in the `match` expression, but did not.
832 let mut missing_ctors = vec![];
833 'req: for req_ctor in &all_ctors {
834 let mut sub_ctors = vec![req_ctor.clone()];
835 // The only constructor patterns for which it is valid to
836 // treat the values as constructors are ranges (see
837 // `all_constructors` for details).
838 let consider_value_constructors = value_constructors && match req_ctor {
839 ConstantRange(..) => true,
842 for used_ctor in &used_ctors {
843 if consider_value_constructors {
844 sub_ctors = ranges_subtract_pattern(cx, used_ctor, sub_ctors);
845 // If the constructor patterns that have been considered so far
846 // already cover the entire range of values, then we the
847 // constructor is not missing, and we can move on to the next one.
848 if sub_ctors.is_empty() {
852 // If the pattern for the required constructor
853 // appears in the `match`, then it is not missing,
854 // and we can move on to the next one.
855 if used_ctor == req_ctor {
860 // If a constructor has not been matched, then it is missing.
861 // We add `sub_ctors` instead of `req_ctor`, because then we can
862 // provide more detailed error information about precisely which
863 // ranges have been omitted.
864 missing_ctors.extend(sub_ctors);
867 // `missing_ctors` is the set of constructors from the same type as the
868 // first column of `matrix` that are matched only by wildcard patterns
869 // from the first column.
871 // Therefore, if there is some pattern that is unmatched by `matrix`,
872 // it will still be unmatched if the first constructor is replaced by
873 // any of the constructors in `missing_ctors`
875 // However, if our scrutinee is *privately* an empty enum, we
876 // must treat it as though it had an "unknown" constructor (in
877 // that case, all other patterns obviously can't be variants)
878 // to avoid exposing its emptyness. See the `match_privately_empty`
881 // FIXME: currently the only way I know of something can
882 // be a privately-empty enum is when the exhaustive_patterns
883 // feature flag is not present, so this is only
884 // needed for that case.
886 let is_privately_empty =
887 all_ctors.is_empty() && !cx.is_uninhabited(pcx.ty);
888 let is_declared_nonexhaustive =
889 cx.is_non_exhaustive_enum(pcx.ty) && !cx.is_local(pcx.ty);
890 debug!("missing_ctors={:#?} is_privately_empty={:#?} is_declared_nonexhaustive={:#?}",
891 missing_ctors, is_privately_empty, is_declared_nonexhaustive);
893 // For privately empty and non-exhaustive enums, we work as if there were an "extra"
894 // `_` constructor for the type, so we can never match over all constructors.
895 let is_non_exhaustive = is_privately_empty || is_declared_nonexhaustive;
897 if missing_ctors.is_empty() && !is_non_exhaustive {
898 if value_constructors {
899 // If we've successfully matched every value
900 // of the type, then we're done.
903 all_ctors.into_iter().map(|c| {
904 is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness)
905 }).find(|result| result.is_useful()).unwrap_or(NotUseful)
908 let matrix = rows.iter().filter_map(|r| {
909 if r[0].is_wildcard() {
910 Some(r[1..].to_vec())
915 match is_useful(cx, &matrix, &v[1..], witness) {
916 UsefulWithWitness(pats) => {
918 // In this case, there's at least one "free"
919 // constructor that is only matched against by
920 // wildcard patterns.
922 // There are 2 ways we can report a witness here.
923 // Commonly, we can report all the "free"
924 // constructors as witnesses, e.g. if we have:
927 // enum Direction { N, S, E, W }
928 // let Direction::N = ...;
931 // we can report 3 witnesses: `S`, `E`, and `W`.
933 // However, there are 2 cases where we don't want
934 // to do this and instead report a single `_` witness:
936 // 1) If the user is matching against a non-exhaustive
937 // enum, there is no point in enumerating all possible
938 // variants, because the user can't actually match
939 // against them himself, e.g. in an example like:
941 // let err: io::ErrorKind = ...;
943 // io::ErrorKind::NotFound => {},
946 // we don't want to show every possible IO error,
947 // but instead have `_` as the witness (this is
948 // actually *required* if the user specified *all*
949 // IO errors, but is probably what we want in every
952 // 2) If the user didn't actually specify a constructor
953 // in this arm, e.g. in
955 // let x: (Direction, Direction, bool) = ...;
956 // let (_, _, false) = x;
958 // we don't want to show all 16 possible witnesses
959 // `(<direction-1>, <direction-2>, true)` - we are
960 // satisfied with `(_, _, true)`. In this case,
961 // `used_ctors` is empty.
962 let new_witnesses = if is_non_exhaustive || used_ctors.is_empty() {
963 // All constructors are unused. Add wild patterns
964 // rather than each individual constructor
965 pats.into_iter().map(|mut witness| {
966 witness.0.push(Pattern {
969 kind: box PatternKind::Wild,
974 if value_constructors {
975 // If we've been trying to exhaustively match
976 // over the domain of values for a type,
977 // then we can provide better diagnostics
978 // regarding which values were missing.
979 missing_ctors.into_iter().map(|ctor| {
981 // A constant range of length 1 is simply
983 ConstantRange(lo, hi, _) if lo == hi => {
984 Witness(vec![Pattern {
987 kind: box PatternKind::Constant { value: lo },
990 // We always report missing intervals
991 // in terms of inclusive ranges.
992 ConstantRange(lo, hi, end) => {
993 Witness(vec![Pattern {
996 kind: box PatternKind::Range { lo, hi, end },
999 _ => bug!("`ranges_subtract_pattern` should only produce \
1004 pats.into_iter().flat_map(|witness| {
1005 missing_ctors.iter().map(move |ctor| {
1006 witness.clone().push_wild_constructor(cx, ctor, pcx.ty)
1011 UsefulWithWitness(new_witnesses)
1019 fn is_useful_specialized<'p, 'a:'p, 'tcx: 'a>(
1020 cx: &mut MatchCheckCtxt<'a, 'tcx>,
1021 &Matrix(ref m): &Matrix<'p, 'tcx>,
1022 v: &[&'p Pattern<'tcx>],
1023 ctor: Constructor<'tcx>,
1025 witness: WitnessPreference) -> Usefulness<'tcx>
1027 debug!("is_useful_specialized({:#?}, {:#?}, {:?})", v, ctor, lty);
1028 let sub_pat_tys = constructor_sub_pattern_tys(cx, &ctor, lty);
1029 let wild_patterns_owned: Vec<_> = sub_pat_tys.iter().map(|ty| {
1033 kind: box PatternKind::Wild,
1036 let wild_patterns: Vec<_> = wild_patterns_owned.iter().collect();
1037 let matrix = Matrix(m.iter().flat_map(|r| {
1038 specialize(cx, &r, &ctor, &wild_patterns)
1040 match specialize(cx, v, &ctor, &wild_patterns) {
1041 Some(v) => match is_useful(cx, &matrix, &v, witness) {
1042 UsefulWithWitness(witnesses) => UsefulWithWitness(
1043 witnesses.into_iter()
1044 .map(|witness| witness.apply_constructor(cx, &ctor, lty))
1053 /// Determines the constructors that the given pattern can be specialized to.
1055 /// In most cases, there's only one constructor that a specific pattern
1056 /// represents, such as a specific enum variant or a specific literal value.
1057 /// Slice patterns, however, can match slices of different lengths. For instance,
1058 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
1060 /// Returns None in case of a catch-all, which can't be specialized.
1061 fn pat_constructors<'tcx>(cx: &mut MatchCheckCtxt,
1062 pat: &Pattern<'tcx>,
1063 pcx: PatternContext)
1064 -> Option<Vec<Constructor<'tcx>>>
1067 PatternKind::Binding { .. } | PatternKind::Wild =>
1069 PatternKind::Leaf { .. } | PatternKind::Deref { .. } =>
1071 PatternKind::Variant { adt_def, variant_index, .. } =>
1072 Some(vec![Variant(adt_def.variants[variant_index].did)]),
1073 PatternKind::Constant { value } =>
1074 Some(vec![ConstantValue(value)]),
1075 PatternKind::Range { lo, hi, end } =>
1076 Some(vec![ConstantRange(lo, hi, end)]),
1077 PatternKind::Array { .. } => match pcx.ty.sty {
1078 ty::TyArray(_, length) => Some(vec![
1079 Slice(length.unwrap_usize(cx.tcx))
1081 _ => span_bug!(pat.span, "bad ty {:?} for array pattern", pcx.ty)
1083 PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
1084 let pat_len = prefix.len() as u64 + suffix.len() as u64;
1085 if slice.is_some() {
1086 Some((pat_len..pcx.max_slice_length+1).map(Slice).collect())
1088 Some(vec![Slice(pat_len)])
1094 /// This computes the arity of a constructor. The arity of a constructor
1095 /// is how many subpattern patterns of that constructor should be expanded to.
1097 /// For instance, a tuple pattern (_, 42, Some([])) has the arity of 3.
1098 /// A struct pattern's arity is the number of fields it contains, etc.
1099 fn constructor_arity(_cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> u64 {
1100 debug!("constructor_arity({:#?}, {:?})", ctor, ty);
1102 ty::TyTuple(ref fs) => fs.len() as u64,
1103 ty::TySlice(..) | ty::TyArray(..) => match *ctor {
1104 Slice(length) => length,
1105 ConstantValue(_) => 0,
1106 _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
1109 ty::TyAdt(adt, _) => {
1110 adt.variants[ctor.variant_index_for_adt(adt)].fields.len() as u64
1116 /// This computes the types of the sub patterns that a constructor should be
1119 /// For instance, a tuple pattern (43u32, 'a') has sub pattern types [u32, char].
1120 fn constructor_sub_pattern_tys<'a, 'tcx: 'a>(cx: &MatchCheckCtxt<'a, 'tcx>,
1122 ty: Ty<'tcx>) -> Vec<Ty<'tcx>>
1124 debug!("constructor_sub_pattern_tys({:#?}, {:?})", ctor, ty);
1126 ty::TyTuple(ref fs) => fs.into_iter().map(|t| *t).collect(),
1127 ty::TySlice(ty) | ty::TyArray(ty, _) => match *ctor {
1128 Slice(length) => (0..length).map(|_| ty).collect(),
1129 ConstantValue(_) => vec![],
1130 _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
1132 ty::TyRef(_, rty, _) => vec![rty],
1133 ty::TyAdt(adt, substs) => {
1135 // Use T as the sub pattern type of Box<T>.
1136 vec![substs.type_at(0)]
1138 adt.variants[ctor.variant_index_for_adt(adt)].fields.iter().map(|field| {
1139 let is_visible = adt.is_enum()
1140 || field.vis.is_accessible_from(cx.module, cx.tcx);
1142 field.ty(cx.tcx, substs)
1144 // Treat all non-visible fields as TyErr. They
1145 // can't appear in any other pattern from
1146 // this match (because they are private),
1147 // so their type does not matter - but
1148 // we don't want to know they are
1159 fn slice_pat_covered_by_constructor<'tcx>(
1160 tcx: TyCtxt<'_, 'tcx, '_>,
1163 prefix: &[Pattern<'tcx>],
1164 slice: &Option<Pattern<'tcx>>,
1165 suffix: &[Pattern<'tcx>]
1166 ) -> Result<bool, ErrorReported> {
1167 let data: &[u8] = match *ctor {
1168 ConstantValue(const_val) => {
1169 let val = match const_val.val {
1170 ConstValue::Unevaluated(..) |
1171 ConstValue::ByRef(..) => bug!("unexpected ConstValue: {:?}", const_val),
1172 ConstValue::Scalar(val) | ConstValue::ScalarPair(val, _) => val,
1174 if let Ok(ptr) = val.to_ptr() {
1175 let is_array_ptr = const_val.ty
1176 .builtin_deref(true)
1177 .and_then(|t| t.ty.builtin_index())
1178 .map_or(false, |t| t == tcx.types.u8);
1179 assert!(is_array_ptr);
1180 tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id).bytes.as_ref()
1182 bug!("unexpected non-ptr ConstantValue")
1188 let pat_len = prefix.len() + suffix.len();
1189 if data.len() < pat_len || (slice.is_none() && data.len() > pat_len) {
1194 data[..prefix.len()].iter().zip(prefix).chain(
1195 data[data.len()-suffix.len()..].iter().zip(suffix))
1198 box PatternKind::Constant { value } => {
1199 let b = value.unwrap_bits(tcx, ty::ParamEnv::empty().and(pat.ty));
1200 assert_eq!(b as u8 as u128, b);
1212 fn constructor_covered_by_range<'a, 'tcx>(
1213 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1214 ctor: &Constructor<'tcx>,
1215 from: &'tcx ty::Const<'tcx>, to: &'tcx ty::Const<'tcx>,
1218 ) -> Result<bool, ErrorReported> {
1219 trace!("constructor_covered_by_range {:#?}, {:#?}, {:#?}, {}", ctor, from, to, ty);
1220 let cmp_from = |c_from| compare_const_vals(tcx, c_from, from, ty::ParamEnv::empty().and(ty))
1221 .map(|res| res != Ordering::Less);
1222 let cmp_to = |c_to| compare_const_vals(tcx, c_to, to, ty::ParamEnv::empty().and(ty));
1223 macro_rules! some_or_ok {
1227 None => return Ok(false), // not char or int
1232 ConstantValue(value) => {
1233 let to = some_or_ok!(cmp_to(value));
1234 let end = (to == Ordering::Less) ||
1235 (end == RangeEnd::Included && to == Ordering::Equal);
1236 Ok(some_or_ok!(cmp_from(value)) && end)
1238 ConstantRange(from, to, RangeEnd::Included) => {
1239 let to = some_or_ok!(cmp_to(to));
1240 let end = (to == Ordering::Less) ||
1241 (end == RangeEnd::Included && to == Ordering::Equal);
1242 Ok(some_or_ok!(cmp_from(from)) && end)
1244 ConstantRange(from, to, RangeEnd::Excluded) => {
1245 let to = some_or_ok!(cmp_to(to));
1246 let end = (to == Ordering::Less) ||
1247 (end == RangeEnd::Excluded && to == Ordering::Equal);
1248 Ok(some_or_ok!(cmp_from(from)) && end)
1255 fn patterns_for_variant<'p, 'a: 'p, 'tcx: 'a>(
1256 subpatterns: &'p [FieldPattern<'tcx>],
1257 wild_patterns: &[&'p Pattern<'tcx>])
1258 -> Vec<&'p Pattern<'tcx>>
1260 let mut result = wild_patterns.to_owned();
1262 for subpat in subpatterns {
1263 result[subpat.field.index()] = &subpat.pattern;
1266 debug!("patterns_for_variant({:#?}, {:#?}) = {:#?}", subpatterns, wild_patterns, result);
1270 /// This is the main specialization step. It expands the first pattern in the given row
1271 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
1272 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
1274 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
1275 /// different patterns.
1276 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
1277 /// fields filled with wild patterns.
1278 fn specialize<'p, 'a: 'p, 'tcx: 'a>(
1279 cx: &mut MatchCheckCtxt<'a, 'tcx>,
1280 r: &[&'p Pattern<'tcx>],
1281 constructor: &Constructor<'tcx>,
1282 wild_patterns: &[&'p Pattern<'tcx>])
1283 -> Option<Vec<&'p Pattern<'tcx>>>
1287 let head: Option<Vec<&Pattern>> = match *pat.kind {
1288 PatternKind::Binding { .. } | PatternKind::Wild => {
1289 Some(wild_patterns.to_owned())
1292 PatternKind::Variant { adt_def, variant_index, ref subpatterns, .. } => {
1293 let ref variant = adt_def.variants[variant_index];
1294 if *constructor == Variant(variant.did) {
1295 Some(patterns_for_variant(subpatterns, wild_patterns))
1301 PatternKind::Leaf { ref subpatterns } => {
1302 Some(patterns_for_variant(subpatterns, wild_patterns))
1305 PatternKind::Deref { ref subpattern } => {
1306 Some(vec![subpattern])
1309 PatternKind::Constant { value } => {
1310 match *constructor {
1312 if let Some(ptr) = value.to_ptr() {
1313 let is_array_ptr = value.ty
1314 .builtin_deref(true)
1315 .and_then(|t| t.ty.builtin_index())
1316 .map_or(false, |t| t == cx.tcx.types.u8);
1317 assert!(is_array_ptr);
1318 let data_len = cx.tcx
1321 .unwrap_memory(ptr.alloc_id)
1324 if wild_patterns.len() == data_len {
1325 Some(cx.lower_byte_str_pattern(pat))
1331 "unexpected const-val {:?} with ctor {:?}", value, constructor)
1335 match constructor_covered_by_range(
1337 constructor, value, value, RangeEnd::Included,
1340 Ok(true) => Some(vec![]),
1342 Err(ErrorReported) => None,
1348 PatternKind::Range { lo, hi, ref end } => {
1349 match constructor_covered_by_range(
1351 constructor, lo, hi, end.clone(), lo.ty,
1353 Ok(true) => Some(vec![]),
1355 Err(ErrorReported) => None,
1359 PatternKind::Array { ref prefix, ref slice, ref suffix } |
1360 PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
1361 match *constructor {
1363 let pat_len = prefix.len() + suffix.len();
1364 if let Some(slice_count) = wild_patterns.len().checked_sub(pat_len) {
1365 if slice_count == 0 || slice.is_some() {
1367 prefix.iter().chain(
1368 wild_patterns.iter().map(|p| *p)
1381 ConstantValue(..) => {
1382 match slice_pat_covered_by_constructor(
1383 cx.tcx, pat.span, constructor, prefix, slice, suffix
1385 Ok(true) => Some(vec![]),
1387 Err(ErrorReported) => None
1390 _ => span_bug!(pat.span,
1391 "unexpected ctor {:?} for slice pat", constructor)
1395 debug!("specialize({:#?}, {:#?}) = {:#?}", r[0], wild_patterns, head);
1397 head.map(|mut head| {
1398 head.extend_from_slice(&r[1 ..]);