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, repeat};
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('+').take(total_width).collect::<String>();
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 //NOTE: appears to be the only place other then InferCtxt to contain a ParamEnv
142 pub struct MatchCheckCtxt<'a, 'tcx: 'a> {
143 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
144 /// The module in which the match occurs. This is necessary for
145 /// checking inhabited-ness of types because whether a type is (visibly)
146 /// inhabited can depend on whether it was defined in the current module or
147 /// not. eg. `struct Foo { _private: ! }` cannot be seen to be empty
148 /// outside it's module and should not be matchable with an empty match
151 pub pattern_arena: &'a TypedArena<Pattern<'tcx>>,
152 pub byte_array_map: FxHashMap<*const Pattern<'tcx>, Vec<&'a Pattern<'tcx>>>,
155 impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> {
156 pub fn create_and_enter<F, R>(
157 tcx: TyCtxt<'a, 'tcx, 'tcx>,
160 where F: for<'b> FnOnce(MatchCheckCtxt<'b, 'tcx>) -> R
162 let pattern_arena = TypedArena::new();
167 pattern_arena: &pattern_arena,
168 byte_array_map: FxHashMap(),
172 // convert a byte-string pattern to a list of u8 patterns.
173 fn lower_byte_str_pattern<'p>(&mut self, pat: &'p Pattern<'tcx>) -> Vec<&'p Pattern<'tcx>>
176 let pattern_arena = &*self.pattern_arena;
178 self.byte_array_map.entry(pat).or_insert_with(|| {
180 box PatternKind::Constant {
183 if let Some(ptr) = const_val.to_ptr() {
184 let is_array_ptr = const_val.ty
186 .and_then(|t| t.ty.builtin_index())
187 .map_or(false, |t| t == tcx.types.u8);
188 assert!(is_array_ptr);
189 let alloc = tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
190 assert_eq!(ptr.offset.bytes(), 0);
191 // FIXME: check length
192 alloc.bytes.iter().map(|b| {
193 &*pattern_arena.alloc(Pattern {
196 kind: box PatternKind::Constant {
197 value: ty::Const::from_bits(
200 ty::ParamEnv::empty().and(tcx.types.u8))
205 bug!("not a byte str: {:?}", const_val)
208 _ => span_bug!(pat.span, "unexpected byte array pattern {:?}", pat)
213 fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool {
214 if self.tcx.features().exhaustive_patterns {
215 self.tcx.is_ty_uninhabited_from(self.module, ty)
221 fn is_non_exhaustive_enum(&self, ty: Ty<'tcx>) -> bool {
223 ty::TyAdt(adt_def, ..) => adt_def.is_enum() && adt_def.is_non_exhaustive(),
228 fn is_local(&self, ty: Ty<'tcx>) -> bool {
230 ty::TyAdt(adt_def, ..) => adt_def.did.is_local(),
235 fn is_variant_uninhabited(&self,
236 variant: &'tcx ty::VariantDef,
237 substs: &'tcx ty::subst::Substs<'tcx>)
240 if self.tcx.features().exhaustive_patterns {
241 self.tcx.is_enum_variant_uninhabited_from(self.module, variant, substs)
248 #[derive(Clone, Debug, PartialEq)]
249 pub enum Constructor<'tcx> {
250 /// The constructor of all patterns that don't vary by constructor,
251 /// e.g. struct patterns and fixed-length arrays.
256 ConstantValue(&'tcx ty::Const<'tcx>),
257 /// Ranges of literal values (`2...5` and `2..5`).
258 ConstantRange(&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>, RangeEnd),
259 /// Array patterns of length n.
263 impl<'tcx> Constructor<'tcx> {
264 fn variant_index_for_adt(&self, adt: &'tcx ty::AdtDef) -> usize {
266 &Variant(vid) => adt.variant_index_with_id(vid),
268 assert!(!adt.is_enum());
271 _ => bug!("bad constructor {:?} for adt {:?}", self, adt)
277 pub enum Usefulness<'tcx> {
279 UsefulWithWitness(Vec<Witness<'tcx>>),
283 impl<'tcx> Usefulness<'tcx> {
284 fn is_useful(&self) -> bool {
292 #[derive(Copy, Clone)]
293 pub enum WitnessPreference {
298 #[derive(Copy, Clone, Debug)]
299 struct PatternContext<'tcx> {
301 max_slice_length: u64,
304 /// A stack of patterns in reverse order of construction
306 pub struct Witness<'tcx>(Vec<Pattern<'tcx>>);
308 impl<'tcx> Witness<'tcx> {
309 pub fn single_pattern(&self) -> &Pattern<'tcx> {
310 assert_eq!(self.0.len(), 1);
314 fn push_wild_constructor<'a>(
316 cx: &MatchCheckCtxt<'a, 'tcx>,
317 ctor: &Constructor<'tcx>,
321 let sub_pattern_tys = constructor_sub_pattern_tys(cx, ctor, ty);
322 self.0.extend(sub_pattern_tys.into_iter().map(|ty| {
326 kind: box PatternKind::Wild,
329 self.apply_constructor(cx, ctor, ty)
333 /// Constructs a partial witness for a pattern given a list of
334 /// patterns expanded by the specialization step.
336 /// When a pattern P is discovered to be useful, this function is used bottom-up
337 /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
338 /// of values, V, where each value in that set is not covered by any previously
339 /// used patterns and is covered by the pattern P'. Examples:
341 /// left_ty: tuple of 3 elements
342 /// pats: [10, 20, _] => (10, 20, _)
344 /// left_ty: struct X { a: (bool, &'static str), b: usize}
345 /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 }
346 fn apply_constructor<'a>(
348 cx: &MatchCheckCtxt<'a,'tcx>,
349 ctor: &Constructor<'tcx>,
353 let arity = constructor_arity(cx, ctor, ty);
355 let len = self.0.len() as u64;
356 let mut pats = self.0.drain((len-arity) as usize..).rev();
361 let pats = pats.enumerate().map(|(i, p)| {
363 field: Field::new(i),
368 if let ty::TyAdt(adt, substs) = ty.sty {
370 PatternKind::Variant {
373 variant_index: ctor.variant_index_for_adt(adt),
377 PatternKind::Leaf { subpatterns: pats }
380 PatternKind::Leaf { subpatterns: pats }
385 PatternKind::Deref { subpattern: pats.nth(0).unwrap() }
388 ty::TySlice(_) | ty::TyArray(..) => {
390 prefix: pats.collect(),
398 ConstantValue(value) => PatternKind::Constant { value },
399 _ => PatternKind::Wild,
405 self.0.push(Pattern {
415 /// This determines the set of all possible constructors of a pattern matching
416 /// values of type `left_ty`. For vectors, this would normally be an infinite set
417 /// but is instead bounded by the maximum fixed length of slice patterns in
418 /// the column of patterns being analyzed.
420 /// This intentionally does not list ConstantValue specializations for
421 /// non-booleans, because we currently assume that there is always a
422 /// "non-standard constant" that matches. See issue #12483.
424 /// We make sure to omit constructors that are statically impossible. eg for
425 /// Option<!> we do not include Some(_) in the returned list of constructors.
426 fn all_constructors<'a, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
427 pcx: PatternContext<'tcx>)
428 -> Vec<Constructor<'tcx>>
430 debug!("all_constructors({:?})", pcx.ty);
433 [true, false].iter().map(|&b| {
434 ConstantValue(ty::Const::from_bool(cx.tcx, b))
437 ty::TyArray(ref sub_ty, len) if len.assert_usize(cx.tcx).is_some() => {
438 let len = len.unwrap_usize(cx.tcx);
439 if len != 0 && cx.is_uninhabited(sub_ty) {
445 // Treat arrays of a constant but unknown length like slices.
446 ty::TyArray(ref sub_ty, _) |
447 ty::TySlice(ref sub_ty) => {
448 if cx.is_uninhabited(sub_ty) {
451 (0..pcx.max_slice_length+1).map(|length| Slice(length)).collect()
454 ty::TyAdt(def, substs) if def.is_enum() => {
456 .filter(|v| !cx.is_variant_uninhabited(v, substs))
457 .map(|v| Variant(v.did))
461 if cx.is_uninhabited(pcx.ty) {
470 fn max_slice_length<'p, 'a: 'p, 'tcx: 'a, I>(
471 cx: &mut MatchCheckCtxt<'a, 'tcx>,
473 where I: Iterator<Item=&'p Pattern<'tcx>>
475 // The exhaustiveness-checking paper does not include any details on
476 // checking variable-length slice patterns. However, they are matched
477 // by an infinite collection of fixed-length array patterns.
479 // Checking the infinite set directly would take an infinite amount
480 // of time. However, it turns out that for each finite set of
481 // patterns `P`, all sufficiently large array lengths are equivalent:
483 // Each slice `s` with a "sufficiently-large" length `l ≥ L` that applies
484 // to exactly the subset `Pₜ` of `P` can be transformed to a slice
485 // `sₘ` for each sufficiently-large length `m` that applies to exactly
486 // the same subset of `P`.
488 // Because of that, each witness for reachability-checking from one
489 // of the sufficiently-large lengths can be transformed to an
490 // equally-valid witness from any other length, so we only have
491 // to check slice lengths from the "minimal sufficiently-large length"
494 // Note that the fact that there is a *single* `sₘ` for each `m`
495 // not depending on the specific pattern in `P` is important: if
496 // you look at the pair of patterns
499 // Then any slice of length ≥1 that matches one of these two
500 // patterns can be be trivially turned to a slice of any
501 // other length ≥1 that matches them and vice-versa - for
502 // but the slice from length 2 `[false, true]` that matches neither
503 // of these patterns can't be turned to a slice from length 1 that
504 // matches neither of these patterns, so we have to consider
505 // slices from length 2 there.
507 // Now, to see that that length exists and find it, observe that slice
508 // patterns are either "fixed-length" patterns (`[_, _, _]`) or
509 // "variable-length" patterns (`[_, .., _]`).
511 // For fixed-length patterns, all slices with lengths *longer* than
512 // the pattern's length have the same outcome (of not matching), so
513 // as long as `L` is greater than the pattern's length we can pick
514 // any `sₘ` from that length and get the same result.
516 // For variable-length patterns, the situation is more complicated,
517 // because as seen above the precise value of `sₘ` matters.
519 // However, for each variable-length pattern `p` with a prefix of length
520 // `plâ‚š` and suffix of length `slâ‚š`, only the first `plâ‚š` and the last
521 // `slâ‚š` elements are examined.
523 // Therefore, as long as `L` is positive (to avoid concerns about empty
524 // types), all elements after the maximum prefix length and before
525 // the maximum suffix length are not examined by any variable-length
526 // pattern, and therefore can be added/removed without affecting
527 // them - creating equivalent patterns from any sufficiently-large
530 // Of course, if fixed-length patterns exist, we must be sure
531 // that our length is large enough to miss them all, so
532 // we can pick `L = max(FIXED_LEN+1 ∪ {max(PREFIX_LEN) + max(SUFFIX_LEN)})`
534 // for example, with the above pair of patterns, all elements
535 // but the first and last can be added/removed, so any
536 // witness of length ≥2 (say, `[false, false, true]`) can be
537 // turned to a witness from any other length ≥2.
539 let mut max_prefix_len = 0;
540 let mut max_suffix_len = 0;
541 let mut max_fixed_len = 0;
543 for row in patterns {
545 PatternKind::Constant { value } => {
546 if let Some(ptr) = value.to_ptr() {
547 let is_array_ptr = value.ty
549 .and_then(|t| t.ty.builtin_index())
550 .map_or(false, |t| t == cx.tcx.types.u8);
552 let alloc = cx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
553 max_fixed_len = cmp::max(max_fixed_len, alloc.bytes.len() as u64);
557 PatternKind::Slice { ref prefix, slice: None, ref suffix } => {
558 let fixed_len = prefix.len() as u64 + suffix.len() as u64;
559 max_fixed_len = cmp::max(max_fixed_len, fixed_len);
561 PatternKind::Slice { ref prefix, slice: Some(_), ref suffix } => {
562 max_prefix_len = cmp::max(max_prefix_len, prefix.len() as u64);
563 max_suffix_len = cmp::max(max_suffix_len, suffix.len() as u64);
569 cmp::max(max_fixed_len + 1, max_prefix_len + max_suffix_len)
572 /// Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
573 /// The algorithm from the paper has been modified to correctly handle empty
574 /// types. The changes are:
575 /// (0) We don't exit early if the pattern matrix has zero rows. We just
576 /// continue to recurse over columns.
577 /// (1) all_constructors will only return constructors that are statically
578 /// possible. eg. it will only return Ok for Result<T, !>
580 /// This finds whether a (row) vector `v` of patterns is 'useful' in relation
581 /// to a set of such vectors `m` - this is defined as there being a set of
582 /// inputs that will match `v` but not any of the sets in `m`.
584 /// All the patterns at each column of the `matrix ++ v` matrix must
585 /// have the same type, except that wildcard (PatternKind::Wild) patterns
586 /// with type TyErr are also allowed, even if the "type of the column"
587 /// is not TyErr. That is used to represent private fields, as using their
588 /// real type would assert that they are inhabited.
590 /// This is used both for reachability checking (if a pattern isn't useful in
591 /// relation to preceding patterns, it is not reachable) and exhaustiveness
592 /// checking (if a wildcard pattern is useful in relation to a matrix, the
593 /// matrix isn't exhaustive).
594 pub fn is_useful<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
595 matrix: &Matrix<'p, 'tcx>,
596 v: &[&'p Pattern<'tcx>],
597 witness: WitnessPreference)
598 -> Usefulness<'tcx> {
599 let &Matrix(ref rows) = matrix;
600 debug!("is_useful({:#?}, {:#?})", matrix, v);
602 // The base case. We are pattern-matching on () and the return value is
603 // based on whether our matrix has a row or not.
604 // NOTE: This could potentially be optimized by checking rows.is_empty()
605 // first and then, if v is non-empty, the return value is based on whether
606 // the type of the tuple we're checking is inhabited or not.
608 return if rows.is_empty() {
610 ConstructWitness => UsefulWithWitness(vec![Witness(vec![])]),
611 LeaveOutWitness => Useful,
618 assert!(rows.iter().all(|r| r.len() == v.len()));
620 let pcx = PatternContext {
621 // TyErr is used to represent the type of wildcard patterns matching
622 // against inaccessible (private) fields of structs, so that we won't
623 // be able to observe whether the types of the struct's fields are
626 // If the field is truly inaccessible, then all the patterns
627 // matching against it must be wildcard patterns, so its type
630 // However, if we are matching against non-wildcard patterns, we
631 // need to know the real type of the field so we can specialize
632 // against it. This primarily occurs through constants - they
633 // can include contents for fields that are inaccessible at the
634 // location of the match. In that case, the field's type is
635 // inhabited - by the constant - so we can just use it.
637 // FIXME: this might lead to "unstable" behavior with macro hygiene
638 // introducing uninhabited patterns for inaccessible fields. We
639 // need to figure out how to model that.
640 ty: rows.iter().map(|r| r[0].ty).find(|ty| !ty.references_error())
642 max_slice_length: max_slice_length(cx, rows.iter().map(|r| r[0]).chain(Some(v[0])))
645 debug!("is_useful_expand_first_col: pcx={:#?}, expanding {:#?}", pcx, v[0]);
647 if let Some(constructors) = pat_constructors(cx, v[0], pcx) {
648 debug!("is_useful - expanding constructors: {:#?}", constructors);
649 constructors.into_iter().map(|c|
650 is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness)
651 ).find(|result| result.is_useful()).unwrap_or(NotUseful)
653 debug!("is_useful - expanding wildcard");
655 let used_ctors: Vec<Constructor> = rows.iter().flat_map(|row| {
656 pat_constructors(cx, row[0], pcx).unwrap_or(vec![])
658 debug!("used_ctors = {:#?}", used_ctors);
659 let all_ctors = all_constructors(cx, pcx);
660 debug!("all_ctors = {:#?}", all_ctors);
661 let missing_ctors: Vec<Constructor> = all_ctors.iter().filter(|c| {
662 !used_ctors.contains(*c)
663 }).cloned().collect();
665 // `missing_ctors` is the set of constructors from the same type as the
666 // first column of `matrix` that are matched only by wildcard patterns
667 // from the first column.
669 // Therefore, if there is some pattern that is unmatched by `matrix`,
670 // it will still be unmatched if the first constructor is replaced by
671 // any of the constructors in `missing_ctors`
673 // However, if our scrutinee is *privately* an empty enum, we
674 // must treat it as though it had an "unknown" constructor (in
675 // that case, all other patterns obviously can't be variants)
676 // to avoid exposing its emptyness. See the `match_privately_empty`
679 // FIXME: currently the only way I know of something can
680 // be a privately-empty enum is when the exhaustive_patterns
681 // feature flag is not present, so this is only
682 // needed for that case.
684 let is_privately_empty =
685 all_ctors.is_empty() && !cx.is_uninhabited(pcx.ty);
686 let is_declared_nonexhaustive =
687 cx.is_non_exhaustive_enum(pcx.ty) && !cx.is_local(pcx.ty);
688 debug!("missing_ctors={:#?} is_privately_empty={:#?} is_declared_nonexhaustive={:#?}",
689 missing_ctors, is_privately_empty, is_declared_nonexhaustive);
691 // For privately empty and non-exhaustive enums, we work as if there were an "extra"
692 // `_` constructor for the type, so we can never match over all constructors.
693 let is_non_exhaustive = is_privately_empty || is_declared_nonexhaustive;
695 if missing_ctors.is_empty() && !is_non_exhaustive {
696 all_ctors.into_iter().map(|c| {
697 is_useful_specialized(cx, matrix, v, c.clone(), pcx.ty, witness)
698 }).find(|result| result.is_useful()).unwrap_or(NotUseful)
700 let matrix = rows.iter().filter_map(|r| {
701 if r[0].is_wildcard() {
702 Some(r[1..].to_vec())
707 match is_useful(cx, &matrix, &v[1..], witness) {
708 UsefulWithWitness(pats) => {
710 // In this case, there's at least one "free"
711 // constructor that is only matched against by
712 // wildcard patterns.
714 // There are 2 ways we can report a witness here.
715 // Commonly, we can report all the "free"
716 // constructors as witnesses, e.g. if we have:
719 // enum Direction { N, S, E, W }
720 // let Direction::N = ...;
723 // we can report 3 witnesses: `S`, `E`, and `W`.
725 // However, there are 2 cases where we don't want
726 // to do this and instead report a single `_` witness:
728 // 1) If the user is matching against a non-exhaustive
729 // enum, there is no point in enumerating all possible
730 // variants, because the user can't actually match
731 // against them himself, e.g. in an example like:
733 // let err: io::ErrorKind = ...;
735 // io::ErrorKind::NotFound => {},
738 // we don't want to show every possible IO error,
739 // but instead have `_` as the witness (this is
740 // actually *required* if the user specified *all*
741 // IO errors, but is probably what we want in every
744 // 2) If the user didn't actually specify a constructor
745 // in this arm, e.g. in
747 // let x: (Direction, Direction, bool) = ...;
748 // let (_, _, false) = x;
750 // we don't want to show all 16 possible witnesses
751 // `(<direction-1>, <direction-2>, true)` - we are
752 // satisfied with `(_, _, true)`. In this case,
753 // `used_ctors` is empty.
754 let new_witnesses = if is_non_exhaustive || used_ctors.is_empty() {
755 // All constructors are unused. Add wild patterns
756 // rather than each individual constructor
757 pats.into_iter().map(|mut witness| {
758 witness.0.push(Pattern {
761 kind: box PatternKind::Wild,
766 pats.into_iter().flat_map(|witness| {
767 missing_ctors.iter().map(move |ctor| {
768 witness.clone().push_wild_constructor(cx, ctor, pcx.ty)
772 UsefulWithWitness(new_witnesses)
780 fn is_useful_specialized<'p, 'a:'p, 'tcx: 'a>(
781 cx: &mut MatchCheckCtxt<'a, 'tcx>,
782 &Matrix(ref m): &Matrix<'p, 'tcx>,
783 v: &[&'p Pattern<'tcx>],
784 ctor: Constructor<'tcx>,
786 witness: WitnessPreference) -> Usefulness<'tcx>
788 debug!("is_useful_specialized({:#?}, {:#?}, {:?})", v, ctor, lty);
789 let sub_pat_tys = constructor_sub_pattern_tys(cx, &ctor, lty);
790 let wild_patterns_owned: Vec<_> = sub_pat_tys.iter().map(|ty| {
794 kind: box PatternKind::Wild,
797 let wild_patterns: Vec<_> = wild_patterns_owned.iter().collect();
798 let matrix = Matrix(m.iter().flat_map(|r| {
799 specialize(cx, &r, &ctor, &wild_patterns)
801 match specialize(cx, v, &ctor, &wild_patterns) {
802 Some(v) => match is_useful(cx, &matrix, &v, witness) {
803 UsefulWithWitness(witnesses) => UsefulWithWitness(
804 witnesses.into_iter()
805 .map(|witness| witness.apply_constructor(cx, &ctor, lty))
814 /// Determines the constructors that the given pattern can be specialized to.
816 /// In most cases, there's only one constructor that a specific pattern
817 /// represents, such as a specific enum variant or a specific literal value.
818 /// Slice patterns, however, can match slices of different lengths. For instance,
819 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
821 /// Returns None in case of a catch-all, which can't be specialized.
822 fn pat_constructors<'tcx>(cx: &mut MatchCheckCtxt,
825 -> Option<Vec<Constructor<'tcx>>>
828 PatternKind::Binding { .. } | PatternKind::Wild =>
830 PatternKind::Leaf { .. } | PatternKind::Deref { .. } =>
832 PatternKind::Variant { adt_def, variant_index, .. } =>
833 Some(vec![Variant(adt_def.variants[variant_index].did)]),
834 PatternKind::Constant { value } =>
835 Some(vec![ConstantValue(value)]),
836 PatternKind::Range { lo, hi, end } =>
837 Some(vec![ConstantRange(lo, hi, end)]),
838 PatternKind::Array { .. } => match pcx.ty.sty {
839 ty::TyArray(_, length) => Some(vec![
840 Slice(length.unwrap_usize(cx.tcx))
842 _ => span_bug!(pat.span, "bad ty {:?} for array pattern", pcx.ty)
844 PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
845 let pat_len = prefix.len() as u64 + suffix.len() as u64;
847 Some((pat_len..pcx.max_slice_length+1).map(Slice).collect())
849 Some(vec![Slice(pat_len)])
855 /// This computes the arity of a constructor. The arity of a constructor
856 /// is how many subpattern patterns of that constructor should be expanded to.
858 /// For instance, a tuple pattern (_, 42, Some([])) has the arity of 3.
859 /// A struct pattern's arity is the number of fields it contains, etc.
860 fn constructor_arity(_cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> u64 {
861 debug!("constructor_arity({:#?}, {:?})", ctor, ty);
863 ty::TyTuple(ref fs) => fs.len() as u64,
864 ty::TySlice(..) | ty::TyArray(..) => match *ctor {
865 Slice(length) => length,
866 ConstantValue(_) => 0,
867 _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
870 ty::TyAdt(adt, _) => {
871 adt.variants[ctor.variant_index_for_adt(adt)].fields.len() as u64
877 /// This computes the types of the sub patterns that a constructor should be
880 /// For instance, a tuple pattern (43u32, 'a') has sub pattern types [u32, char].
881 fn constructor_sub_pattern_tys<'a, 'tcx: 'a>(cx: &MatchCheckCtxt<'a, 'tcx>,
883 ty: Ty<'tcx>) -> Vec<Ty<'tcx>>
885 debug!("constructor_sub_pattern_tys({:#?}, {:?})", ctor, ty);
887 ty::TyTuple(ref fs) => fs.into_iter().map(|t| *t).collect(),
888 ty::TySlice(ty) | ty::TyArray(ty, _) => match *ctor {
889 Slice(length) => (0..length).map(|_| ty).collect(),
890 ConstantValue(_) => vec![],
891 _ => bug!("bad slice pattern {:?} {:?}", ctor, ty)
893 ty::TyRef(_, rty, _) => vec![rty],
894 ty::TyAdt(adt, substs) => {
896 // Use T as the sub pattern type of Box<T>.
897 vec![substs.type_at(0)]
899 adt.variants[ctor.variant_index_for_adt(adt)].fields.iter().map(|field| {
900 let is_visible = adt.is_enum()
901 || field.vis.is_accessible_from(cx.module, cx.tcx);
903 field.ty(cx.tcx, substs)
905 // Treat all non-visible fields as TyErr. They
906 // can't appear in any other pattern from
907 // this match (because they are private),
908 // so their type does not matter - but
909 // we don't want to know they are
920 fn slice_pat_covered_by_constructor<'tcx>(
921 tcx: TyCtxt<'_, 'tcx, '_>,
924 prefix: &[Pattern<'tcx>],
925 slice: &Option<Pattern<'tcx>>,
926 suffix: &[Pattern<'tcx>]
927 ) -> Result<bool, ErrorReported> {
928 let data: &[u8] = match *ctor {
929 ConstantValue(const_val) => {
930 let val = match const_val.val {
931 ConstValue::Unevaluated(..) |
932 ConstValue::ByRef(..) => bug!("unexpected ConstValue: {:?}", const_val),
933 ConstValue::Scalar(val) | ConstValue::ScalarPair(val, _) => val,
935 if let Ok(ptr) = val.to_ptr() {
936 let is_array_ptr = const_val.ty
938 .and_then(|t| t.ty.builtin_index())
939 .map_or(false, |t| t == tcx.types.u8);
940 assert!(is_array_ptr);
941 tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id).bytes.as_ref()
943 bug!("unexpected non-ptr ConstantValue")
949 let pat_len = prefix.len() + suffix.len();
950 if data.len() < pat_len || (slice.is_none() && data.len() > pat_len) {
955 data[..prefix.len()].iter().zip(prefix).chain(
956 data[data.len()-suffix.len()..].iter().zip(suffix))
959 box PatternKind::Constant { value } => {
960 let b = value.unwrap_bits(tcx, ty::ParamEnv::empty().and(pat.ty));
961 assert_eq!(b as u8 as u128, b);
973 fn constructor_covered_by_range<'a, 'tcx>(
974 tcx: TyCtxt<'a, 'tcx, 'tcx>,
975 ctor: &Constructor<'tcx>,
976 from: &'tcx ty::Const<'tcx>, to: &'tcx ty::Const<'tcx>,
979 ) -> Result<bool, ErrorReported> {
980 trace!("constructor_covered_by_range {:#?}, {:#?}, {:#?}, {}", ctor, from, to, ty);
981 let cmp_from = |c_from| compare_const_vals(tcx, c_from, from, ty::ParamEnv::empty().and(ty))
982 .map(|res| res != Ordering::Less);
983 let cmp_to = |c_to| compare_const_vals(tcx, c_to, to, ty::ParamEnv::empty().and(ty));
984 macro_rules! some_or_ok {
988 None => return Ok(false), // not char or int
993 ConstantValue(value) => {
994 let to = some_or_ok!(cmp_to(value));
995 let end = (to == Ordering::Less) ||
996 (end == RangeEnd::Included && to == Ordering::Equal);
997 Ok(some_or_ok!(cmp_from(value)) && end)
999 ConstantRange(from, to, RangeEnd::Included) => {
1000 let to = some_or_ok!(cmp_to(to));
1001 let end = (to == Ordering::Less) ||
1002 (end == RangeEnd::Included && to == Ordering::Equal);
1003 Ok(some_or_ok!(cmp_from(from)) && end)
1005 ConstantRange(from, to, RangeEnd::Excluded) => {
1006 let to = some_or_ok!(cmp_to(to));
1007 let end = (to == Ordering::Less) ||
1008 (end == RangeEnd::Excluded && to == Ordering::Equal);
1009 Ok(some_or_ok!(cmp_from(from)) && end)
1016 fn patterns_for_variant<'p, 'a: 'p, 'tcx: 'a>(
1017 subpatterns: &'p [FieldPattern<'tcx>],
1018 wild_patterns: &[&'p Pattern<'tcx>])
1019 -> Vec<&'p Pattern<'tcx>>
1021 let mut result = wild_patterns.to_owned();
1023 for subpat in subpatterns {
1024 result[subpat.field.index()] = &subpat.pattern;
1027 debug!("patterns_for_variant({:#?}, {:#?}) = {:#?}", subpatterns, wild_patterns, result);
1031 /// This is the main specialization step. It expands the first pattern in the given row
1032 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
1033 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
1035 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
1036 /// different patterns.
1037 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
1038 /// fields filled with wild patterns.
1039 fn specialize<'p, 'a: 'p, 'tcx: 'a>(
1040 cx: &mut MatchCheckCtxt<'a, 'tcx>,
1041 r: &[&'p Pattern<'tcx>],
1042 constructor: &Constructor<'tcx>,
1043 wild_patterns: &[&'p Pattern<'tcx>])
1044 -> Option<Vec<&'p Pattern<'tcx>>>
1048 let head: Option<Vec<&Pattern>> = match *pat.kind {
1049 PatternKind::Binding { .. } | PatternKind::Wild => {
1050 Some(wild_patterns.to_owned())
1053 PatternKind::Variant { adt_def, variant_index, ref subpatterns, .. } => {
1054 let ref variant = adt_def.variants[variant_index];
1055 if *constructor == Variant(variant.did) {
1056 Some(patterns_for_variant(subpatterns, wild_patterns))
1062 PatternKind::Leaf { ref subpatterns } => {
1063 Some(patterns_for_variant(subpatterns, wild_patterns))
1065 PatternKind::Deref { ref subpattern } => {
1066 Some(vec![subpattern])
1069 PatternKind::Constant { value } => {
1070 match *constructor {
1072 if let Some(ptr) = value.to_ptr() {
1073 let is_array_ptr = value.ty
1074 .builtin_deref(true)
1075 .and_then(|t| t.ty.builtin_index())
1076 .map_or(false, |t| t == cx.tcx.types.u8);
1077 assert!(is_array_ptr);
1078 let data_len = cx.tcx
1081 .unwrap_memory(ptr.alloc_id)
1084 if wild_patterns.len() == data_len {
1085 Some(cx.lower_byte_str_pattern(pat))
1091 "unexpected const-val {:?} with ctor {:?}", value, constructor)
1095 match constructor_covered_by_range(
1097 constructor, value, value, RangeEnd::Included,
1100 Ok(true) => Some(vec![]),
1102 Err(ErrorReported) => None,
1108 PatternKind::Range { lo, hi, ref end } => {
1109 match constructor_covered_by_range(
1111 constructor, lo, hi, end.clone(), lo.ty,
1113 Ok(true) => Some(vec![]),
1115 Err(ErrorReported) => None,
1119 PatternKind::Array { ref prefix, ref slice, ref suffix } |
1120 PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
1121 match *constructor {
1123 let pat_len = prefix.len() + suffix.len();
1124 if let Some(slice_count) = wild_patterns.len().checked_sub(pat_len) {
1125 if slice_count == 0 || slice.is_some() {
1127 prefix.iter().chain(
1128 wild_patterns.iter().map(|p| *p)
1141 ConstantValue(..) => {
1142 match slice_pat_covered_by_constructor(
1143 cx.tcx, pat.span, constructor, prefix, slice, suffix
1145 Ok(true) => Some(vec![]),
1147 Err(ErrorReported) => None
1150 _ => span_bug!(pat.span,
1151 "unexpected ctor {:?} for slice pat", constructor)
1155 debug!("specialize({:#?}, {:#?}) = {:#?}", r[0], wild_patterns, head);
1157 head.map(|mut head| {
1158 head.extend_from_slice(&r[1 ..]);