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};
38 use std::ops::RangeInclusive;
40 pub fn expand_pattern<'a, 'tcx>(cx: &MatchCheckCtxt<'a, 'tcx>, pat: Pattern<'tcx>)
43 cx.pattern_arena.alloc(LiteralExpander.fold_pattern(&pat))
46 struct LiteralExpander;
47 impl<'tcx> PatternFolder<'tcx> for LiteralExpander {
48 fn fold_pattern(&mut self, pat: &Pattern<'tcx>) -> Pattern<'tcx> {
49 match (&pat.ty.sty, &*pat.kind) {
50 (&ty::TyRef(_, rty, _), &PatternKind::Constant { ref value }) => {
54 kind: box PatternKind::Deref {
58 kind: box PatternKind::Constant { value: value.clone() },
63 (_, &PatternKind::Binding { subpattern: Some(ref s), .. }) => {
66 _ => pat.super_fold_with(self)
71 impl<'tcx> Pattern<'tcx> {
72 fn is_wildcard(&self) -> bool {
74 PatternKind::Binding { subpattern: None, .. } | PatternKind::Wild =>
81 pub struct Matrix<'a, 'tcx: 'a>(Vec<Vec<&'a Pattern<'tcx>>>);
83 impl<'a, 'tcx> Matrix<'a, 'tcx> {
84 pub fn empty() -> Self {
88 pub fn push(&mut self, row: Vec<&'a Pattern<'tcx>>) {
93 /// Pretty-printer for matrices of patterns, example:
94 /// ++++++++++++++++++++++++++
96 /// ++++++++++++++++++++++++++
97 /// + true + [First] +
98 /// ++++++++++++++++++++++++++
99 /// + true + [Second(true)] +
100 /// ++++++++++++++++++++++++++
102 /// ++++++++++++++++++++++++++
103 /// + _ + [_, _, ..tail] +
104 /// ++++++++++++++++++++++++++
105 impl<'a, 'tcx> fmt::Debug for Matrix<'a, 'tcx> {
106 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
109 let &Matrix(ref m) = self;
110 let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| {
111 row.iter().map(|pat| format!("{:?}", pat)).collect()
114 let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0);
115 assert!(m.iter().all(|row| row.len() == column_count));
116 let column_widths: Vec<usize> = (0..column_count).map(|col| {
117 pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0)
120 let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1;
121 let br = "+".repeat(total_width);
122 write!(f, "{}\n", br)?;
123 for row in pretty_printed_matrix {
125 for (column, pat_str) in row.into_iter().enumerate() {
127 write!(f, "{:1$}", pat_str, column_widths[column])?;
131 write!(f, "{}\n", br)?;
137 impl<'a, 'tcx> FromIterator<Vec<&'a Pattern<'tcx>>> for Matrix<'a, 'tcx> {
138 fn from_iter<T: IntoIterator<Item=Vec<&'a Pattern<'tcx>>>>(iter: T) -> Self
140 Matrix(iter.into_iter().collect())
144 pub struct MatchCheckCtxt<'a, 'tcx: 'a> {
145 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
146 /// The module in which the match occurs. This is necessary for
147 /// checking inhabited-ness of types because whether a type is (visibly)
148 /// inhabited can depend on whether it was defined in the current module or
149 /// not. eg. `struct Foo { _private: ! }` cannot be seen to be empty
150 /// outside it's module and should not be matchable with an empty match
153 pub pattern_arena: &'a TypedArena<Pattern<'tcx>>,
154 pub byte_array_map: FxHashMap<*const Pattern<'tcx>, Vec<&'a Pattern<'tcx>>>,
157 impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> {
158 pub fn create_and_enter<F, R>(
159 tcx: TyCtxt<'a, 'tcx, 'tcx>,
162 where F: for<'b> FnOnce(MatchCheckCtxt<'b, 'tcx>) -> R
164 let pattern_arena = TypedArena::new();
169 pattern_arena: &pattern_arena,
170 byte_array_map: FxHashMap(),
174 // convert a byte-string pattern to a list of u8 patterns.
175 fn lower_byte_str_pattern<'p>(&mut self, pat: &'p Pattern<'tcx>) -> Vec<&'p Pattern<'tcx>>
178 let pattern_arena = &*self.pattern_arena;
180 self.byte_array_map.entry(pat).or_insert_with(|| {
182 box PatternKind::Constant {
185 if let Some(ptr) = const_val.to_ptr() {
186 let is_array_ptr = const_val.ty
188 .and_then(|t| t.ty.builtin_index())
189 .map_or(false, |t| t == tcx.types.u8);
190 assert!(is_array_ptr);
191 let alloc = tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
192 assert_eq!(ptr.offset.bytes(), 0);
193 // FIXME: check length
194 alloc.bytes.iter().map(|b| {
195 &*pattern_arena.alloc(Pattern {
198 kind: box PatternKind::Constant {
199 value: ty::Const::from_bits(
202 ty::ParamEnv::empty().and(tcx.types.u8))
207 bug!("not a byte str: {:?}", const_val)
210 _ => span_bug!(pat.span, "unexpected byte array pattern {:?}", pat)
215 fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool {
216 if self.tcx.features().exhaustive_patterns {
217 self.tcx.is_ty_uninhabited_from(self.module, ty)
223 fn is_non_exhaustive_enum(&self, ty: Ty<'tcx>) -> bool {
225 ty::TyAdt(adt_def, ..) => adt_def.is_enum() && adt_def.is_non_exhaustive(),
230 fn is_local(&self, ty: Ty<'tcx>) -> bool {
232 ty::TyAdt(adt_def, ..) => adt_def.did.is_local(),
237 fn is_variant_uninhabited(&self,
238 variant: &'tcx ty::VariantDef,
239 substs: &'tcx ty::subst::Substs<'tcx>)
242 if self.tcx.features().exhaustive_patterns {
243 self.tcx.is_enum_variant_uninhabited_from(self.module, variant, substs)
250 #[derive(Clone, Debug, PartialEq)]
251 pub enum Constructor<'tcx> {
252 /// The constructor of all patterns that don't vary by constructor,
253 /// e.g. struct patterns and fixed-length arrays.
258 ConstantValue(&'tcx ty::Const<'tcx>),
259 /// Ranges of literal values (`2...5` and `2..5`).
260 ConstantRange(&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>, RangeEnd),
261 /// Array patterns of length n.
265 impl<'tcx> Constructor<'tcx> {
266 fn variant_index_for_adt(&self, adt: &'tcx ty::AdtDef) -> usize {
268 &Variant(vid) => adt.variant_index_with_id(vid),
270 assert!(!adt.is_enum());
273 _ => bug!("bad constructor {:?} for adt {:?}", self, adt)
278 #[derive(Clone, Debug)]
279 pub enum Usefulness<'tcx> {
281 UsefulWithWitness(Vec<Witness<'tcx>>),
285 impl<'tcx> Usefulness<'tcx> {
286 fn is_useful(&self) -> bool {
294 #[derive(Copy, Clone, Debug)]
295 pub enum WitnessPreference {
300 #[derive(Copy, Clone, Debug)]
301 struct PatternContext<'tcx> {
303 max_slice_length: u64,
306 /// A witness of non-exhaustiveness for error reporting, represented
307 /// as a list of patterns (in reverse order of construction) with
308 /// wildcards inside to represent elements that can take any inhabitant
309 /// of the type as a value.
311 /// A witness against a list of patterns should have the same types
312 /// and length as the pattern matched against. Because Rust `match`
313 /// is always against a single pattern, at the end the witness will
314 /// have length 1, but in the middle of the algorithm, it can contain
315 /// multiple patterns.
317 /// For example, if we are constructing a witness for the match against
319 /// struct Pair(Option<(u32, u32)>, bool);
321 /// match (p: Pair) {
322 /// Pair(None, _) => {}
323 /// Pair(_, false) => {}
327 /// We'll perform the following steps:
328 /// 1. Start with an empty witness
329 /// `Witness(vec![])`
330 /// 2. Push a witness `Some(_)` against the `None`
331 /// `Witness(vec![Some(_)])`
332 /// 3. Push a witness `true` against the `false`
333 /// `Witness(vec![Some(_), true])`
334 /// 4. Apply the `Pair` constructor to the witnesses
335 /// `Witness(vec![Pair(Some(_), true)])`
337 /// The final `Pair(Some(_), true)` is then the resulting witness.
338 #[derive(Clone, Debug)]
339 pub struct Witness<'tcx>(Vec<Pattern<'tcx>>);
341 impl<'tcx> Witness<'tcx> {
342 pub fn single_pattern(&self) -> &Pattern<'tcx> {
343 assert_eq!(self.0.len(), 1);
347 fn push_wild_constructor<'a>(
349 cx: &MatchCheckCtxt<'a, 'tcx>,
350 ctor: &Constructor<'tcx>,
354 let sub_pattern_tys = constructor_sub_pattern_tys(cx, ctor, ty);
355 self.0.extend(sub_pattern_tys.into_iter().map(|ty| {
359 kind: box PatternKind::Wild,
362 self.apply_constructor(cx, ctor, ty)
366 /// Constructs a partial witness for a pattern given a list of
367 /// patterns expanded by the specialization step.
369 /// When a pattern P is discovered to be useful, this function is used bottom-up
370 /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
371 /// of values, V, where each value in that set is not covered by any previously
372 /// used patterns and is covered by the pattern P'. Examples:
374 /// left_ty: tuple of 3 elements
375 /// pats: [10, 20, _] => (10, 20, _)
377 /// left_ty: struct X { a: (bool, &'static str), b: usize}
378 /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 }
379 fn apply_constructor<'a>(
381 cx: &MatchCheckCtxt<'a,'tcx>,
382 ctor: &Constructor<'tcx>,
386 let arity = constructor_arity(cx, ctor, ty);
388 let len = self.0.len() as u64;
389 let mut pats = self.0.drain((len - arity) as usize..).rev();
394 let pats = pats.enumerate().map(|(i, p)| {
396 field: Field::new(i),
401 if let ty::TyAdt(adt, substs) = ty.sty {
403 PatternKind::Variant {
406 variant_index: ctor.variant_index_for_adt(adt),
410 PatternKind::Leaf { subpatterns: pats }
413 PatternKind::Leaf { subpatterns: pats }
418 PatternKind::Deref { subpattern: pats.nth(0).unwrap() }
421 ty::TySlice(_) | ty::TyArray(..) => {
423 prefix: pats.collect(),
431 ConstantValue(value) => PatternKind::Constant { value },
432 ConstantRange(lo, hi, end) => PatternKind::Range { lo, hi, end },
433 _ => PatternKind::Wild,
439 self.0.push(Pattern {
449 /// This determines the set of all possible constructors of a pattern matching
450 /// values of type `left_ty`. For vectors, this would normally be an infinite set
451 /// but is instead bounded by the maximum fixed length of slice patterns in
452 /// the column of patterns being analyzed.
454 /// We make sure to omit constructors that are statically impossible. eg for
455 /// Option<!> we do not include Some(_) in the returned list of constructors.
456 fn all_constructors<'a, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
457 pcx: PatternContext<'tcx>)
458 -> Vec<Constructor<'tcx>>
460 debug!("all_constructors({:?})", pcx.ty);
461 let exhaustive_integer_patterns = cx.tcx.features().exhaustive_integer_patterns;
462 let ctors = match pcx.ty.sty {
464 [true, false].iter().map(|&b| {
465 ConstantValue(ty::Const::from_bool(cx.tcx, b))
468 ty::TyArray(ref sub_ty, len) if len.assert_usize(cx.tcx).is_some() => {
469 let len = len.unwrap_usize(cx.tcx);
470 if len != 0 && cx.is_uninhabited(sub_ty) {
476 // Treat arrays of a constant but unknown length like slices.
477 ty::TyArray(ref sub_ty, _) |
478 ty::TySlice(ref sub_ty) => {
479 if cx.is_uninhabited(sub_ty) {
482 (0..pcx.max_slice_length+1).map(|length| Slice(length)).collect()
485 ty::TyAdt(def, substs) if def.is_enum() => {
487 .filter(|v| !cx.is_variant_uninhabited(v, substs))
488 .map(|v| Variant(v.did))
491 ty::TyChar if exhaustive_integer_patterns => {
492 let endpoint = |c: char| {
493 let ty = ty::ParamEnv::empty().and(cx.tcx.types.char);
494 ty::Const::from_bits(cx.tcx, c as u128, ty)
497 // The valid Unicode Scalar Value ranges.
498 ConstantRange(endpoint('\u{0000}'), endpoint('\u{D7FF}'), RangeEnd::Included),
499 ConstantRange(endpoint('\u{E000}'), endpoint('\u{10FFFF}'), RangeEnd::Included),
502 ty::TyInt(ity) if exhaustive_integer_patterns => {
503 // FIXME(49937): refactor these bit manipulations into interpret.
504 let bits = Integer::from_attr(cx.tcx, SignedInt(ity)).size().bits() as u128;
505 let min = 1u128 << (bits - 1);
506 let max = (1u128 << (bits - 1)) - 1;
507 let ty = ty::ParamEnv::empty().and(pcx.ty);
508 vec![ConstantRange(ty::Const::from_bits(cx.tcx, min as u128, ty),
509 ty::Const::from_bits(cx.tcx, max as u128, ty),
512 ty::TyUint(uty) if exhaustive_integer_patterns => {
513 // FIXME(49937): refactor these bit manipulations into interpret.
514 let bits = Integer::from_attr(cx.tcx, UnsignedInt(uty)).size().bits() as u128;
515 let max = !0u128 >> (128 - bits);
516 let ty = ty::ParamEnv::empty().and(pcx.ty);
517 vec![ConstantRange(ty::Const::from_bits(cx.tcx, 0, ty),
518 ty::Const::from_bits(cx.tcx, max, ty),
522 if cx.is_uninhabited(pcx.ty) {
532 fn max_slice_length<'p, 'a: 'p, 'tcx: 'a, I>(
533 cx: &mut MatchCheckCtxt<'a, 'tcx>,
535 where I: Iterator<Item=&'p Pattern<'tcx>>
537 // The exhaustiveness-checking paper does not include any details on
538 // checking variable-length slice patterns. However, they are matched
539 // by an infinite collection of fixed-length array patterns.
541 // Checking the infinite set directly would take an infinite amount
542 // of time. However, it turns out that for each finite set of
543 // patterns `P`, all sufficiently large array lengths are equivalent:
545 // Each slice `s` with a "sufficiently-large" length `l ≥ L` that applies
546 // to exactly the subset `Pₜ` of `P` can be transformed to a slice
547 // `sₘ` for each sufficiently-large length `m` that applies to exactly
548 // the same subset of `P`.
550 // Because of that, each witness for reachability-checking from one
551 // of the sufficiently-large lengths can be transformed to an
552 // equally-valid witness from any other length, so we only have
553 // to check slice lengths from the "minimal sufficiently-large length"
556 // Note that the fact that there is a *single* `sₘ` for each `m`
557 // not depending on the specific pattern in `P` is important: if
558 // you look at the pair of patterns
561 // Then any slice of length ≥1 that matches one of these two
562 // patterns can be trivially turned to a slice of any
563 // other length ≥1 that matches them and vice-versa - for
564 // but the slice from length 2 `[false, true]` that matches neither
565 // of these patterns can't be turned to a slice from length 1 that
566 // matches neither of these patterns, so we have to consider
567 // slices from length 2 there.
569 // Now, to see that that length exists and find it, observe that slice
570 // patterns are either "fixed-length" patterns (`[_, _, _]`) or
571 // "variable-length" patterns (`[_, .., _]`).
573 // For fixed-length patterns, all slices with lengths *longer* than
574 // the pattern's length have the same outcome (of not matching), so
575 // as long as `L` is greater than the pattern's length we can pick
576 // any `sₘ` from that length and get the same result.
578 // For variable-length patterns, the situation is more complicated,
579 // because as seen above the precise value of `sₘ` matters.
581 // However, for each variable-length pattern `p` with a prefix of length
582 // `plâ‚š` and suffix of length `slâ‚š`, only the first `plâ‚š` and the last
583 // `slâ‚š` elements are examined.
585 // Therefore, as long as `L` is positive (to avoid concerns about empty
586 // types), all elements after the maximum prefix length and before
587 // the maximum suffix length are not examined by any variable-length
588 // pattern, and therefore can be added/removed without affecting
589 // them - creating equivalent patterns from any sufficiently-large
592 // Of course, if fixed-length patterns exist, we must be sure
593 // that our length is large enough to miss them all, so
594 // we can pick `L = max(FIXED_LEN+1 ∪ {max(PREFIX_LEN) + max(SUFFIX_LEN)})`
596 // for example, with the above pair of patterns, all elements
597 // but the first and last can be added/removed, so any
598 // witness of length ≥2 (say, `[false, false, true]`) can be
599 // turned to a witness from any other length ≥2.
601 let mut max_prefix_len = 0;
602 let mut max_suffix_len = 0;
603 let mut max_fixed_len = 0;
605 for row in patterns {
607 PatternKind::Constant { value } => {
608 if let Some(ptr) = value.to_ptr() {
609 let is_array_ptr = value.ty
611 .and_then(|t| t.ty.builtin_index())
612 .map_or(false, |t| t == cx.tcx.types.u8);
614 let alloc = cx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
615 max_fixed_len = cmp::max(max_fixed_len, alloc.bytes.len() as u64);
619 PatternKind::Slice { ref prefix, slice: None, ref suffix } => {
620 let fixed_len = prefix.len() as u64 + suffix.len() as u64;
621 max_fixed_len = cmp::max(max_fixed_len, fixed_len);
623 PatternKind::Slice { ref prefix, slice: Some(_), ref suffix } => {
624 max_prefix_len = cmp::max(max_prefix_len, prefix.len() as u64);
625 max_suffix_len = cmp::max(max_suffix_len, suffix.len() as u64);
631 cmp::max(max_fixed_len + 1, max_prefix_len + max_suffix_len)
634 /// An inclusive interval, used for precise integer exhaustiveness checking.
635 /// `IntRange`s always store a contiguous range. This means that values are
636 /// encoded such that `0` encodes the minimum value for the integer,
637 /// regardless of the signedness.
638 /// For example, the pattern `-128...127i8` is encoded as `0..=255`.
639 /// This makes comparisons and arithmetic on interval endpoints much more
640 /// straightforward. See `signed_bias` for details.
641 struct IntRange<'tcx> {
642 pub range: RangeInclusive<u128>,
646 impl<'tcx> IntRange<'tcx> {
647 fn from_ctor(tcx: TyCtxt<'_, 'tcx, 'tcx>,
648 ctor: &Constructor<'tcx>)
649 -> Option<IntRange<'tcx>> {
651 ConstantRange(lo, hi, end) => {
652 assert_eq!(lo.ty, hi.ty);
654 let env_ty = ty::ParamEnv::empty().and(ty);
655 if let Some(lo) = lo.assert_bits(tcx, env_ty) {
656 if let Some(hi) = hi.assert_bits(tcx, env_ty) {
657 // Perform a shift if the underlying types are signed,
658 // which makes the interval arithmetic simpler.
659 let bias = IntRange::signed_bias(tcx, ty);
660 let (lo, hi) = (lo ^ bias, hi ^ bias);
661 // Make sure the interval is well-formed.
662 return if lo > hi || lo == hi && *end == RangeEnd::Excluded {
665 let offset = (*end == RangeEnd::Excluded) as u128;
666 Some(IntRange { range: lo..=(hi - offset), ty })
672 ConstantValue(val) => {
674 if let Some(val) = val.assert_bits(tcx, ty::ParamEnv::empty().and(ty)) {
675 let bias = IntRange::signed_bias(tcx, ty);
676 let val = val ^ bias;
677 Some(IntRange { range: val..=val, ty })
682 Single | Variant(_) | Slice(_) => {
688 // The return value of `signed_bias` should be
689 // XORed with an endpoint to encode/decode it.
690 fn signed_bias(tcx: TyCtxt<'_, 'tcx, 'tcx>, ty: Ty<'tcx>) -> u128 {
693 let bits = Integer::from_attr(tcx, SignedInt(ity)).size().bits() as u128;
700 /// Given an `IntRange` corresponding to a pattern in a `match` and a collection of
701 /// ranges corresponding to the domain of values of a type (say, an integer), return
702 /// a new collection of ranges corresponding to the original ranges minus the ranges
703 /// covered by the `IntRange`.
704 fn subtract_from(self,
705 tcx: TyCtxt<'_, 'tcx, 'tcx>,
706 ranges: Vec<Constructor<'tcx>>)
707 -> Vec<Constructor<'tcx>> {
708 let ranges = ranges.into_iter().filter_map(|r| {
709 IntRange::from_ctor(tcx, &r).map(|i| i.range)
711 // Convert a `RangeInclusive` to a `ConstantValue` or inclusive `ConstantRange`.
712 let bias = IntRange::signed_bias(tcx, self.ty);
713 let ty = ty::ParamEnv::empty().and(self.ty);
714 let range_to_constant = |r: RangeInclusive<u128>| {
715 let (lo, hi) = r.into_inner();
717 ConstantValue(ty::Const::from_bits(tcx, lo ^ bias, ty))
719 ConstantRange(ty::Const::from_bits(tcx, lo ^ bias, ty),
720 ty::Const::from_bits(tcx, hi ^ bias, ty),
724 let mut remaining_ranges = vec![];
725 let (lo, hi) = self.range.into_inner();
726 for subrange in ranges {
727 let (subrange_lo, subrange_hi) = subrange.into_inner();
728 if lo > subrange_hi || subrange_lo > hi {
729 // The pattern doesn't intersect with the subrange at all,
730 // so the subrange remains untouched.
731 remaining_ranges.push(range_to_constant(subrange_lo..=subrange_hi));
733 if lo > subrange_lo {
734 // The pattern intersects an upper section of the
735 // subrange, so a lower section will remain.
736 remaining_ranges.push(range_to_constant(subrange_lo..=(lo - 1)));
738 if hi < subrange_hi {
739 // The pattern intersects a lower section of the
740 // subrange, so an upper section will remain.
741 remaining_ranges.push(range_to_constant((hi + 1)..=subrange_hi));
749 /// Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
750 /// The algorithm from the paper has been modified to correctly handle empty
751 /// types. The changes are:
752 /// (0) We don't exit early if the pattern matrix has zero rows. We just
753 /// continue to recurse over columns.
754 /// (1) all_constructors will only return constructors that are statically
755 /// possible. eg. it will only return Ok for Result<T, !>
757 /// This finds whether a (row) vector `v` of patterns is 'useful' in relation
758 /// to a set of such vectors `m` - this is defined as there being a set of
759 /// inputs that will match `v` but not any of the sets in `m`.
761 /// All the patterns at each column of the `matrix ++ v` matrix must
762 /// have the same type, except that wildcard (PatternKind::Wild) patterns
763 /// with type TyErr are also allowed, even if the "type of the column"
764 /// is not TyErr. That is used to represent private fields, as using their
765 /// real type would assert that they are inhabited.
767 /// This is used both for reachability checking (if a pattern isn't useful in
768 /// relation to preceding patterns, it is not reachable) and exhaustiveness
769 /// checking (if a wildcard pattern is useful in relation to a matrix, the
770 /// matrix isn't exhaustive).
771 pub fn is_useful<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
772 matrix: &Matrix<'p, 'tcx>,
773 v: &[&'p Pattern<'tcx>],
774 witness: WitnessPreference)
775 -> Usefulness<'tcx> {
776 let &Matrix(ref rows) = matrix;
777 debug!("is_useful({:#?}, {:#?})", matrix, v);
779 // The base case. We are pattern-matching on () and the return value is
780 // based on whether our matrix has a row or not.
781 // NOTE: This could potentially be optimized by checking rows.is_empty()
782 // first and then, if v is non-empty, the return value is based on whether
783 // the type of the tuple we're checking is inhabited or not.
785 return if rows.is_empty() {
787 ConstructWitness => UsefulWithWitness(vec![Witness(vec![])]),
788 LeaveOutWitness => Useful,
795 assert!(rows.iter().all(|r| r.len() == v.len()));
797 let pcx = PatternContext {
798 // TyErr is used to represent the type of wildcard patterns matching
799 // against inaccessible (private) fields of structs, so that we won't
800 // be able to observe whether the types of the struct's fields are
803 // If the field is truly inaccessible, then all the patterns
804 // matching against it must be wildcard patterns, so its type
807 // However, if we are matching against non-wildcard patterns, we
808 // need to know the real type of the field so we can specialize
809 // against it. This primarily occurs through constants - they
810 // can include contents for fields that are inaccessible at the
811 // location of the match. In that case, the field's type is
812 // inhabited - by the constant - so we can just use it.
814 // FIXME: this might lead to "unstable" behavior with macro hygiene
815 // introducing uninhabited patterns for inaccessible fields. We
816 // need to figure out how to model that.
817 ty: rows.iter().map(|r| r[0].ty).find(|ty| !ty.references_error())
819 max_slice_length: max_slice_length(cx, rows.iter().map(|r| r[0]).chain(Some(v[0])))
822 debug!("is_useful_expand_first_col: pcx={:#?}, expanding {:#?}", pcx, v[0]);
824 if let Some(constructors) = pat_constructors(cx, v[0], pcx) {
825 debug!("is_useful - expanding constructors: {:#?}", constructors);
826 constructors.into_iter().map(|c|
827 is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness)
828 ).find(|result| result.is_useful()).unwrap_or(NotUseful)
830 debug!("is_useful - expanding wildcard");
832 let used_ctors: Vec<Constructor> = rows.iter().flat_map(|row| {
833 pat_constructors(cx, row[0], pcx).unwrap_or(vec![])
835 debug!("used_ctors = {:#?}", used_ctors);
836 // `all_ctors` are all the constructors for the given type, which
837 // should all be represented (or caught with the wild pattern `_`).
838 let all_ctors = all_constructors(cx, pcx);
839 debug!("all_ctors = {:#?}", all_ctors);
841 // The only constructor patterns for which it is valid to
842 // treat the values as constructors are ranges (see
843 // `all_constructors` for details).
844 let exhaustive_integer_patterns = cx.tcx.features().exhaustive_integer_patterns;
845 let consider_value_constructors = exhaustive_integer_patterns
846 && all_ctors.iter().all(|ctor| match ctor {
847 ConstantRange(..) => true,
851 // `missing_ctors` are those that should have appeared
852 // as patterns in the `match` expression, but did not.
853 let mut missing_ctors = vec![];
854 for req_ctor in &all_ctors {
855 let mut refined_ctors = vec![req_ctor.clone()];
856 for used_ctor in &used_ctors {
857 if used_ctor == req_ctor {
858 // If a constructor appears in a `match` arm, we can
859 // eliminate it straight away.
860 refined_ctors = vec![]
861 } else if exhaustive_integer_patterns {
862 if let Some(interval) = IntRange::from_ctor(cx.tcx, used_ctor) {
863 // Refine the required constructors for the type by subtracting
864 // the range defined by the current constructor pattern.
865 refined_ctors = interval.subtract_from(cx.tcx, refined_ctors);
869 // If the constructor patterns that have been considered so far
870 // already cover the entire range of values, then we the
871 // constructor is not missing, and we can move on to the next one.
872 if refined_ctors.is_empty() {
876 // If a constructor has not been matched, then it is missing.
877 // We add `refined_ctors` instead of `req_ctor`, because then we can
878 // provide more detailed error information about precisely which
879 // ranges have been omitted.
880 missing_ctors.extend(refined_ctors);
883 // `missing_ctors` is the set of constructors from the same type as the
884 // first column of `matrix` that are matched only by wildcard patterns
885 // from the first column.
887 // Therefore, if there is some pattern that is unmatched by `matrix`,
888 // it will still be unmatched if the first constructor is replaced by
889 // any of the constructors in `missing_ctors`
891 // However, if our scrutinee is *privately* an empty enum, we
892 // must treat it as though it had an "unknown" constructor (in
893 // that case, all other patterns obviously can't be variants)
894 // to avoid exposing its emptyness. See the `match_privately_empty`
897 // FIXME: currently the only way I know of something can
898 // be a privately-empty enum is when the exhaustive_patterns
899 // feature flag is not present, so this is only
900 // needed for that case.
902 let is_privately_empty =
903 all_ctors.is_empty() && !cx.is_uninhabited(pcx.ty);
904 let is_declared_nonexhaustive =
905 cx.is_non_exhaustive_enum(pcx.ty) && !cx.is_local(pcx.ty);
906 debug!("missing_ctors={:#?} is_privately_empty={:#?} is_declared_nonexhaustive={:#?}",
907 missing_ctors, is_privately_empty, is_declared_nonexhaustive);
909 // For privately empty and non-exhaustive enums, we work as if there were an "extra"
910 // `_` constructor for the type, so we can never match over all constructors.
911 let is_non_exhaustive = is_privately_empty || is_declared_nonexhaustive;
913 if missing_ctors.is_empty() && !is_non_exhaustive {
914 if consider_value_constructors {
915 // If we've successfully matched every value
916 // of the type, then we're done.
919 all_ctors.into_iter().map(|c| {
920 is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness)
921 }).find(|result| result.is_useful()).unwrap_or(NotUseful)
924 let matrix = rows.iter().filter_map(|r| {
925 if r[0].is_wildcard() {
926 Some(r[1..].to_vec())
931 match is_useful(cx, &matrix, &v[1..], witness) {
932 UsefulWithWitness(pats) => {
934 // In this case, there's at least one "free"
935 // constructor that is only matched against by
936 // wildcard patterns.
938 // There are 2 ways we can report a witness here.
939 // Commonly, we can report all the "free"
940 // constructors as witnesses, e.g. if we have:
943 // enum Direction { N, S, E, W }
944 // let Direction::N = ...;
947 // we can report 3 witnesses: `S`, `E`, and `W`.
949 // However, there are 2 cases where we don't want
950 // to do this and instead report a single `_` witness:
952 // 1) If the user is matching against a non-exhaustive
953 // enum, there is no point in enumerating all possible
954 // variants, because the user can't actually match
955 // against them himself, e.g. in an example like:
957 // let err: io::ErrorKind = ...;
959 // io::ErrorKind::NotFound => {},
962 // we don't want to show every possible IO error,
963 // but instead have `_` as the witness (this is
964 // actually *required* if the user specified *all*
965 // IO errors, but is probably what we want in every
968 // 2) If the user didn't actually specify a constructor
969 // in this arm, e.g. in
971 // let x: (Direction, Direction, bool) = ...;
972 // let (_, _, false) = x;
974 // we don't want to show all 16 possible witnesses
975 // `(<direction-1>, <direction-2>, true)` - we are
976 // satisfied with `(_, _, true)`. In this case,
977 // `used_ctors` is empty.
978 let new_witnesses = if is_non_exhaustive || used_ctors.is_empty() {
979 // All constructors are unused. Add wild patterns
980 // rather than each individual constructor.
981 pats.into_iter().map(|mut witness| {
982 witness.0.push(Pattern {
985 kind: box PatternKind::Wild,
990 pats.into_iter().flat_map(|witness| {
991 missing_ctors.iter().map(move |ctor| {
992 // Extends the witness with a "wild" version of this
993 // constructor, that matches everything that can be built with
994 // it. For example, if `ctor` is a `Constructor::Variant` for
995 // `Option::Some`, this pushes the witness for `Some(_)`.
996 witness.clone().push_wild_constructor(cx, ctor, pcx.ty)
1000 UsefulWithWitness(new_witnesses)
1008 fn is_useful_specialized<'p, 'a:'p, 'tcx: 'a>(
1009 cx: &mut MatchCheckCtxt<'a, 'tcx>,
1010 &Matrix(ref m): &Matrix<'p, 'tcx>,
1011 v: &[&'p Pattern<'tcx>],
1012 ctor: Constructor<'tcx>,
1014 witness: WitnessPreference) -> Usefulness<'tcx>
1016 debug!("is_useful_specialized({:#?}, {:#?}, {:?})", v, ctor, lty);
1017 let sub_pat_tys = constructor_sub_pattern_tys(cx, &ctor, lty);
1018 let wild_patterns_owned: Vec<_> = sub_pat_tys.iter().map(|ty| {
1022 kind: box PatternKind::Wild,
1025 let wild_patterns: Vec<_> = wild_patterns_owned.iter().collect();
1026 let matrix = Matrix(m.iter().flat_map(|r| {
1027 specialize(cx, &r, &ctor, &wild_patterns)
1029 match specialize(cx, v, &ctor, &wild_patterns) {
1030 Some(v) => match is_useful(cx, &matrix, &v, witness) {
1031 UsefulWithWitness(witnesses) => UsefulWithWitness(
1032 witnesses.into_iter()
1033 .map(|witness| witness.apply_constructor(cx, &ctor, lty))
1042 /// Determines the constructors that the given pattern can be specialized to.
1044 /// In most cases, there's only one constructor that a specific pattern
1045 /// represents, such as a specific enum variant or a specific literal value.
1046 /// Slice patterns, however, can match slices of different lengths. For instance,
1047 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
1049 /// Returns None in case of a catch-all, which can't be specialized.
1050 fn pat_constructors<'tcx>(cx: &mut MatchCheckCtxt,
1051 pat: &Pattern<'tcx>,
1052 pcx: PatternContext)
1053 -> Option<Vec<Constructor<'tcx>>>
1056 PatternKind::Binding { .. } | PatternKind::Wild =>
1058 PatternKind::Leaf { .. } | PatternKind::Deref { .. } =>
1060 PatternKind::Variant { adt_def, variant_index, .. } =>
1061 Some(vec![Variant(adt_def.variants[variant_index].did)]),
1062 PatternKind::Constant { value } =>
1063 Some(vec![ConstantValue(value)]),
1064 PatternKind::Range { lo, hi, end } =>
1065 Some(vec![ConstantRange(lo, hi, end)]),
1066 PatternKind::Array { .. } => match pcx.ty.sty {
1067 ty::TyArray(_, length) => Some(vec![
1068 Slice(length.unwrap_usize(cx.tcx))
1070 _ => span_bug!(pat.span, "bad ty {:?} for array pattern", pcx.ty)
1072 PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
1073 let pat_len = prefix.len() as u64 + suffix.len() as u64;
1074 if slice.is_some() {
1075 Some((pat_len..pcx.max_slice_length+1).map(Slice).collect())
1077 Some(vec![Slice(pat_len)])
1083 /// This computes the arity of a constructor. The arity of a constructor
1084 /// is how many subpattern patterns of that constructor should be expanded to.
1086 /// For instance, a tuple pattern (_, 42, Some([])) has the arity of 3.
1087 /// A struct pattern's arity is the number of fields it contains, etc.
1088 fn constructor_arity(_cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> u64 {
1089 debug!("constructor_arity({:#?}, {:?})", ctor, ty);
1091 ty::TyTuple(ref fs) => fs.len() as u64,
1092 ty::TySlice(..) | ty::TyArray(..) => match *ctor {
1093 Slice(length) => length,
1094 ConstantValue(_) => 0,
1095 _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
1098 ty::TyAdt(adt, _) => {
1099 adt.variants[ctor.variant_index_for_adt(adt)].fields.len() as u64
1105 /// This computes the types of the sub patterns that a constructor should be
1108 /// For instance, a tuple pattern (43u32, 'a') has sub pattern types [u32, char].
1109 fn constructor_sub_pattern_tys<'a, 'tcx: 'a>(cx: &MatchCheckCtxt<'a, 'tcx>,
1111 ty: Ty<'tcx>) -> Vec<Ty<'tcx>>
1113 debug!("constructor_sub_pattern_tys({:#?}, {:?})", ctor, ty);
1115 ty::TyTuple(ref fs) => fs.into_iter().map(|t| *t).collect(),
1116 ty::TySlice(ty) | ty::TyArray(ty, _) => match *ctor {
1117 Slice(length) => (0..length).map(|_| ty).collect(),
1118 ConstantValue(_) => vec![],
1119 _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
1121 ty::TyRef(_, rty, _) => vec![rty],
1122 ty::TyAdt(adt, substs) => {
1124 // Use T as the sub pattern type of Box<T>.
1125 vec![substs.type_at(0)]
1127 adt.variants[ctor.variant_index_for_adt(adt)].fields.iter().map(|field| {
1128 let is_visible = adt.is_enum()
1129 || field.vis.is_accessible_from(cx.module, cx.tcx);
1131 field.ty(cx.tcx, substs)
1133 // Treat all non-visible fields as TyErr. They
1134 // can't appear in any other pattern from
1135 // this match (because they are private),
1136 // so their type does not matter - but
1137 // we don't want to know they are
1148 fn slice_pat_covered_by_constructor<'tcx>(
1149 tcx: TyCtxt<'_, 'tcx, '_>,
1152 prefix: &[Pattern<'tcx>],
1153 slice: &Option<Pattern<'tcx>>,
1154 suffix: &[Pattern<'tcx>]
1155 ) -> Result<bool, ErrorReported> {
1156 let data: &[u8] = match *ctor {
1157 ConstantValue(const_val) => {
1158 let val = match const_val.val {
1159 ConstValue::Unevaluated(..) |
1160 ConstValue::ByRef(..) => bug!("unexpected ConstValue: {:?}", const_val),
1161 ConstValue::Scalar(val) | ConstValue::ScalarPair(val, _) => val,
1163 if let Ok(ptr) = val.to_ptr() {
1164 let is_array_ptr = const_val.ty
1165 .builtin_deref(true)
1166 .and_then(|t| t.ty.builtin_index())
1167 .map_or(false, |t| t == tcx.types.u8);
1168 assert!(is_array_ptr);
1169 tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id).bytes.as_ref()
1171 bug!("unexpected non-ptr ConstantValue")
1177 let pat_len = prefix.len() + suffix.len();
1178 if data.len() < pat_len || (slice.is_none() && data.len() > pat_len) {
1183 data[..prefix.len()].iter().zip(prefix).chain(
1184 data[data.len()-suffix.len()..].iter().zip(suffix))
1187 box PatternKind::Constant { value } => {
1188 let b = value.unwrap_bits(tcx, ty::ParamEnv::empty().and(pat.ty));
1189 assert_eq!(b as u8 as u128, b);
1201 fn constructor_covered_by_range<'a, 'tcx>(
1202 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1203 ctor: &Constructor<'tcx>,
1204 from: &'tcx ty::Const<'tcx>, to: &'tcx ty::Const<'tcx>,
1207 ) -> Result<bool, ErrorReported> {
1208 trace!("constructor_covered_by_range {:#?}, {:#?}, {:#?}, {}", ctor, from, to, ty);
1209 let cmp_from = |c_from| compare_const_vals(tcx, c_from, from, ty::ParamEnv::empty().and(ty))
1210 .map(|res| res != Ordering::Less);
1211 let cmp_to = |c_to| compare_const_vals(tcx, c_to, to, ty::ParamEnv::empty().and(ty));
1212 macro_rules! some_or_ok {
1216 None => return Ok(false), // not char or int
1221 ConstantValue(value) => {
1222 let to = some_or_ok!(cmp_to(value));
1223 let end = (to == Ordering::Less) ||
1224 (end == RangeEnd::Included && to == Ordering::Equal);
1225 Ok(some_or_ok!(cmp_from(value)) && end)
1227 ConstantRange(from, to, RangeEnd::Included) => {
1228 let to = some_or_ok!(cmp_to(to));
1229 let end = (to == Ordering::Less) ||
1230 (end == RangeEnd::Included && to == Ordering::Equal);
1231 Ok(some_or_ok!(cmp_from(from)) && end)
1233 ConstantRange(from, to, RangeEnd::Excluded) => {
1234 let to = some_or_ok!(cmp_to(to));
1235 let end = (to == Ordering::Less) ||
1236 (end == RangeEnd::Excluded && to == Ordering::Equal);
1237 Ok(some_or_ok!(cmp_from(from)) && end)
1244 fn patterns_for_variant<'p, 'a: 'p, 'tcx: 'a>(
1245 subpatterns: &'p [FieldPattern<'tcx>],
1246 wild_patterns: &[&'p Pattern<'tcx>])
1247 -> Vec<&'p Pattern<'tcx>>
1249 let mut result = wild_patterns.to_owned();
1251 for subpat in subpatterns {
1252 result[subpat.field.index()] = &subpat.pattern;
1255 debug!("patterns_for_variant({:#?}, {:#?}) = {:#?}", subpatterns, wild_patterns, result);
1259 /// This is the main specialization step. It expands the first pattern in the given row
1260 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
1261 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
1263 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
1264 /// different patterns.
1265 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
1266 /// fields filled with wild patterns.
1267 fn specialize<'p, 'a: 'p, 'tcx: 'a>(
1268 cx: &mut MatchCheckCtxt<'a, 'tcx>,
1269 r: &[&'p Pattern<'tcx>],
1270 constructor: &Constructor<'tcx>,
1271 wild_patterns: &[&'p Pattern<'tcx>])
1272 -> Option<Vec<&'p Pattern<'tcx>>>
1276 let head: Option<Vec<&Pattern>> = match *pat.kind {
1277 PatternKind::Binding { .. } | PatternKind::Wild => {
1278 Some(wild_patterns.to_owned())
1281 PatternKind::Variant { adt_def, variant_index, ref subpatterns, .. } => {
1282 let ref variant = adt_def.variants[variant_index];
1283 if *constructor == Variant(variant.did) {
1284 Some(patterns_for_variant(subpatterns, wild_patterns))
1290 PatternKind::Leaf { ref subpatterns } => {
1291 Some(patterns_for_variant(subpatterns, wild_patterns))
1294 PatternKind::Deref { ref subpattern } => {
1295 Some(vec![subpattern])
1298 PatternKind::Constant { value } => {
1299 match *constructor {
1301 if let Some(ptr) = value.to_ptr() {
1302 let is_array_ptr = value.ty
1303 .builtin_deref(true)
1304 .and_then(|t| t.ty.builtin_index())
1305 .map_or(false, |t| t == cx.tcx.types.u8);
1306 assert!(is_array_ptr);
1307 let data_len = cx.tcx
1310 .unwrap_memory(ptr.alloc_id)
1313 if wild_patterns.len() == data_len {
1314 Some(cx.lower_byte_str_pattern(pat))
1320 "unexpected const-val {:?} with ctor {:?}", value, constructor)
1324 match constructor_covered_by_range(
1326 constructor, value, value, RangeEnd::Included,
1329 Ok(true) => Some(vec![]),
1331 Err(ErrorReported) => None,
1337 PatternKind::Range { lo, hi, ref end } => {
1338 match constructor_covered_by_range(
1340 constructor, lo, hi, end.clone(), lo.ty,
1342 Ok(true) => Some(vec![]),
1344 Err(ErrorReported) => None,
1348 PatternKind::Array { ref prefix, ref slice, ref suffix } |
1349 PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
1350 match *constructor {
1352 let pat_len = prefix.len() + suffix.len();
1353 if let Some(slice_count) = wild_patterns.len().checked_sub(pat_len) {
1354 if slice_count == 0 || slice.is_some() {
1356 prefix.iter().chain(
1357 wild_patterns.iter().map(|p| *p)
1370 ConstantValue(..) => {
1371 match slice_pat_covered_by_constructor(
1372 cx.tcx, pat.span, constructor, prefix, slice, suffix
1374 Ok(true) => Some(vec![]),
1376 Err(ErrorReported) => None
1379 _ => span_bug!(pat.span,
1380 "unexpected ctor {:?} for slice pat", constructor)
1384 debug!("specialize({:#?}, {:#?}) = {:#?}", r[0], wild_patterns, head);
1386 head.map(|mut head| {
1387 head.extend_from_slice(&r[1 ..]);