1 // Copyright 2012-2014 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 middle::const_eval::{compare_const_vals, const_bool, const_float, const_nil, const_val};
12 use middle::const_eval::{const_expr_to_pat, eval_const_expr, lookup_const_by_id};
14 use middle::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, Init};
15 use middle::expr_use_visitor::{JustWrite, LoanCause, MutateMode};
16 use middle::expr_use_visitor::{WriteAndRead};
17 use middle::mem_categorization::cmt;
18 use middle::pat_util::*;
22 use std::iter::AdditiveIterator;
23 use std::iter::range_inclusive;
26 use syntax::ast_util::walk_pat;
27 use syntax::codemap::{Span, Spanned, DUMMY_SP};
28 use syntax::fold::{Folder, noop_fold_pat};
29 use syntax::print::pprust::pat_to_string;
30 use syntax::parse::token;
32 use syntax::visit::{mod, Visitor, FnKind};
33 use util::ppaux::ty_to_string;
35 static DUMMY_WILD_PAT: Pat = Pat {
37 node: PatWild(PatWildSingle),
41 struct Matrix<'a>(Vec<Vec<&'a Pat>>);
43 /// Pretty-printer for matrices of patterns, example:
44 /// ++++++++++++++++++++++++++
46 /// ++++++++++++++++++++++++++
47 /// + true + [First] +
48 /// ++++++++++++++++++++++++++
49 /// + true + [Second(true)] +
50 /// ++++++++++++++++++++++++++
52 /// ++++++++++++++++++++++++++
53 /// + _ + [_, _, ..tail] +
54 /// ++++++++++++++++++++++++++
55 impl<'a> fmt::Show for Matrix<'a> {
56 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
57 try!(write!(f, "\n"));
59 let &Matrix(ref m) = self;
60 let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| {
62 .map(|&pat| pat_to_string(&*pat))
63 .collect::<Vec<String>>()
66 let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0u);
67 assert!(m.iter().all(|row| row.len() == column_count));
68 let column_widths: Vec<uint> = range(0, column_count).map(|col| {
69 pretty_printed_matrix.iter().map(|row| row.get(col).len()).max().unwrap_or(0u)
72 let total_width = column_widths.iter().map(|n| *n).sum() + column_count * 3 + 1;
73 let br = String::from_char(total_width, '+');
74 try!(write!(f, "{}\n", br));
75 for row in pretty_printed_matrix.into_iter() {
77 for (column, pat_str) in row.into_iter().enumerate() {
79 f.width = Some(*column_widths.get(column));
80 try!(f.pad(pat_str.as_slice()));
81 try!(write!(f, " +"));
83 try!(write!(f, "\n"));
84 try!(write!(f, "{}\n", br));
90 impl<'a> FromIterator<Vec<&'a Pat>> for Matrix<'a> {
91 fn from_iter<T: Iterator<Vec<&'a Pat>>>(mut iterator: T) -> Matrix<'a> {
92 Matrix(iterator.collect())
96 pub struct MatchCheckCtxt<'a, 'tcx: 'a> {
97 pub tcx: &'a ty::ctxt<'tcx>
100 #[deriving(Clone, PartialEq)]
101 pub enum Constructor {
102 /// The constructor of all patterns that don't vary by constructor,
103 /// e.g. struct patterns and fixed-length arrays.
108 ConstantValue(const_val),
109 /// Ranges of literal values (2..5).
110 ConstantRange(const_val, const_val),
111 /// Array patterns of length n.
113 /// Array patterns with a subslice.
114 SliceWithSubslice(uint, uint)
117 #[deriving(Clone, PartialEq)]
120 UsefulWithWitness(Vec<P<Pat>>),
124 enum WitnessPreference {
129 impl<'a, 'tcx, 'v> Visitor<'v> for MatchCheckCtxt<'a, 'tcx> {
130 fn visit_expr(&mut self, ex: &Expr) {
131 check_expr(self, ex);
133 fn visit_local(&mut self, l: &Local) {
134 check_local(self, l);
136 fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl,
137 b: &'v Block, s: Span, _: NodeId) {
138 check_fn(self, fk, fd, b, s);
142 pub fn check_crate(tcx: &ty::ctxt) {
143 visit::walk_crate(&mut MatchCheckCtxt { tcx: tcx }, tcx.map.krate());
144 tcx.sess.abort_if_errors();
147 fn check_expr(cx: &mut MatchCheckCtxt, ex: &Expr) {
148 visit::walk_expr(cx, ex);
150 ExprMatch(ref scrut, ref arms, source) => {
151 // First, check legality of move bindings.
152 for arm in arms.iter() {
153 check_legality_of_move_bindings(cx,
155 arm.pats.as_slice());
156 for pat in arm.pats.iter() {
157 check_legality_of_bindings_in_at_patterns(cx, &**pat);
161 // Second, if there is a guard on each arm, make sure it isn't
162 // assigning or borrowing anything mutably.
163 for arm in arms.iter() {
165 Some(ref guard) => check_for_mutation_in_guard(cx, &**guard),
170 let mut static_inliner = StaticInliner::new(cx.tcx);
171 let inlined_arms = arms.iter().map(|arm| {
172 (arm.pats.iter().map(|pat| {
173 static_inliner.fold_pat((*pat).clone())
174 }).collect(), arm.guard.as_ref().map(|e| &**e))
175 }).collect::<Vec<(Vec<P<Pat>>, Option<&Expr>)>>();
177 if static_inliner.failed {
181 // Third, check if there are any references to NaN that we should warn about.
182 for &(ref pats, _) in inlined_arms.iter() {
183 check_for_static_nan(cx, pats.as_slice());
186 // Fourth, check for unreachable arms.
187 check_arms(cx, inlined_arms.as_slice(), source);
189 // Finally, check if the whole match expression is exhaustive.
190 // Check for empty enum, because is_useful only works on inhabited types.
191 let pat_ty = node_id_to_type(cx.tcx, scrut.id);
192 if inlined_arms.is_empty() {
193 if !type_is_empty(cx.tcx, pat_ty) {
194 // We know the type is inhabited, so this must be wrong
195 span_err!(cx.tcx.sess, ex.span, E0002,
196 "non-exhaustive patterns: type {} is non-empty",
197 ty_to_string(cx.tcx, pat_ty)
200 // If the type *is* empty, it's vacuously exhaustive
204 let matrix: Matrix = inlined_arms
206 .filter(|&&(_, guard)| guard.is_none())
207 .flat_map(|arm| arm.ref0().iter())
208 .map(|pat| vec![&**pat])
210 check_exhaustive(cx, ex.span, &matrix);
212 ExprForLoop(ref pat, _, _, _) => {
213 let mut static_inliner = StaticInliner::new(cx.tcx);
214 is_refutable(cx, &*static_inliner.fold_pat((*pat).clone()), |uncovered_pat| {
215 cx.tcx.sess.span_err(
217 format!("refutable pattern in `for` loop binding: \
219 pat_to_string(uncovered_pat)).as_slice());
222 // Check legality of move bindings.
223 check_legality_of_move_bindings(cx, false, slice::ref_slice(pat));
224 check_legality_of_bindings_in_at_patterns(cx, &**pat);
230 fn is_expr_const_nan(tcx: &ty::ctxt, expr: &Expr) -> bool {
231 match eval_const_expr(tcx, expr) {
232 const_float(f) => f.is_nan(),
237 // Check that we do not match against a static NaN (#6804)
238 fn check_for_static_nan(cx: &MatchCheckCtxt, pats: &[P<Pat>]) {
239 for pat in pats.iter() {
240 walk_pat(&**pat, |p| {
242 PatLit(ref expr) if is_expr_const_nan(cx.tcx, &**expr) => {
243 span_warn!(cx.tcx.sess, p.span, E0003,
244 "unmatchable NaN in pattern, \
245 use the is_nan method in a guard instead");
254 // Check for unreachable patterns
255 fn check_arms(cx: &MatchCheckCtxt, arms: &[(Vec<P<Pat>>, Option<&Expr>)], source: MatchSource) {
256 let mut seen = Matrix(vec![]);
257 let mut printed_if_let_err = false;
258 for &(ref pats, guard) in arms.iter() {
259 for pat in pats.iter() {
260 let v = vec![&**pat];
262 match is_useful(cx, &seen, v.as_slice(), LeaveOutWitness) {
264 if source == MatchIfLetDesugar {
265 if printed_if_let_err {
266 // we already printed an irrefutable if-let pattern error.
267 // We don't want two, that's just confusing.
269 // find the first arm pattern so we can use its span
270 let &(ref first_arm_pats, _) = &arms[0];
271 let first_pat = first_arm_pats.get(0);
272 let span = first_pat.span;
273 span_err!(cx.tcx.sess, span, E0162, "irrefutable if-let pattern");
274 printed_if_let_err = true;
277 span_err!(cx.tcx.sess, pat.span, E0001, "unreachable pattern");
281 UsefulWithWitness(_) => unreachable!()
284 let Matrix(mut rows) = seen;
292 fn raw_pat<'a>(p: &'a Pat) -> &'a Pat {
294 PatIdent(_, _, Some(ref s)) => raw_pat(&**s),
299 fn check_exhaustive(cx: &MatchCheckCtxt, sp: Span, matrix: &Matrix) {
300 match is_useful(cx, matrix, &[&DUMMY_WILD_PAT], ConstructWitness) {
301 UsefulWithWitness(pats) => {
302 let witness = match pats.as_slice() {
303 [ref witness] => &**witness,
304 [] => &DUMMY_WILD_PAT,
307 span_err!(cx.tcx.sess, sp, E0004,
308 "non-exhaustive patterns: `{}` not covered",
309 pat_to_string(witness)
313 // This is good, wildcard pattern isn't reachable
319 fn const_val_to_expr(value: &const_val) -> P<Expr> {
320 let node = match value {
321 &const_bool(b) => LitBool(b),
322 &const_nil => LitNil,
327 node: ExprLit(P(Spanned { node: node, span: DUMMY_SP })),
332 pub struct StaticInliner<'a, 'tcx: 'a> {
333 pub tcx: &'a ty::ctxt<'tcx>,
337 impl<'a, 'tcx> StaticInliner<'a, 'tcx> {
338 pub fn new<'a>(tcx: &'a ty::ctxt<'tcx>) -> StaticInliner<'a, 'tcx> {
346 impl<'a, 'tcx> Folder for StaticInliner<'a, 'tcx> {
347 fn fold_pat(&mut self, pat: P<Pat>) -> P<Pat> {
349 PatIdent(..) | PatEnum(..) => {
350 let def = self.tcx.def_map.borrow().find_copy(&pat.id);
352 Some(DefStatic(did, _)) => match lookup_const_by_id(self.tcx, did) {
353 Some(const_expr) => {
354 const_expr_to_pat(self.tcx, const_expr).map(|mut new_pat| {
355 new_pat.span = pat.span;
361 span_err!(self.tcx.sess, pat.span, E0158,
362 "extern statics cannot be referenced in patterns");
366 _ => noop_fold_pat(pat, self)
369 _ => noop_fold_pat(pat, self)
374 /// Constructs a partial witness for a pattern given a list of
375 /// patterns expanded by the specialization step.
377 /// When a pattern P is discovered to be useful, this function is used bottom-up
378 /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
379 /// of values, V, where each value in that set is not covered by any previously
380 /// used patterns and is covered by the pattern P'. Examples:
382 /// left_ty: tuple of 3 elements
383 /// pats: [10, 20, _] => (10, 20, _)
385 /// left_ty: struct X { a: (bool, &'static str), b: uint}
386 /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 }
387 fn construct_witness(cx: &MatchCheckCtxt, ctor: &Constructor,
388 pats: Vec<&Pat>, left_ty: ty::t) -> P<Pat> {
389 let pats_len = pats.len();
390 let mut pats = pats.into_iter().map(|p| P((*p).clone()));
391 let pat = match ty::get(left_ty).sty {
392 ty::ty_tup(_) => PatTup(pats.collect()),
394 ty::ty_enum(cid, _) | ty::ty_struct(cid, _) => {
395 let (vid, is_structure) = match ctor {
397 (vid, ty::enum_variant_with_id(cx.tcx, cid, vid).arg_names.is_some()),
399 (cid, ty::lookup_struct_fields(cx.tcx, cid).iter()
400 .any(|field| field.name != token::special_idents::unnamed_field.name))
403 let fields = ty::lookup_struct_fields(cx.tcx, vid);
404 let field_pats: Vec<FieldPat> = fields.into_iter()
406 .filter(|&(_, ref pat)| pat.node != PatWild(PatWildSingle))
407 .map(|(field, pat)| FieldPat {
408 ident: Ident::new(field.name),
411 let has_more_fields = field_pats.len() < pats_len;
412 PatStruct(def_to_path(cx.tcx, vid), field_pats, has_more_fields)
414 PatEnum(def_to_path(cx.tcx, vid), Some(pats.collect()))
418 ty::ty_rptr(_, ty::mt { ty: ty, .. }) => {
419 match ty::get(ty).sty {
420 ty::ty_vec(_, Some(n)) => match ctor {
422 assert_eq!(pats_len, n);
423 PatVec(pats.collect(), None, vec!())
427 ty::ty_vec(_, None) => match ctor {
429 assert_eq!(pats_len, n);
430 PatVec(pats.collect(), None, vec!())
434 ty::ty_str => PatWild(PatWildSingle),
437 assert_eq!(pats_len, 1);
438 PatRegion(pats.nth(0).unwrap())
444 assert_eq!(pats_len, 1);
445 PatBox(pats.nth(0).unwrap())
448 ty::ty_vec(_, Some(len)) => {
449 assert_eq!(pats_len, len);
450 PatVec(pats.collect(), None, vec![])
455 ConstantValue(ref v) => PatLit(const_val_to_expr(v)),
456 _ => PatWild(PatWildSingle),
468 fn missing_constructor(cx: &MatchCheckCtxt, &Matrix(ref rows): &Matrix,
469 left_ty: ty::t, max_slice_length: uint) -> Option<Constructor> {
470 let used_constructors: Vec<Constructor> = rows.iter()
471 .flat_map(|row| pat_constructors(cx, *row.get(0), left_ty, max_slice_length).into_iter())
473 all_constructors(cx, left_ty, max_slice_length)
475 .find(|c| !used_constructors.contains(c))
478 /// This determines the set of all possible constructors of a pattern matching
479 /// values of type `left_ty`. For vectors, this would normally be an infinite set
480 /// but is instead bounded by the maximum fixed length of slice patterns in
481 /// the column of patterns being analyzed.
482 fn all_constructors(cx: &MatchCheckCtxt, left_ty: ty::t,
483 max_slice_length: uint) -> Vec<Constructor> {
484 match ty::get(left_ty).sty {
486 [true, false].iter().map(|b| ConstantValue(const_bool(*b))).collect(),
489 vec!(ConstantValue(const_nil)),
491 ty::ty_rptr(_, ty::mt { ty: ty, .. }) => match ty::get(ty).sty {
492 ty::ty_vec(_, None) =>
493 range_inclusive(0, max_slice_length).map(|length| Slice(length)).collect(),
497 ty::ty_enum(eid, _) =>
498 ty::enum_variants(cx.tcx, eid)
500 .map(|va| Variant(va.id))
508 // Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
510 // Whether a vector `v` of patterns is 'useful' in relation to a set of such
511 // vectors `m` is defined as there being a set of inputs that will match `v`
512 // but not any of the sets in `m`.
514 // This is used both for reachability checking (if a pattern isn't useful in
515 // relation to preceding patterns, it is not reachable) and exhaustiveness
516 // checking (if a wildcard pattern is useful in relation to a matrix, the
517 // matrix isn't exhaustive).
519 // Note: is_useful doesn't work on empty types, as the paper notes.
520 // So it assumes that v is non-empty.
521 fn is_useful(cx: &MatchCheckCtxt,
524 witness: WitnessPreference)
526 let &Matrix(ref rows) = matrix;
527 debug!("{:}", matrix);
528 if rows.len() == 0u {
529 return match witness {
530 ConstructWitness => UsefulWithWitness(vec!()),
531 LeaveOutWitness => Useful
534 if rows.get(0).len() == 0u {
537 let real_pat = match rows.iter().find(|r| r.get(0).id != DUMMY_NODE_ID) {
538 Some(r) => raw_pat(*r.get(0)),
539 None if v.len() == 0 => return NotUseful,
542 let left_ty = if real_pat.id == DUMMY_NODE_ID {
545 ty::pat_ty(cx.tcx, &*real_pat)
548 let max_slice_length = rows.iter().filter_map(|row| match row.get(0).node {
549 PatVec(ref before, _, ref after) => Some(before.len() + after.len()),
551 }).max().map_or(0, |v| v + 1);
553 let constructors = pat_constructors(cx, v[0], left_ty, max_slice_length);
554 if constructors.is_empty() {
555 match missing_constructor(cx, matrix, left_ty, max_slice_length) {
557 all_constructors(cx, left_ty, max_slice_length).into_iter().map(|c| {
558 match is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness) {
559 UsefulWithWitness(pats) => UsefulWithWitness({
560 let arity = constructor_arity(cx, &c, left_ty);
562 let pat_slice = pats.as_slice();
563 let subpats = Vec::from_fn(arity, |i| {
564 pat_slice.get(i).map_or(&DUMMY_WILD_PAT, |p| &**p)
566 vec![construct_witness(cx, &c, subpats, left_ty)]
568 result.extend(pats.into_iter().skip(arity));
573 }).find(|result| result != &NotUseful).unwrap_or(NotUseful)
576 Some(constructor) => {
577 let matrix = rows.iter().filter_map(|r| {
578 if pat_is_binding_or_wild(&cx.tcx.def_map, raw_pat(r[0])) {
579 Some(Vec::from_slice(r.tail()))
584 match is_useful(cx, &matrix, v.tail(), witness) {
585 UsefulWithWitness(pats) => {
586 let arity = constructor_arity(cx, &constructor, left_ty);
587 let wild_pats = Vec::from_elem(arity, &DUMMY_WILD_PAT);
588 let enum_pat = construct_witness(cx, &constructor, wild_pats, left_ty);
589 let mut new_pats = vec![enum_pat];
590 new_pats.extend(pats.into_iter());
591 UsefulWithWitness(new_pats)
598 constructors.into_iter().map(|c|
599 is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness)
600 ).find(|result| result != &NotUseful).unwrap_or(NotUseful)
604 fn is_useful_specialized(cx: &MatchCheckCtxt, &Matrix(ref m): &Matrix,
605 v: &[&Pat], ctor: Constructor, lty: ty::t,
606 witness: WitnessPreference) -> Usefulness {
607 let arity = constructor_arity(cx, &ctor, lty);
608 let matrix = Matrix(m.iter().filter_map(|r| {
609 specialize(cx, r.as_slice(), &ctor, 0u, arity)
611 match specialize(cx, v, &ctor, 0u, arity) {
612 Some(v) => is_useful(cx, &matrix, v.as_slice(), witness),
617 /// Determines the constructors that the given pattern can be specialized to.
619 /// In most cases, there's only one constructor that a specific pattern
620 /// represents, such as a specific enum variant or a specific literal value.
621 /// Slice patterns, however, can match slices of different lengths. For instance,
622 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
624 /// On the other hand, a wild pattern and an identifier pattern cannot be
625 /// specialized in any way.
626 fn pat_constructors(cx: &MatchCheckCtxt, p: &Pat,
627 left_ty: ty::t, max_slice_length: uint) -> Vec<Constructor> {
628 let pat = raw_pat(p);
631 match cx.tcx.def_map.borrow().find(&pat.id) {
632 Some(&DefStatic(..)) =>
633 cx.tcx.sess.span_bug(pat.span, "static pattern should've been rewritten"),
634 Some(&DefStruct(_)) => vec!(Single),
635 Some(&DefVariant(_, id, _)) => vec!(Variant(id)),
639 match cx.tcx.def_map.borrow().find(&pat.id) {
640 Some(&DefStatic(..)) =>
641 cx.tcx.sess.span_bug(pat.span, "static pattern should've been rewritten"),
642 Some(&DefVariant(_, id, _)) => vec!(Variant(id)),
646 match cx.tcx.def_map.borrow().find(&pat.id) {
647 Some(&DefStatic(..)) =>
648 cx.tcx.sess.span_bug(pat.span, "static pattern should've been rewritten"),
649 Some(&DefVariant(_, id, _)) => vec!(Variant(id)),
653 vec!(ConstantValue(eval_const_expr(cx.tcx, &**expr))),
654 PatRange(ref lo, ref hi) =>
655 vec!(ConstantRange(eval_const_expr(cx.tcx, &**lo), eval_const_expr(cx.tcx, &**hi))),
656 PatVec(ref before, ref slice, ref after) =>
657 match ty::get(left_ty).sty {
658 ty::ty_vec(_, Some(_)) => vec!(Single),
659 _ => if slice.is_some() {
660 range_inclusive(before.len() + after.len(), max_slice_length)
661 .map(|length| Slice(length))
664 vec!(Slice(before.len() + after.len()))
667 PatBox(_) | PatTup(_) | PatRegion(..) =>
672 cx.tcx.sess.bug("unexpanded macro")
676 /// This computes the arity of a constructor. The arity of a constructor
677 /// is how many subpattern patterns of that constructor should be expanded to.
679 /// For instance, a tuple pattern (_, 42u, Some([])) has the arity of 3.
680 /// A struct pattern's arity is the number of fields it contains, etc.
681 pub fn constructor_arity(cx: &MatchCheckCtxt, ctor: &Constructor, ty: ty::t) -> uint {
682 match ty::get(ty).sty {
683 ty::ty_tup(ref fs) => fs.len(),
684 ty::ty_box(_) | ty::ty_uniq(_) => 1u,
685 ty::ty_rptr(_, ty::mt { ty: ty, .. }) => match ty::get(ty).sty {
686 ty::ty_vec(_, None) => match *ctor {
687 Slice(length) => length,
688 ConstantValue(_) => 0u,
694 ty::ty_enum(eid, _) => {
696 Variant(id) => enum_variant_with_id(cx.tcx, eid, id).args.len(),
700 ty::ty_struct(cid, _) => ty::lookup_struct_fields(cx.tcx, cid).len(),
701 ty::ty_vec(_, Some(n)) => n,
706 fn range_covered_by_constructor(ctor: &Constructor,
707 from: &const_val, to: &const_val) -> Option<bool> {
708 let (c_from, c_to) = match *ctor {
709 ConstantValue(ref value) => (value, value),
710 ConstantRange(ref from, ref to) => (from, to),
711 Single => return Some(true),
714 let cmp_from = compare_const_vals(c_from, from);
715 let cmp_to = compare_const_vals(c_to, to);
716 match (cmp_from, cmp_to) {
717 (Some(val1), Some(val2)) => Some(val1 >= 0 && val2 <= 0),
722 /// This is the main specialization step. It expands the first pattern in the given row
723 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
724 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
726 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
727 /// different patterns.
728 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
729 /// fields filled with wild patterns.
730 pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat],
731 constructor: &Constructor, col: uint, arity: uint) -> Option<Vec<&'a Pat>> {
733 id: pat_id, node: ref node, span: pat_span
735 let head: Option<Vec<&Pat>> = match node {
738 Some(Vec::from_elem(arity, &DUMMY_WILD_PAT)),
740 &PatIdent(_, _, _) => {
741 let opt_def = cx.tcx.def_map.borrow().find_copy(&pat_id);
743 Some(DefStatic(..)) =>
744 cx.tcx.sess.span_bug(pat_span, "static pattern should've been rewritten"),
745 Some(DefVariant(_, id, _)) => if *constructor == Variant(id) {
750 _ => Some(Vec::from_elem(arity, &DUMMY_WILD_PAT))
754 &PatEnum(_, ref args) => {
755 let def = cx.tcx.def_map.borrow().get_copy(&pat_id);
758 cx.tcx.sess.span_bug(pat_span, "static pattern should've been rewritten"),
759 DefVariant(_, id, _) if *constructor != Variant(id) => None,
760 DefVariant(..) | DefFn(..) | DefStruct(..) => {
762 &Some(ref args) => args.iter().map(|p| &**p).collect(),
763 &None => Vec::from_elem(arity, &DUMMY_WILD_PAT)
770 &PatStruct(_, ref pattern_fields, _) => {
771 // Is this a struct or an enum variant?
772 let def = cx.tcx.def_map.borrow().get_copy(&pat_id);
773 let class_id = match def {
775 cx.tcx.sess.span_bug(pat_span, "static pattern should've been rewritten"),
776 DefVariant(_, variant_id, _) => if *constructor == Variant(variant_id) {
782 // Assume this is a struct.
783 match ty::ty_to_def_id(node_id_to_type(cx.tcx, pat_id)) {
785 cx.tcx.sess.span_bug(pat_span,
786 "struct pattern wasn't of a \
787 type with a def ID?!")
789 Some(def_id) => Some(def_id),
793 class_id.map(|variant_id| {
794 let struct_fields = ty::lookup_struct_fields(cx.tcx, variant_id);
795 let args = struct_fields.iter().map(|sf| {
796 match pattern_fields.iter().find(|f| f.ident.name == sf.name) {
797 Some(ref f) => &*f.pat,
806 Some(args.iter().map(|p| &**p).collect()),
808 &PatBox(ref inner) | &PatRegion(ref inner) =>
809 Some(vec![&**inner]),
811 &PatLit(ref expr) => {
812 let expr_value = eval_const_expr(cx.tcx, &**expr);
813 match range_covered_by_constructor(constructor, &expr_value, &expr_value) {
814 Some(true) => Some(vec![]),
817 cx.tcx.sess.span_err(pat_span, "mismatched types between arms");
823 &PatRange(ref from, ref to) => {
824 let from_value = eval_const_expr(cx.tcx, &**from);
825 let to_value = eval_const_expr(cx.tcx, &**to);
826 match range_covered_by_constructor(constructor, &from_value, &to_value) {
827 Some(true) => Some(vec![]),
830 cx.tcx.sess.span_err(pat_span, "mismatched types between arms");
836 &PatVec(ref before, ref slice, ref after) => {
838 // Fixed-length vectors.
840 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
841 pats.grow_fn(arity - before.len() - after.len(), |_| &DUMMY_WILD_PAT);
842 pats.extend(after.iter().map(|p| &**p));
845 Slice(length) if before.len() + after.len() <= length && slice.is_some() => {
846 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
847 pats.grow_fn(arity - before.len() - after.len(), |_| &DUMMY_WILD_PAT);
848 pats.extend(after.iter().map(|p| &**p));
851 Slice(length) if before.len() + after.len() == length => {
852 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
853 pats.extend(after.iter().map(|p| &**p));
856 SliceWithSubslice(prefix, suffix)
857 if before.len() == prefix
858 && after.len() == suffix
859 && slice.is_some() => {
860 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
861 pats.extend(after.iter().map(|p| &**p));
869 cx.tcx.sess.span_err(pat_span, "unexpanded macro");
873 head.map(|head| head.append(r.slice_to(col)).append(r.slice_from(col + 1)))
876 fn check_local(cx: &mut MatchCheckCtxt, loc: &Local) {
877 visit::walk_local(cx, loc);
879 let name = match loc.source {
881 LocalFor => "`for` loop"
884 let mut static_inliner = StaticInliner::new(cx.tcx);
885 is_refutable(cx, &*static_inliner.fold_pat(loc.pat.clone()), |pat| {
886 span_err!(cx.tcx.sess, loc.pat.span, E0005,
887 "refutable pattern in {} binding: `{}` not covered",
888 name, pat_to_string(pat)
892 // Check legality of move bindings and `@` patterns.
893 check_legality_of_move_bindings(cx, false, slice::ref_slice(&loc.pat));
894 check_legality_of_bindings_in_at_patterns(cx, &*loc.pat);
897 fn check_fn(cx: &mut MatchCheckCtxt,
902 visit::walk_fn(cx, kind, decl, body, sp);
903 for input in decl.inputs.iter() {
904 is_refutable(cx, &*input.pat, |pat| {
905 span_err!(cx.tcx.sess, input.pat.span, E0006,
906 "refutable pattern in function argument: `{}` not covered",
910 check_legality_of_move_bindings(cx, false, slice::ref_slice(&input.pat));
911 check_legality_of_bindings_in_at_patterns(cx, &*input.pat);
915 fn is_refutable<A>(cx: &MatchCheckCtxt, pat: &Pat, refutable: |&Pat| -> A) -> Option<A> {
916 let pats = Matrix(vec!(vec!(pat)));
917 match is_useful(cx, &pats, [&DUMMY_WILD_PAT], ConstructWitness) {
918 UsefulWithWitness(pats) => {
919 assert_eq!(pats.len(), 1);
920 Some(refutable(&*pats[0]))
923 Useful => unreachable!()
927 // Legality of move bindings checking
928 fn check_legality_of_move_bindings(cx: &MatchCheckCtxt,
932 let def_map = &tcx.def_map;
933 let mut by_ref_span = None;
934 for pat in pats.iter() {
935 pat_bindings(def_map, &**pat, |bm, _, span, _path| {
938 by_ref_span = Some(span);
946 let check_move: |&Pat, Option<&Pat>| = |p, sub| {
947 // check legality of moving out of the enum
949 // x @ Foo(..) is legal, but x @ Foo(y) isn't.
950 if sub.map_or(false, |p| pat_contains_bindings(def_map, &*p)) {
951 span_err!(cx.tcx.sess, p.span, E0007, "cannot bind by-move with sub-bindings");
952 } else if has_guard {
953 span_err!(cx.tcx.sess, p.span, E0008, "cannot bind by-move into a pattern guard");
954 } else if by_ref_span.is_some() {
955 span_err!(cx.tcx.sess, p.span, E0009,
956 "cannot bind by-move and by-ref in the same pattern");
957 span_note!(cx.tcx.sess, by_ref_span.unwrap(), "by-ref binding occurs here");
961 for pat in pats.iter() {
962 walk_pat(&**pat, |p| {
963 if pat_is_binding(def_map, &*p) {
965 PatIdent(BindByValue(_), _, ref sub) => {
966 let pat_ty = ty::node_id_to_type(tcx, p.id);
967 if ty::type_moves_by_default(tcx, pat_ty) {
968 check_move(p, sub.as_ref().map(|p| &**p));
971 PatIdent(BindByRef(_), _, _) => {
974 cx.tcx.sess.span_bug(
976 format!("binding pattern {} is not an \
988 /// Ensures that a pattern guard doesn't borrow by mutable reference or
990 fn check_for_mutation_in_guard<'a, 'tcx>(cx: &'a MatchCheckCtxt<'a, 'tcx>, guard: &Expr) {
991 let mut checker = MutationChecker {
994 let mut visitor = ExprUseVisitor::new(&mut checker, checker.cx.tcx);
995 visitor.walk_expr(guard);
998 struct MutationChecker<'a, 'tcx: 'a> {
999 cx: &'a MatchCheckCtxt<'a, 'tcx>,
1002 impl<'a, 'tcx> Delegate for MutationChecker<'a, 'tcx> {
1003 fn consume(&mut self, _: NodeId, _: Span, _: cmt, _: ConsumeMode) {}
1004 fn consume_pat(&mut self, _: &Pat, _: cmt, _: ConsumeMode) {}
1005 fn borrow(&mut self,
1018 "cannot mutably borrow in a pattern guard")
1020 ImmBorrow | UniqueImmBorrow => {}
1023 fn decl_without_init(&mut self, _: NodeId, _: Span) {}
1024 fn mutate(&mut self, _: NodeId, span: Span, _: cmt, mode: MutateMode) {
1026 JustWrite | WriteAndRead => {
1030 .span_err(span, "cannot assign in a pattern guard")
1037 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
1038 /// because of the way rvalues are handled in the borrow check. (See issue
1040 fn check_legality_of_bindings_in_at_patterns(cx: &MatchCheckCtxt, pat: &Pat) {
1041 AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
1044 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
1045 cx: &'a MatchCheckCtxt<'b, 'tcx>,
1046 bindings_allowed: bool
1049 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
1050 fn visit_pat(&mut self, pat: &Pat) {
1051 if !self.bindings_allowed && pat_is_binding(&self.cx.tcx.def_map, pat) {
1052 self.cx.tcx.sess.span_err(pat.span,
1053 "pattern bindings are not allowed \
1058 PatIdent(_, _, Some(_)) => {
1059 let bindings_were_allowed = self.bindings_allowed;
1060 self.bindings_allowed = false;
1061 visit::walk_pat(self, pat);
1062 self.bindings_allowed = bindings_were_allowed;
1064 _ => visit::walk_pat(self, pat),