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 pub use self::Constructor::*;
12 use self::Usefulness::*;
13 use self::WitnessPreference::*;
15 use middle::const_eval::{compare_const_vals, const_bool, const_float, const_val};
16 use middle::const_eval::{const_expr_to_pat, eval_const_expr, lookup_const_by_id};
18 use middle::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, Init};
19 use middle::expr_use_visitor::{JustWrite, LoanCause, MutateMode};
20 use middle::expr_use_visitor::{WriteAndRead};
21 use middle::expr_use_visitor as euv;
22 use middle::mem_categorization::cmt;
23 use middle::pat_util::*;
25 use middle::ty::{mod, Ty};
27 use std::iter::AdditiveIterator;
28 use std::iter::range_inclusive;
31 use syntax::ast::{mod, DUMMY_NODE_ID, NodeId, Pat};
32 use syntax::ast_util::walk_pat;
33 use syntax::codemap::{Span, Spanned, DUMMY_SP};
34 use syntax::fold::{Folder, noop_fold_pat};
35 use syntax::print::pprust::pat_to_string;
36 use syntax::parse::token;
38 use syntax::visit::{mod, Visitor, FnKind};
39 use util::ppaux::ty_to_string;
41 pub const DUMMY_WILD_PAT: &'static Pat = &Pat {
43 node: ast::PatWild(ast::PatWildSingle),
47 struct Matrix<'a>(Vec<Vec<&'a Pat>>);
49 /// Pretty-printer for matrices of patterns, example:
50 /// ++++++++++++++++++++++++++
52 /// ++++++++++++++++++++++++++
53 /// + true + [First] +
54 /// ++++++++++++++++++++++++++
55 /// + true + [Second(true)] +
56 /// ++++++++++++++++++++++++++
58 /// ++++++++++++++++++++++++++
59 /// + _ + [_, _, ..tail] +
60 /// ++++++++++++++++++++++++++
61 impl<'a> fmt::Show for Matrix<'a> {
62 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
63 try!(write!(f, "\n"));
65 let &Matrix(ref m) = self;
66 let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| {
68 .map(|&pat| pat_to_string(&*pat))
69 .collect::<Vec<String>>()
72 let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0u);
73 assert!(m.iter().all(|row| row.len() == column_count));
74 let column_widths: Vec<uint> = range(0, column_count).map(|col| {
75 pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0u)
78 let total_width = column_widths.iter().map(|n| *n).sum() + column_count * 3 + 1;
79 let br = String::from_char(total_width, '+');
80 try!(write!(f, "{}\n", br));
81 for row in pretty_printed_matrix.into_iter() {
83 for (column, pat_str) in row.into_iter().enumerate() {
85 try!(write!(f, "{:1$}", pat_str, column_widths[column]));
86 try!(write!(f, " +"));
88 try!(write!(f, "\n"));
89 try!(write!(f, "{}\n", br));
95 impl<'a> FromIterator<Vec<&'a Pat>> for Matrix<'a> {
96 fn from_iter<T: Iterator<Vec<&'a Pat>>>(iterator: T) -> Matrix<'a> {
97 Matrix(iterator.collect())
101 pub struct MatchCheckCtxt<'a, 'tcx: 'a> {
102 pub tcx: &'a ty::ctxt<'tcx>
105 #[deriving(Clone, PartialEq)]
106 pub enum Constructor {
107 /// The constructor of all patterns that don't vary by constructor,
108 /// e.g. struct patterns and fixed-length arrays.
113 ConstantValue(const_val),
114 /// Ranges of literal values (2..5).
115 ConstantRange(const_val, const_val),
116 /// Array patterns of length n.
118 /// Array patterns with a subslice.
119 SliceWithSubslice(uint, uint)
122 #[deriving(Clone, PartialEq)]
125 UsefulWithWitness(Vec<P<Pat>>),
129 enum WitnessPreference {
134 impl<'a, 'tcx, 'v> Visitor<'v> for MatchCheckCtxt<'a, 'tcx> {
135 fn visit_expr(&mut self, ex: &ast::Expr) {
136 check_expr(self, ex);
138 fn visit_local(&mut self, l: &ast::Local) {
139 check_local(self, l);
141 fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v ast::FnDecl,
142 b: &'v ast::Block, s: Span, n: NodeId) {
143 check_fn(self, fk, fd, b, s, n);
147 pub fn check_crate(tcx: &ty::ctxt) {
148 visit::walk_crate(&mut MatchCheckCtxt { tcx: tcx }, tcx.map.krate());
149 tcx.sess.abort_if_errors();
152 fn check_expr(cx: &mut MatchCheckCtxt, ex: &ast::Expr) {
153 visit::walk_expr(cx, ex);
155 ast::ExprMatch(ref scrut, ref arms, source) => {
156 for arm in arms.iter() {
157 // First, check legality of move bindings.
158 check_legality_of_move_bindings(cx,
160 arm.pats.as_slice());
162 // Second, if there is a guard on each arm, make sure it isn't
163 // assigning or borrowing anything mutably.
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<&ast::Expr>)>>();
177 // Bail out early if inlining failed.
178 if static_inliner.failed {
182 for pat in inlined_arms
184 .flat_map(|&(ref pats, _)| pats.iter()) {
185 // Third, check legality of move bindings.
186 check_legality_of_bindings_in_at_patterns(cx, &**pat);
188 // Fourth, check if there are any references to NaN that we should warn about.
189 check_for_static_nan(cx, &**pat);
191 // Fifth, check if for any of the patterns that match an enumerated type
192 // are bindings with the same name as one of the variants of said type.
193 check_for_bindings_named_the_same_as_variants(cx, &**pat);
196 // Fourth, check for unreachable arms.
197 check_arms(cx, inlined_arms.as_slice(), source);
199 // Finally, check if the whole match expression is exhaustive.
200 // Check for empty enum, because is_useful only works on inhabited types.
201 let pat_ty = node_id_to_type(cx.tcx, scrut.id);
202 if inlined_arms.is_empty() {
203 if !type_is_empty(cx.tcx, pat_ty) {
204 // We know the type is inhabited, so this must be wrong
205 span_err!(cx.tcx.sess, ex.span, E0002,
206 "non-exhaustive patterns: type {} is non-empty",
207 ty_to_string(cx.tcx, pat_ty)
210 // If the type *is* empty, it's vacuously exhaustive
214 let matrix: Matrix = inlined_arms
216 .filter(|&&(_, guard)| guard.is_none())
217 .flat_map(|arm| arm.ref0().iter())
218 .map(|pat| vec![&**pat])
220 check_exhaustive(cx, ex.span, &matrix);
222 ast::ExprForLoop(ref pat, _, _, _) => {
223 let mut static_inliner = StaticInliner::new(cx.tcx);
224 is_refutable(cx, &*static_inliner.fold_pat((*pat).clone()), |uncovered_pat| {
225 cx.tcx.sess.span_err(
227 format!("refutable pattern in `for` loop binding: \
229 pat_to_string(uncovered_pat)).as_slice());
232 // Check legality of move bindings.
233 check_legality_of_move_bindings(cx, false, slice::ref_slice(pat));
234 check_legality_of_bindings_in_at_patterns(cx, &**pat);
240 fn is_expr_const_nan(tcx: &ty::ctxt, expr: &ast::Expr) -> bool {
241 match eval_const_expr(tcx, expr) {
242 const_float(f) => f.is_nan(),
247 fn check_for_bindings_named_the_same_as_variants(cx: &MatchCheckCtxt, pat: &Pat) {
250 ast::PatIdent(ast::BindByValue(ast::MutImmutable), ident, None) => {
251 let pat_ty = ty::pat_ty(cx.tcx, p);
252 if let ty::ty_enum(def_id, _) = pat_ty.sty {
253 let def = cx.tcx.def_map.borrow().get(&p.id).cloned();
254 if let Some(DefLocal(_)) = def {
255 if ty::enum_variants(cx.tcx, def_id).iter().any(|variant|
256 token::get_name(variant.name) == token::get_name(ident.node.name)
257 && variant.args.len() == 0
259 span_warn!(cx.tcx.sess, p.span, E0170,
260 "pattern binding `{}` is named the same as one \
261 of the variants of the type `{}`",
262 token::get_ident(ident.node).get(), ty_to_string(cx.tcx, pat_ty));
263 span_help!(cx.tcx.sess, p.span,
264 "if you meant to match on a variant, \
265 consider making the path in the pattern qualified: `{}::{}`",
266 ty_to_string(cx.tcx, pat_ty), token::get_ident(ident.node).get());
277 // Check that we do not match against a static NaN (#6804)
278 fn check_for_static_nan(cx: &MatchCheckCtxt, pat: &Pat) {
281 ast::PatLit(ref expr) if is_expr_const_nan(cx.tcx, &**expr) => {
282 span_warn!(cx.tcx.sess, p.span, E0003,
283 "unmatchable NaN in pattern, \
284 use the is_nan method in a guard instead");
292 // Check for unreachable patterns
293 fn check_arms(cx: &MatchCheckCtxt,
294 arms: &[(Vec<P<Pat>>, Option<&ast::Expr>)],
295 source: ast::MatchSource) {
296 let mut seen = Matrix(vec![]);
297 let mut printed_if_let_err = false;
298 for &(ref pats, guard) in arms.iter() {
299 for pat in pats.iter() {
300 let v = vec![&**pat];
302 match is_useful(cx, &seen, v.as_slice(), LeaveOutWitness) {
305 ast::MatchIfLetDesugar => {
306 if printed_if_let_err {
307 // we already printed an irrefutable if-let pattern error.
308 // We don't want two, that's just confusing.
310 // find the first arm pattern so we can use its span
311 let &(ref first_arm_pats, _) = &arms[0];
312 let first_pat = &first_arm_pats[0];
313 let span = first_pat.span;
314 span_err!(cx.tcx.sess, span, E0162, "irrefutable if-let pattern");
315 printed_if_let_err = true;
319 ast::MatchWhileLetDesugar => {
320 // find the first arm pattern so we can use its span
321 let &(ref first_arm_pats, _) = &arms[0];
322 let first_pat = &first_arm_pats[0];
323 let span = first_pat.span;
324 span_err!(cx.tcx.sess, span, E0165, "irrefutable while-let pattern");
327 ast::MatchNormal => {
328 span_err!(cx.tcx.sess, pat.span, E0001, "unreachable pattern")
333 UsefulWithWitness(_) => unreachable!()
336 let Matrix(mut rows) = seen;
344 fn raw_pat<'a>(p: &'a Pat) -> &'a Pat {
346 ast::PatIdent(_, _, Some(ref s)) => raw_pat(&**s),
351 fn check_exhaustive(cx: &MatchCheckCtxt, sp: Span, matrix: &Matrix) {
352 match is_useful(cx, matrix, &[DUMMY_WILD_PAT], ConstructWitness) {
353 UsefulWithWitness(pats) => {
354 let witness = match pats.as_slice() {
355 [ref witness] => &**witness,
356 [] => DUMMY_WILD_PAT,
359 span_err!(cx.tcx.sess, sp, E0004,
360 "non-exhaustive patterns: `{}` not covered",
361 pat_to_string(witness)
365 // This is good, wildcard pattern isn't reachable
371 fn const_val_to_expr(value: &const_val) -> P<ast::Expr> {
372 let node = match value {
373 &const_bool(b) => ast::LitBool(b),
378 node: ast::ExprLit(P(Spanned { node: node, span: DUMMY_SP })),
383 pub struct StaticInliner<'a, 'tcx: 'a> {
384 pub tcx: &'a ty::ctxt<'tcx>,
388 impl<'a, 'tcx> StaticInliner<'a, 'tcx> {
389 pub fn new<'a>(tcx: &'a ty::ctxt<'tcx>) -> StaticInliner<'a, 'tcx> {
397 impl<'a, 'tcx> Folder for StaticInliner<'a, 'tcx> {
398 fn fold_pat(&mut self, pat: P<Pat>) -> P<Pat> {
400 ast::PatIdent(..) | ast::PatEnum(..) => {
401 let def = self.tcx.def_map.borrow().get(&pat.id).cloned();
403 Some(DefConst(did)) => match lookup_const_by_id(self.tcx, did) {
404 Some(const_expr) => {
405 const_expr_to_pat(self.tcx, const_expr).map(|mut new_pat| {
406 new_pat.span = pat.span;
412 span_err!(self.tcx.sess, pat.span, E0158,
413 "statics cannot be referenced in patterns");
417 _ => noop_fold_pat(pat, self)
420 _ => noop_fold_pat(pat, self)
425 /// Constructs a partial witness for a pattern given a list of
426 /// patterns expanded by the specialization step.
428 /// When a pattern P is discovered to be useful, this function is used bottom-up
429 /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
430 /// of values, V, where each value in that set is not covered by any previously
431 /// used patterns and is covered by the pattern P'. Examples:
433 /// left_ty: tuple of 3 elements
434 /// pats: [10, 20, _] => (10, 20, _)
436 /// left_ty: struct X { a: (bool, &'static str), b: uint}
437 /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 }
438 fn construct_witness(cx: &MatchCheckCtxt, ctor: &Constructor,
439 pats: Vec<&Pat>, left_ty: Ty) -> P<Pat> {
440 let pats_len = pats.len();
441 let mut pats = pats.into_iter().map(|p| P((*p).clone()));
442 let pat = match left_ty.sty {
443 ty::ty_tup(_) => ast::PatTup(pats.collect()),
445 ty::ty_enum(cid, _) | ty::ty_struct(cid, _) => {
446 let (vid, is_structure) = match ctor {
448 (vid, ty::enum_variant_with_id(cx.tcx, cid, vid).arg_names.is_some()),
450 (cid, !ty::is_tuple_struct(cx.tcx, cid))
453 let fields = ty::lookup_struct_fields(cx.tcx, vid);
454 let field_pats: Vec<_> = fields.into_iter()
456 .filter(|&(_, ref pat)| pat.node != ast::PatWild(ast::PatWildSingle))
457 .map(|(field, pat)| Spanned {
459 node: ast::FieldPat {
460 ident: ast::Ident::new(field.name),
465 let has_more_fields = field_pats.len() < pats_len;
466 ast::PatStruct(def_to_path(cx.tcx, vid), field_pats, has_more_fields)
468 ast::PatEnum(def_to_path(cx.tcx, vid), Some(pats.collect()))
472 ty::ty_rptr(_, ty::mt { ty, .. }) => {
474 ty::ty_vec(_, Some(n)) => match ctor {
476 assert_eq!(pats_len, n);
477 ast::PatVec(pats.collect(), None, vec!())
481 ty::ty_vec(_, None) => match ctor {
483 assert_eq!(pats_len, n);
484 ast::PatVec(pats.collect(), None, vec!())
488 ty::ty_str => ast::PatWild(ast::PatWildSingle),
491 assert_eq!(pats_len, 1);
492 ast::PatRegion(pats.nth(0).unwrap())
497 ty::ty_vec(_, Some(len)) => {
498 assert_eq!(pats_len, len);
499 ast::PatVec(pats.collect(), None, vec![])
504 ConstantValue(ref v) => ast::PatLit(const_val_to_expr(v)),
505 _ => ast::PatWild(ast::PatWildSingle),
517 fn missing_constructor(cx: &MatchCheckCtxt, &Matrix(ref rows): &Matrix,
518 left_ty: Ty, max_slice_length: uint) -> Option<Constructor> {
519 let used_constructors: Vec<Constructor> = rows.iter()
520 .flat_map(|row| pat_constructors(cx, row[0], left_ty, max_slice_length).into_iter())
522 all_constructors(cx, left_ty, max_slice_length)
524 .find(|c| !used_constructors.contains(c))
527 /// This determines the set of all possible constructors of a pattern matching
528 /// values of type `left_ty`. For vectors, this would normally be an infinite set
529 /// but is instead bounded by the maximum fixed length of slice patterns in
530 /// the column of patterns being analyzed.
531 fn all_constructors(cx: &MatchCheckCtxt, left_ty: Ty,
532 max_slice_length: uint) -> Vec<Constructor> {
535 [true, false].iter().map(|b| ConstantValue(const_bool(*b))).collect(),
537 ty::ty_rptr(_, ty::mt { ty, .. }) => match ty.sty {
538 ty::ty_vec(_, None) =>
539 range_inclusive(0, max_slice_length).map(|length| Slice(length)).collect(),
543 ty::ty_enum(eid, _) =>
544 ty::enum_variants(cx.tcx, eid)
546 .map(|va| Variant(va.id))
554 // Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
556 // Whether a vector `v` of patterns is 'useful' in relation to a set of such
557 // vectors `m` is defined as there being a set of inputs that will match `v`
558 // but not any of the sets in `m`.
560 // This is used both for reachability checking (if a pattern isn't useful in
561 // relation to preceding patterns, it is not reachable) and exhaustiveness
562 // checking (if a wildcard pattern is useful in relation to a matrix, the
563 // matrix isn't exhaustive).
565 // Note: is_useful doesn't work on empty types, as the paper notes.
566 // So it assumes that v is non-empty.
567 fn is_useful(cx: &MatchCheckCtxt,
570 witness: WitnessPreference)
572 let &Matrix(ref rows) = matrix;
573 debug!("{:}", matrix);
574 if rows.len() == 0u {
575 return match witness {
576 ConstructWitness => UsefulWithWitness(vec!()),
577 LeaveOutWitness => Useful
580 if rows[0].len() == 0u {
583 let real_pat = match rows.iter().find(|r| (*r)[0].id != DUMMY_NODE_ID) {
584 Some(r) => raw_pat(r[0]),
585 None if v.len() == 0 => return NotUseful,
588 let left_ty = if real_pat.id == DUMMY_NODE_ID {
591 ty::pat_ty(cx.tcx, &*real_pat)
594 let max_slice_length = rows.iter().filter_map(|row| match row[0].node {
595 ast::PatVec(ref before, _, ref after) => Some(before.len() + after.len()),
597 }).max().map_or(0, |v| v + 1);
599 let constructors = pat_constructors(cx, v[0], left_ty, max_slice_length);
600 if constructors.is_empty() {
601 match missing_constructor(cx, matrix, left_ty, max_slice_length) {
603 all_constructors(cx, left_ty, max_slice_length).into_iter().map(|c| {
604 match is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness) {
605 UsefulWithWitness(pats) => UsefulWithWitness({
606 let arity = constructor_arity(cx, &c, left_ty);
608 let pat_slice = pats.as_slice();
609 let subpats = Vec::from_fn(arity, |i| {
610 pat_slice.get(i).map_or(DUMMY_WILD_PAT, |p| &**p)
612 vec![construct_witness(cx, &c, subpats, left_ty)]
614 result.extend(pats.into_iter().skip(arity));
619 }).find(|result| result != &NotUseful).unwrap_or(NotUseful)
622 Some(constructor) => {
623 let matrix = rows.iter().filter_map(|r| {
624 if pat_is_binding_or_wild(&cx.tcx.def_map, raw_pat(r[0])) {
625 Some(r.tail().to_vec())
630 match is_useful(cx, &matrix, v.tail(), witness) {
631 UsefulWithWitness(pats) => {
632 let arity = constructor_arity(cx, &constructor, left_ty);
633 let wild_pats = Vec::from_elem(arity, DUMMY_WILD_PAT);
634 let enum_pat = construct_witness(cx, &constructor, wild_pats, left_ty);
635 let mut new_pats = vec![enum_pat];
636 new_pats.extend(pats.into_iter());
637 UsefulWithWitness(new_pats)
644 constructors.into_iter().map(|c|
645 is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness)
646 ).find(|result| result != &NotUseful).unwrap_or(NotUseful)
650 fn is_useful_specialized(cx: &MatchCheckCtxt, &Matrix(ref m): &Matrix,
651 v: &[&Pat], ctor: Constructor, lty: Ty,
652 witness: WitnessPreference) -> Usefulness {
653 let arity = constructor_arity(cx, &ctor, lty);
654 let matrix = Matrix(m.iter().filter_map(|r| {
655 specialize(cx, r.as_slice(), &ctor, 0u, arity)
657 match specialize(cx, v, &ctor, 0u, arity) {
658 Some(v) => is_useful(cx, &matrix, v.as_slice(), witness),
663 /// Determines the constructors that the given pattern can be specialized to.
665 /// In most cases, there's only one constructor that a specific pattern
666 /// represents, such as a specific enum variant or a specific literal value.
667 /// Slice patterns, however, can match slices of different lengths. For instance,
668 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
670 /// On the other hand, a wild pattern and an identifier pattern cannot be
671 /// specialized in any way.
672 fn pat_constructors(cx: &MatchCheckCtxt, p: &Pat,
673 left_ty: Ty, max_slice_length: uint) -> Vec<Constructor> {
674 let pat = raw_pat(p);
677 match cx.tcx.def_map.borrow().get(&pat.id) {
678 Some(&DefConst(..)) =>
679 cx.tcx.sess.span_bug(pat.span, "const pattern should've \
681 Some(&DefStruct(_)) => vec!(Single),
682 Some(&DefVariant(_, id, _)) => vec!(Variant(id)),
686 match cx.tcx.def_map.borrow().get(&pat.id) {
687 Some(&DefConst(..)) =>
688 cx.tcx.sess.span_bug(pat.span, "const pattern should've \
690 Some(&DefVariant(_, id, _)) => vec!(Variant(id)),
693 ast::PatStruct(..) =>
694 match cx.tcx.def_map.borrow().get(&pat.id) {
695 Some(&DefConst(..)) =>
696 cx.tcx.sess.span_bug(pat.span, "const pattern should've \
698 Some(&DefVariant(_, id, _)) => vec!(Variant(id)),
701 ast::PatLit(ref expr) =>
702 vec!(ConstantValue(eval_const_expr(cx.tcx, &**expr))),
703 ast::PatRange(ref lo, ref hi) =>
704 vec!(ConstantRange(eval_const_expr(cx.tcx, &**lo), eval_const_expr(cx.tcx, &**hi))),
705 ast::PatVec(ref before, ref slice, ref after) =>
707 ty::ty_vec(_, Some(_)) => vec!(Single),
708 _ => if slice.is_some() {
709 range_inclusive(before.len() + after.len(), max_slice_length)
710 .map(|length| Slice(length))
713 vec!(Slice(before.len() + after.len()))
716 ast::PatBox(_) | ast::PatTup(_) | ast::PatRegion(..) =>
721 cx.tcx.sess.bug("unexpanded macro")
725 /// This computes the arity of a constructor. The arity of a constructor
726 /// is how many subpattern patterns of that constructor should be expanded to.
728 /// For instance, a tuple pattern (_, 42u, Some([])) has the arity of 3.
729 /// A struct pattern's arity is the number of fields it contains, etc.
730 pub fn constructor_arity(cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> uint {
732 ty::ty_tup(ref fs) => fs.len(),
733 ty::ty_uniq(_) => 1u,
734 ty::ty_rptr(_, ty::mt { ty, .. }) => match ty.sty {
735 ty::ty_vec(_, None) => match *ctor {
736 Slice(length) => length,
737 ConstantValue(_) => 0u,
743 ty::ty_enum(eid, _) => {
745 Variant(id) => enum_variant_with_id(cx.tcx, eid, id).args.len(),
749 ty::ty_struct(cid, _) => ty::lookup_struct_fields(cx.tcx, cid).len(),
750 ty::ty_vec(_, Some(n)) => n,
755 fn range_covered_by_constructor(ctor: &Constructor,
756 from: &const_val, to: &const_val) -> Option<bool> {
757 let (c_from, c_to) = match *ctor {
758 ConstantValue(ref value) => (value, value),
759 ConstantRange(ref from, ref to) => (from, to),
760 Single => return Some(true),
763 let cmp_from = compare_const_vals(c_from, from);
764 let cmp_to = compare_const_vals(c_to, to);
765 match (cmp_from, cmp_to) {
766 (Some(val1), Some(val2)) => Some(val1 >= 0 && val2 <= 0),
771 /// This is the main specialization step. It expands the first pattern in the given row
772 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
773 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
775 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
776 /// different patterns.
777 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
778 /// fields filled with wild patterns.
779 pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat],
780 constructor: &Constructor, col: uint, arity: uint) -> Option<Vec<&'a Pat>> {
782 id: pat_id, ref node, span: pat_span
784 let head: Option<Vec<&Pat>> = match *node {
786 Some(Vec::from_elem(arity, DUMMY_WILD_PAT)),
788 ast::PatIdent(_, _, _) => {
789 let opt_def = cx.tcx.def_map.borrow().get(&pat_id).cloned();
791 Some(DefConst(..)) =>
792 cx.tcx.sess.span_bug(pat_span, "const pattern should've \
794 Some(DefVariant(_, id, _)) => if *constructor == Variant(id) {
799 _ => Some(Vec::from_elem(arity, DUMMY_WILD_PAT))
803 ast::PatEnum(_, ref args) => {
804 let def = cx.tcx.def_map.borrow()[pat_id].clone();
807 cx.tcx.sess.span_bug(pat_span, "const pattern should've \
809 DefVariant(_, id, _) if *constructor != Variant(id) => None,
810 DefVariant(..) | DefStruct(..) => {
812 &Some(ref args) => args.iter().map(|p| &**p).collect(),
813 &None => Vec::from_elem(arity, DUMMY_WILD_PAT)
820 ast::PatStruct(_, ref pattern_fields, _) => {
821 // Is this a struct or an enum variant?
822 let def = cx.tcx.def_map.borrow()[pat_id].clone();
823 let class_id = match def {
825 cx.tcx.sess.span_bug(pat_span, "const pattern should've \
827 DefVariant(_, variant_id, _) => if *constructor == Variant(variant_id) {
833 // Assume this is a struct.
834 match ty::ty_to_def_id(node_id_to_type(cx.tcx, pat_id)) {
836 cx.tcx.sess.span_bug(pat_span,
837 "struct pattern wasn't of a \
838 type with a def ID?!")
840 Some(def_id) => Some(def_id),
844 class_id.map(|variant_id| {
845 let struct_fields = ty::lookup_struct_fields(cx.tcx, variant_id);
846 let args = struct_fields.iter().map(|sf| {
847 match pattern_fields.iter().find(|f| f.node.ident.name == sf.name) {
848 Some(ref f) => &*f.node.pat,
856 ast::PatTup(ref args) =>
857 Some(args.iter().map(|p| &**p).collect()),
859 ast::PatBox(ref inner) | ast::PatRegion(ref inner) =>
860 Some(vec![&**inner]),
862 ast::PatLit(ref expr) => {
863 let expr_value = eval_const_expr(cx.tcx, &**expr);
864 match range_covered_by_constructor(constructor, &expr_value, &expr_value) {
865 Some(true) => Some(vec![]),
868 cx.tcx.sess.span_err(pat_span, "mismatched types between arms");
874 ast::PatRange(ref from, ref to) => {
875 let from_value = eval_const_expr(cx.tcx, &**from);
876 let to_value = eval_const_expr(cx.tcx, &**to);
877 match range_covered_by_constructor(constructor, &from_value, &to_value) {
878 Some(true) => Some(vec![]),
881 cx.tcx.sess.span_err(pat_span, "mismatched types between arms");
887 ast::PatVec(ref before, ref slice, ref after) => {
889 // Fixed-length vectors.
891 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
892 pats.grow_fn(arity - before.len() - after.len(), |_| DUMMY_WILD_PAT);
893 pats.extend(after.iter().map(|p| &**p));
896 Slice(length) if before.len() + after.len() <= length && slice.is_some() => {
897 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
898 pats.grow_fn(arity - before.len() - after.len(), |_| DUMMY_WILD_PAT);
899 pats.extend(after.iter().map(|p| &**p));
902 Slice(length) if before.len() + after.len() == length => {
903 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
904 pats.extend(after.iter().map(|p| &**p));
907 SliceWithSubslice(prefix, suffix)
908 if before.len() == prefix
909 && after.len() == suffix
910 && slice.is_some() => {
911 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
912 pats.extend(after.iter().map(|p| &**p));
920 cx.tcx.sess.span_err(pat_span, "unexpanded macro");
924 head.map(|mut head| {
925 head.push_all(r[..col]);
926 head.push_all(r[col + 1..]);
931 fn check_local(cx: &mut MatchCheckCtxt, loc: &ast::Local) {
932 visit::walk_local(cx, loc);
934 let name = match loc.source {
935 ast::LocalLet => "local",
936 ast::LocalFor => "`for` loop"
939 let mut static_inliner = StaticInliner::new(cx.tcx);
940 is_refutable(cx, &*static_inliner.fold_pat(loc.pat.clone()), |pat| {
941 span_err!(cx.tcx.sess, loc.pat.span, E0005,
942 "refutable pattern in {} binding: `{}` not covered",
943 name, pat_to_string(pat)
947 // Check legality of move bindings and `@` patterns.
948 check_legality_of_move_bindings(cx, false, slice::ref_slice(&loc.pat));
949 check_legality_of_bindings_in_at_patterns(cx, &*loc.pat);
952 fn check_fn(cx: &mut MatchCheckCtxt,
958 visit::walk_fn(cx, kind, decl, body, sp);
959 for input in decl.inputs.iter() {
960 is_refutable(cx, &*input.pat, |pat| {
961 span_err!(cx.tcx.sess, input.pat.span, E0006,
962 "refutable pattern in function argument: `{}` not covered",
966 check_legality_of_move_bindings(cx, false, slice::ref_slice(&input.pat));
967 check_legality_of_bindings_in_at_patterns(cx, &*input.pat);
971 fn is_refutable<A>(cx: &MatchCheckCtxt, pat: &Pat, refutable: |&Pat| -> A) -> Option<A> {
972 let pats = Matrix(vec!(vec!(pat)));
973 match is_useful(cx, &pats, &[DUMMY_WILD_PAT], ConstructWitness) {
974 UsefulWithWitness(pats) => {
975 assert_eq!(pats.len(), 1);
976 Some(refutable(&*pats[0]))
979 Useful => unreachable!()
983 // Legality of move bindings checking
984 fn check_legality_of_move_bindings(cx: &MatchCheckCtxt,
988 let def_map = &tcx.def_map;
989 let mut by_ref_span = None;
990 for pat in pats.iter() {
991 pat_bindings(def_map, &**pat, |bm, _, span, _path| {
993 ast::BindByRef(_) => {
994 by_ref_span = Some(span);
996 ast::BindByValue(_) => {
1002 let check_move: |&Pat, Option<&Pat>| = |p, sub| {
1003 // check legality of moving out of the enum
1005 // x @ Foo(..) is legal, but x @ Foo(y) isn't.
1006 if sub.map_or(false, |p| pat_contains_bindings(def_map, &*p)) {
1007 span_err!(cx.tcx.sess, p.span, E0007, "cannot bind by-move with sub-bindings");
1008 } else if has_guard {
1009 span_err!(cx.tcx.sess, p.span, E0008, "cannot bind by-move into a pattern guard");
1010 } else if by_ref_span.is_some() {
1011 span_err!(cx.tcx.sess, p.span, E0009,
1012 "cannot bind by-move and by-ref in the same pattern");
1013 span_note!(cx.tcx.sess, by_ref_span.unwrap(), "by-ref binding occurs here");
1017 for pat in pats.iter() {
1018 walk_pat(&**pat, |p| {
1019 if pat_is_binding(def_map, &*p) {
1021 ast::PatIdent(ast::BindByValue(_), _, ref sub) => {
1022 let pat_ty = ty::node_id_to_type(tcx, p.id);
1023 if ty::type_moves_by_default(tcx, pat_ty) {
1024 check_move(p, sub.as_ref().map(|p| &**p));
1027 ast::PatIdent(ast::BindByRef(_), _, _) => {
1030 cx.tcx.sess.span_bug(
1032 format!("binding pattern {} is not an \
1035 p.node).as_slice());
1044 /// Ensures that a pattern guard doesn't borrow by mutable reference or
1046 fn check_for_mutation_in_guard<'a, 'tcx>(cx: &'a MatchCheckCtxt<'a, 'tcx>,
1047 guard: &ast::Expr) {
1048 let mut checker = MutationChecker {
1051 let mut visitor = ExprUseVisitor::new(&mut checker, checker.cx.tcx);
1052 visitor.walk_expr(guard);
1055 struct MutationChecker<'a, 'tcx: 'a> {
1056 cx: &'a MatchCheckCtxt<'a, 'tcx>,
1059 impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> {
1060 fn matched_pat(&mut self, _: &Pat, _: cmt, _: euv::MatchMode) {}
1061 fn consume(&mut self, _: NodeId, _: Span, _: cmt, _: ConsumeMode) {}
1062 fn consume_pat(&mut self, _: &Pat, _: cmt, _: ConsumeMode) {}
1063 fn borrow(&mut self,
1076 "cannot mutably borrow in a pattern guard")
1078 ImmBorrow | UniqueImmBorrow => {}
1081 fn decl_without_init(&mut self, _: NodeId, _: Span) {}
1082 fn mutate(&mut self, _: NodeId, span: Span, _: cmt, mode: MutateMode) {
1084 JustWrite | WriteAndRead => {
1088 .span_err(span, "cannot assign in a pattern guard")
1095 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
1096 /// because of the way rvalues are handled in the borrow check. (See issue
1098 fn check_legality_of_bindings_in_at_patterns(cx: &MatchCheckCtxt, pat: &Pat) {
1099 AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
1102 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
1103 cx: &'a MatchCheckCtxt<'b, 'tcx>,
1104 bindings_allowed: bool
1107 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
1108 fn visit_pat(&mut self, pat: &Pat) {
1109 if !self.bindings_allowed && pat_is_binding(&self.cx.tcx.def_map, pat) {
1110 self.cx.tcx.sess.span_err(pat.span,
1111 "pattern bindings are not allowed \
1116 ast::PatIdent(_, _, Some(_)) => {
1117 let bindings_were_allowed = self.bindings_allowed;
1118 self.bindings_allowed = false;
1119 visit::walk_pat(self, pat);
1120 self.bindings_allowed = bindings_were_allowed;
1122 _ => visit::walk_pat(self, pat),