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::*;
27 use std::iter::{range_inclusive, AdditiveIterator, FromIterator, repeat};
30 use syntax::ast::{self, DUMMY_NODE_ID, NodeId, Pat};
31 use syntax::ast_util::walk_pat;
32 use syntax::codemap::{Span, Spanned, DUMMY_SP};
33 use syntax::fold::{Folder, noop_fold_pat};
34 use syntax::print::pprust::pat_to_string;
35 use syntax::parse::token;
37 use syntax::visit::{self, Visitor, FnKind};
38 use util::ppaux::ty_to_string;
40 pub const DUMMY_WILD_PAT: &'static Pat = &Pat {
42 node: ast::PatWild(ast::PatWildSingle),
46 struct Matrix<'a>(Vec<Vec<&'a Pat>>);
48 /// Pretty-printer for matrices of patterns, example:
49 /// ++++++++++++++++++++++++++
50 /// + _ + .index(&FullRange) +
51 /// ++++++++++++++++++++++++++
52 /// + true + [First] +
53 /// ++++++++++++++++++++++++++
54 /// + true + [Second(true)] +
55 /// ++++++++++++++++++++++++++
57 /// ++++++++++++++++++++++++++
58 /// + _ + [_, _, ..tail] +
59 /// ++++++++++++++++++++++++++
60 impl<'a> fmt::Show for Matrix<'a> {
61 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
62 try!(write!(f, "\n"));
64 let &Matrix(ref m) = self;
65 let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| {
67 .map(|&pat| pat_to_string(&*pat))
68 .collect::<Vec<String>>()
71 let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0u);
72 assert!(m.iter().all(|row| row.len() == column_count));
73 let column_widths: Vec<uint> = range(0, column_count).map(|col| {
74 pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0u)
77 let total_width = column_widths.iter().map(|n| *n).sum() + column_count * 3 + 1;
78 let br = repeat('+').take(total_width).collect::<String>();
79 try!(write!(f, "{}\n", br));
80 for row in pretty_printed_matrix.into_iter() {
82 for (column, pat_str) in row.into_iter().enumerate() {
84 try!(write!(f, "{:1$}", pat_str, column_widths[column]));
85 try!(write!(f, " +"));
87 try!(write!(f, "\n"));
88 try!(write!(f, "{}\n", br));
94 impl<'a> FromIterator<Vec<&'a Pat>> for Matrix<'a> {
95 fn from_iter<T: Iterator<Item=Vec<&'a Pat>>>(iterator: T) -> Matrix<'a> {
96 Matrix(iterator.collect())
100 pub struct MatchCheckCtxt<'a, 'tcx: 'a> {
101 pub tcx: &'a ty::ctxt<'tcx>,
102 pub param_env: ParameterEnvironment<'a, 'tcx>,
105 #[derive(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 #[derive(Clone, PartialEq)]
125 UsefulWithWitness(Vec<P<Pat>>),
130 enum WitnessPreference {
135 impl<'a, 'tcx, 'v> Visitor<'v> for MatchCheckCtxt<'a, 'tcx> {
136 fn visit_expr(&mut self, ex: &ast::Expr) {
137 check_expr(self, ex);
139 fn visit_local(&mut self, l: &ast::Local) {
140 check_local(self, l);
142 fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v ast::FnDecl,
143 b: &'v ast::Block, s: Span, n: NodeId) {
144 check_fn(self, fk, fd, b, s, n);
148 pub fn check_crate(tcx: &ty::ctxt) {
149 visit::walk_crate(&mut MatchCheckCtxt {
151 param_env: ty::empty_parameter_environment(tcx),
153 tcx.sess.abort_if_errors();
156 fn check_expr(cx: &mut MatchCheckCtxt, ex: &ast::Expr) {
157 visit::walk_expr(cx, ex);
159 ast::ExprMatch(ref scrut, ref arms, source) => {
160 for arm in arms.iter() {
161 // First, check legality of move bindings.
162 check_legality_of_move_bindings(cx,
164 arm.pats.index(&FullRange));
166 // Second, if there is a guard on each arm, make sure it isn't
167 // assigning or borrowing anything mutably.
169 Some(ref guard) => check_for_mutation_in_guard(cx, &**guard),
174 let mut static_inliner = StaticInliner::new(cx.tcx);
175 let inlined_arms = arms.iter().map(|arm| {
176 (arm.pats.iter().map(|pat| {
177 static_inliner.fold_pat((*pat).clone())
178 }).collect(), arm.guard.as_ref().map(|e| &**e))
179 }).collect::<Vec<(Vec<P<Pat>>, Option<&ast::Expr>)>>();
181 // Bail out early if inlining failed.
182 if static_inliner.failed {
186 for pat in inlined_arms
188 .flat_map(|&(ref pats, _)| pats.iter()) {
189 // Third, check legality of move bindings.
190 check_legality_of_bindings_in_at_patterns(cx, &**pat);
192 // Fourth, check if there are any references to NaN that we should warn about.
193 check_for_static_nan(cx, &**pat);
195 // Fifth, check if for any of the patterns that match an enumerated type
196 // are bindings with the same name as one of the variants of said type.
197 check_for_bindings_named_the_same_as_variants(cx, &**pat);
200 // Fourth, check for unreachable arms.
201 check_arms(cx, inlined_arms.index(&FullRange), source);
203 // Finally, check if the whole match expression is exhaustive.
204 // Check for empty enum, because is_useful only works on inhabited types.
205 let pat_ty = node_id_to_type(cx.tcx, scrut.id);
206 if inlined_arms.is_empty() {
207 if !type_is_empty(cx.tcx, pat_ty) {
208 // We know the type is inhabited, so this must be wrong
209 span_err!(cx.tcx.sess, ex.span, E0002,
210 "non-exhaustive patterns: type {} is non-empty",
211 ty_to_string(cx.tcx, pat_ty)
214 // If the type *is* empty, it's vacuously exhaustive
218 let matrix: Matrix = inlined_arms
220 .filter(|&&(_, guard)| guard.is_none())
221 .flat_map(|arm| arm.0.iter())
222 .map(|pat| vec![&**pat])
224 check_exhaustive(cx, ex.span, &matrix);
226 ast::ExprForLoop(ref pat, _, _, _) => {
227 let mut static_inliner = StaticInliner::new(cx.tcx);
228 is_refutable(cx, &*static_inliner.fold_pat((*pat).clone()), |uncovered_pat| {
229 cx.tcx.sess.span_err(
231 format!("refutable pattern in `for` loop binding: \
233 pat_to_string(uncovered_pat)).index(&FullRange));
236 // Check legality of move bindings.
237 check_legality_of_move_bindings(cx, false, slice::ref_slice(pat));
238 check_legality_of_bindings_in_at_patterns(cx, &**pat);
244 fn is_expr_const_nan(tcx: &ty::ctxt, expr: &ast::Expr) -> bool {
245 match eval_const_expr(tcx, expr) {
246 const_float(f) => f.is_nan(),
251 fn check_for_bindings_named_the_same_as_variants(cx: &MatchCheckCtxt, pat: &Pat) {
254 ast::PatIdent(ast::BindByValue(ast::MutImmutable), ident, None) => {
255 let pat_ty = ty::pat_ty(cx.tcx, p);
256 if let ty::ty_enum(def_id, _) = pat_ty.sty {
257 let def = cx.tcx.def_map.borrow().get(&p.id).cloned();
258 if let Some(DefLocal(_)) = def {
259 if ty::enum_variants(cx.tcx, def_id).iter().any(|variant|
260 token::get_name(variant.name) == token::get_name(ident.node.name)
261 && variant.args.len() == 0
263 span_warn!(cx.tcx.sess, p.span, E0170,
264 "pattern binding `{}` is named the same as one \
265 of the variants of the type `{}`",
266 token::get_ident(ident.node).get(), ty_to_string(cx.tcx, pat_ty));
267 span_help!(cx.tcx.sess, p.span,
268 "if you meant to match on a variant, \
269 consider making the path in the pattern qualified: `{}::{}`",
270 ty_to_string(cx.tcx, pat_ty), token::get_ident(ident.node).get());
281 // Check that we do not match against a static NaN (#6804)
282 fn check_for_static_nan(cx: &MatchCheckCtxt, pat: &Pat) {
285 ast::PatLit(ref expr) if is_expr_const_nan(cx.tcx, &**expr) => {
286 span_warn!(cx.tcx.sess, p.span, E0003,
287 "unmatchable NaN in pattern, \
288 use the is_nan method in a guard instead");
296 // Check for unreachable patterns
297 fn check_arms(cx: &MatchCheckCtxt,
298 arms: &[(Vec<P<Pat>>, Option<&ast::Expr>)],
299 source: ast::MatchSource) {
300 let mut seen = Matrix(vec![]);
301 let mut printed_if_let_err = false;
302 for &(ref pats, guard) in arms.iter() {
303 for pat in pats.iter() {
304 let v = vec![&**pat];
306 match is_useful(cx, &seen, v.index(&FullRange), LeaveOutWitness) {
309 ast::MatchSource::IfLetDesugar { .. } => {
310 if printed_if_let_err {
311 // we already printed an irrefutable if-let pattern error.
312 // We don't want two, that's just confusing.
314 // find the first arm pattern so we can use its span
315 let &(ref first_arm_pats, _) = &arms[0];
316 let first_pat = &first_arm_pats[0];
317 let span = first_pat.span;
318 span_err!(cx.tcx.sess, span, E0162, "irrefutable if-let pattern");
319 printed_if_let_err = true;
323 ast::MatchSource::WhileLetDesugar => {
324 // find the first arm pattern so we can use its span
325 let &(ref first_arm_pats, _) = &arms[0];
326 let first_pat = &first_arm_pats[0];
327 let span = first_pat.span;
328 span_err!(cx.tcx.sess, span, E0165, "irrefutable while-let pattern");
331 ast::MatchSource::Normal => {
332 span_err!(cx.tcx.sess, pat.span, E0001, "unreachable pattern")
337 UsefulWithWitness(_) => unreachable!()
340 let Matrix(mut rows) = seen;
348 fn raw_pat<'a>(p: &'a Pat) -> &'a Pat {
350 ast::PatIdent(_, _, Some(ref s)) => raw_pat(&**s),
355 fn check_exhaustive(cx: &MatchCheckCtxt, sp: Span, matrix: &Matrix) {
356 match is_useful(cx, matrix, &[DUMMY_WILD_PAT], ConstructWitness) {
357 UsefulWithWitness(pats) => {
358 let witness = match pats.index(&FullRange) {
359 [ref witness] => &**witness,
360 [] => DUMMY_WILD_PAT,
363 span_err!(cx.tcx.sess, sp, E0004,
364 "non-exhaustive patterns: `{}` not covered",
365 pat_to_string(witness)
369 // This is good, wildcard pattern isn't reachable
375 fn const_val_to_expr(value: &const_val) -> P<ast::Expr> {
376 let node = match value {
377 &const_bool(b) => ast::LitBool(b),
382 node: ast::ExprLit(P(Spanned { node: node, span: DUMMY_SP })),
387 pub struct StaticInliner<'a, 'tcx: 'a> {
388 pub tcx: &'a ty::ctxt<'tcx>,
392 impl<'a, 'tcx> StaticInliner<'a, 'tcx> {
393 pub fn new<'b>(tcx: &'b ty::ctxt<'tcx>) -> StaticInliner<'b, 'tcx> {
401 impl<'a, 'tcx> Folder for StaticInliner<'a, 'tcx> {
402 fn fold_pat(&mut self, pat: P<Pat>) -> P<Pat> {
404 ast::PatIdent(..) | ast::PatEnum(..) => {
405 let def = self.tcx.def_map.borrow().get(&pat.id).cloned();
407 Some(DefConst(did)) => match lookup_const_by_id(self.tcx, did) {
408 Some(const_expr) => {
409 const_expr_to_pat(self.tcx, const_expr).map(|mut new_pat| {
410 new_pat.span = pat.span;
416 span_err!(self.tcx.sess, pat.span, E0158,
417 "statics cannot be referenced in patterns");
421 _ => noop_fold_pat(pat, self)
424 _ => noop_fold_pat(pat, self)
429 /// Constructs a partial witness for a pattern given a list of
430 /// patterns expanded by the specialization step.
432 /// When a pattern P is discovered to be useful, this function is used bottom-up
433 /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
434 /// of values, V, where each value in that set is not covered by any previously
435 /// used patterns and is covered by the pattern P'. Examples:
437 /// left_ty: tuple of 3 elements
438 /// pats: [10, 20, _] => (10, 20, _)
440 /// left_ty: struct X { a: (bool, &'static str), b: uint}
441 /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 }
442 fn construct_witness(cx: &MatchCheckCtxt, ctor: &Constructor,
443 pats: Vec<&Pat>, left_ty: Ty) -> P<Pat> {
444 let pats_len = pats.len();
445 let mut pats = pats.into_iter().map(|p| P((*p).clone()));
446 let pat = match left_ty.sty {
447 ty::ty_tup(_) => ast::PatTup(pats.collect()),
449 ty::ty_enum(cid, _) | ty::ty_struct(cid, _) => {
450 let (vid, is_structure) = match ctor {
452 (vid, ty::enum_variant_with_id(cx.tcx, cid, vid).arg_names.is_some()),
454 (cid, !ty::is_tuple_struct(cx.tcx, cid))
457 let fields = ty::lookup_struct_fields(cx.tcx, vid);
458 let field_pats: Vec<_> = fields.into_iter()
460 .filter(|&(_, ref pat)| pat.node != ast::PatWild(ast::PatWildSingle))
461 .map(|(field, pat)| Spanned {
463 node: ast::FieldPat {
464 ident: ast::Ident::new(field.name),
469 let has_more_fields = field_pats.len() < pats_len;
470 ast::PatStruct(def_to_path(cx.tcx, vid), field_pats, has_more_fields)
472 ast::PatEnum(def_to_path(cx.tcx, vid), Some(pats.collect()))
476 ty::ty_rptr(_, ty::mt { ty, mutbl }) => {
478 ty::ty_vec(_, Some(n)) => match ctor {
480 assert_eq!(pats_len, n);
481 ast::PatVec(pats.collect(), None, vec!())
485 ty::ty_vec(_, None) => match ctor {
487 assert_eq!(pats_len, n);
488 ast::PatVec(pats.collect(), None, vec!())
492 ty::ty_str => ast::PatWild(ast::PatWildSingle),
495 assert_eq!(pats_len, 1);
496 ast::PatRegion(pats.nth(0).unwrap(), mutbl)
501 ty::ty_vec(_, Some(len)) => {
502 assert_eq!(pats_len, len);
503 ast::PatVec(pats.collect(), None, vec![])
508 ConstantValue(ref v) => ast::PatLit(const_val_to_expr(v)),
509 _ => ast::PatWild(ast::PatWildSingle),
521 fn missing_constructor(cx: &MatchCheckCtxt, &Matrix(ref rows): &Matrix,
522 left_ty: Ty, max_slice_length: uint) -> Option<Constructor> {
523 let used_constructors: Vec<Constructor> = rows.iter()
524 .flat_map(|row| pat_constructors(cx, row[0], left_ty, max_slice_length).into_iter())
526 all_constructors(cx, left_ty, max_slice_length)
528 .find(|c| !used_constructors.contains(c))
531 /// This determines the set of all possible constructors of a pattern matching
532 /// values of type `left_ty`. For vectors, this would normally be an infinite set
533 /// but is instead bounded by the maximum fixed length of slice patterns in
534 /// the column of patterns being analyzed.
535 fn all_constructors(cx: &MatchCheckCtxt, left_ty: Ty,
536 max_slice_length: uint) -> Vec<Constructor> {
539 [true, false].iter().map(|b| ConstantValue(const_bool(*b))).collect(),
541 ty::ty_rptr(_, ty::mt { ty, .. }) => match ty.sty {
542 ty::ty_vec(_, None) =>
543 range_inclusive(0, max_slice_length).map(|length| Slice(length)).collect(),
547 ty::ty_enum(eid, _) =>
548 ty::enum_variants(cx.tcx, eid)
550 .map(|va| Variant(va.id))
558 // Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
560 // Whether a vector `v` of patterns is 'useful' in relation to a set of such
561 // vectors `m` is defined as there being a set of inputs that will match `v`
562 // but not any of the sets in `m`.
564 // This is used both for reachability checking (if a pattern isn't useful in
565 // relation to preceding patterns, it is not reachable) and exhaustiveness
566 // checking (if a wildcard pattern is useful in relation to a matrix, the
567 // matrix isn't exhaustive).
569 // Note: is_useful doesn't work on empty types, as the paper notes.
570 // So it assumes that v is non-empty.
571 fn is_useful(cx: &MatchCheckCtxt,
574 witness: WitnessPreference)
576 let &Matrix(ref rows) = matrix;
577 debug!("{:?}", matrix);
578 if rows.len() == 0u {
579 return match witness {
580 ConstructWitness => UsefulWithWitness(vec!()),
581 LeaveOutWitness => Useful
584 if rows[0].len() == 0u {
587 let real_pat = match rows.iter().find(|r| (*r)[0].id != DUMMY_NODE_ID) {
588 Some(r) => raw_pat(r[0]),
589 None if v.len() == 0 => return NotUseful,
592 let left_ty = if real_pat.id == DUMMY_NODE_ID {
595 ty::pat_ty(cx.tcx, &*real_pat)
598 let max_slice_length = rows.iter().filter_map(|row| match row[0].node {
599 ast::PatVec(ref before, _, ref after) => Some(before.len() + after.len()),
601 }).max().map_or(0, |v| v + 1);
603 let constructors = pat_constructors(cx, v[0], left_ty, max_slice_length);
604 if constructors.is_empty() {
605 match missing_constructor(cx, matrix, left_ty, max_slice_length) {
607 all_constructors(cx, left_ty, max_slice_length).into_iter().map(|c| {
608 match is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness) {
609 UsefulWithWitness(pats) => UsefulWithWitness({
610 let arity = constructor_arity(cx, &c, left_ty);
612 let pat_slice = pats.index(&FullRange);
613 let subpats: Vec<_> = range(0, arity).map(|i| {
614 pat_slice.get(i).map_or(DUMMY_WILD_PAT, |p| &**p)
616 vec![construct_witness(cx, &c, subpats, left_ty)]
618 result.extend(pats.into_iter().skip(arity));
623 }).find(|result| result != &NotUseful).unwrap_or(NotUseful)
626 Some(constructor) => {
627 let matrix = rows.iter().filter_map(|r| {
628 if pat_is_binding_or_wild(&cx.tcx.def_map, raw_pat(r[0])) {
629 Some(r.tail().to_vec())
634 match is_useful(cx, &matrix, v.tail(), witness) {
635 UsefulWithWitness(pats) => {
636 let arity = constructor_arity(cx, &constructor, left_ty);
637 let wild_pats: Vec<_> = repeat(DUMMY_WILD_PAT).take(arity).collect();
638 let enum_pat = construct_witness(cx, &constructor, wild_pats, left_ty);
639 let mut new_pats = vec![enum_pat];
640 new_pats.extend(pats.into_iter());
641 UsefulWithWitness(new_pats)
648 constructors.into_iter().map(|c|
649 is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness)
650 ).find(|result| result != &NotUseful).unwrap_or(NotUseful)
654 fn is_useful_specialized(cx: &MatchCheckCtxt, &Matrix(ref m): &Matrix,
655 v: &[&Pat], ctor: Constructor, lty: Ty,
656 witness: WitnessPreference) -> Usefulness {
657 let arity = constructor_arity(cx, &ctor, lty);
658 let matrix = Matrix(m.iter().filter_map(|r| {
659 specialize(cx, r.index(&FullRange), &ctor, 0u, arity)
661 match specialize(cx, v, &ctor, 0u, arity) {
662 Some(v) => is_useful(cx, &matrix, v.index(&FullRange), witness),
667 /// Determines the constructors that the given pattern can be specialized to.
669 /// In most cases, there's only one constructor that a specific pattern
670 /// represents, such as a specific enum variant or a specific literal value.
671 /// Slice patterns, however, can match slices of different lengths. For instance,
672 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
674 /// On the other hand, a wild pattern and an identifier pattern cannot be
675 /// specialized in any way.
676 fn pat_constructors(cx: &MatchCheckCtxt, p: &Pat,
677 left_ty: Ty, max_slice_length: uint) -> Vec<Constructor> {
678 let pat = raw_pat(p);
681 match cx.tcx.def_map.borrow().get(&pat.id) {
682 Some(&DefConst(..)) =>
683 cx.tcx.sess.span_bug(pat.span, "const pattern should've \
685 Some(&DefStruct(_)) => vec!(Single),
686 Some(&DefVariant(_, id, _)) => vec!(Variant(id)),
690 match cx.tcx.def_map.borrow().get(&pat.id) {
691 Some(&DefConst(..)) =>
692 cx.tcx.sess.span_bug(pat.span, "const pattern should've \
694 Some(&DefVariant(_, id, _)) => vec!(Variant(id)),
697 ast::PatStruct(..) =>
698 match cx.tcx.def_map.borrow().get(&pat.id) {
699 Some(&DefConst(..)) =>
700 cx.tcx.sess.span_bug(pat.span, "const pattern should've \
702 Some(&DefVariant(_, id, _)) => vec!(Variant(id)),
705 ast::PatLit(ref expr) =>
706 vec!(ConstantValue(eval_const_expr(cx.tcx, &**expr))),
707 ast::PatRange(ref lo, ref hi) =>
708 vec!(ConstantRange(eval_const_expr(cx.tcx, &**lo), eval_const_expr(cx.tcx, &**hi))),
709 ast::PatVec(ref before, ref slice, ref after) =>
711 ty::ty_vec(_, Some(_)) => vec!(Single),
712 _ => if slice.is_some() {
713 range_inclusive(before.len() + after.len(), max_slice_length)
714 .map(|length| Slice(length))
717 vec!(Slice(before.len() + after.len()))
720 ast::PatBox(_) | ast::PatTup(_) | ast::PatRegion(..) =>
725 cx.tcx.sess.bug("unexpanded macro")
729 /// This computes the arity of a constructor. The arity of a constructor
730 /// is how many subpattern patterns of that constructor should be expanded to.
732 /// For instance, a tuple pattern (_, 42u, Some(.index(&FullRange))) has the arity of 3.
733 /// A struct pattern's arity is the number of fields it contains, etc.
734 pub fn constructor_arity(cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> uint {
736 ty::ty_tup(ref fs) => fs.len(),
737 ty::ty_uniq(_) => 1u,
738 ty::ty_rptr(_, ty::mt { ty, .. }) => match ty.sty {
739 ty::ty_vec(_, None) => match *ctor {
740 Slice(length) => length,
741 ConstantValue(_) => 0u,
747 ty::ty_enum(eid, _) => {
749 Variant(id) => enum_variant_with_id(cx.tcx, eid, id).args.len(),
753 ty::ty_struct(cid, _) => ty::lookup_struct_fields(cx.tcx, cid).len(),
754 ty::ty_vec(_, Some(n)) => n,
759 fn range_covered_by_constructor(ctor: &Constructor,
760 from: &const_val, to: &const_val) -> Option<bool> {
761 let (c_from, c_to) = match *ctor {
762 ConstantValue(ref value) => (value, value),
763 ConstantRange(ref from, ref to) => (from, to),
764 Single => return Some(true),
767 let cmp_from = compare_const_vals(c_from, from);
768 let cmp_to = compare_const_vals(c_to, to);
769 match (cmp_from, cmp_to) {
770 (Some(val1), Some(val2)) => Some(val1 >= 0 && val2 <= 0),
775 /// This is the main specialization step. It expands the first pattern in the given row
776 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
777 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
779 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
780 /// different patterns.
781 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
782 /// fields filled with wild patterns.
783 pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat],
784 constructor: &Constructor, col: uint, arity: uint) -> Option<Vec<&'a Pat>> {
786 id: pat_id, ref node, span: pat_span
788 let head: Option<Vec<&Pat>> = match *node {
790 Some(repeat(DUMMY_WILD_PAT).take(arity).collect()),
792 ast::PatIdent(_, _, _) => {
793 let opt_def = cx.tcx.def_map.borrow().get(&pat_id).cloned();
795 Some(DefConst(..)) =>
796 cx.tcx.sess.span_bug(pat_span, "const pattern should've \
798 Some(DefVariant(_, id, _)) => if *constructor == Variant(id) {
803 _ => Some(repeat(DUMMY_WILD_PAT).take(arity).collect())
807 ast::PatEnum(_, ref args) => {
808 let def = cx.tcx.def_map.borrow()[pat_id].clone();
811 cx.tcx.sess.span_bug(pat_span, "const pattern should've \
813 DefVariant(_, id, _) if *constructor != Variant(id) => None,
814 DefVariant(..) | DefStruct(..) => {
816 &Some(ref args) => args.iter().map(|p| &**p).collect(),
817 &None => repeat(DUMMY_WILD_PAT).take(arity).collect(),
824 ast::PatStruct(_, ref pattern_fields, _) => {
825 // Is this a struct or an enum variant?
826 let def = cx.tcx.def_map.borrow()[pat_id].clone();
827 let class_id = match def {
829 cx.tcx.sess.span_bug(pat_span, "const pattern should've \
831 DefVariant(_, variant_id, _) => if *constructor == Variant(variant_id) {
837 // Assume this is a struct.
838 match ty::ty_to_def_id(node_id_to_type(cx.tcx, pat_id)) {
840 cx.tcx.sess.span_bug(pat_span,
841 "struct pattern wasn't of a \
842 type with a def ID?!")
844 Some(def_id) => Some(def_id),
848 class_id.map(|variant_id| {
849 let struct_fields = ty::lookup_struct_fields(cx.tcx, variant_id);
850 let args = struct_fields.iter().map(|sf| {
851 match pattern_fields.iter().find(|f| f.node.ident.name == sf.name) {
852 Some(ref f) => &*f.node.pat,
860 ast::PatTup(ref args) =>
861 Some(args.iter().map(|p| &**p).collect()),
863 ast::PatBox(ref inner) | ast::PatRegion(ref inner, _) =>
864 Some(vec![&**inner]),
866 ast::PatLit(ref expr) => {
867 let expr_value = eval_const_expr(cx.tcx, &**expr);
868 match range_covered_by_constructor(constructor, &expr_value, &expr_value) {
869 Some(true) => Some(vec![]),
872 cx.tcx.sess.span_err(pat_span, "mismatched types between arms");
878 ast::PatRange(ref from, ref to) => {
879 let from_value = eval_const_expr(cx.tcx, &**from);
880 let to_value = eval_const_expr(cx.tcx, &**to);
881 match range_covered_by_constructor(constructor, &from_value, &to_value) {
882 Some(true) => Some(vec![]),
885 cx.tcx.sess.span_err(pat_span, "mismatched types between arms");
891 ast::PatVec(ref before, ref slice, ref after) => {
893 // Fixed-length vectors.
895 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
896 pats.extend(repeat(DUMMY_WILD_PAT).take(arity - before.len() - after.len()));
897 pats.extend(after.iter().map(|p| &**p));
900 Slice(length) if before.len() + after.len() <= length && slice.is_some() => {
901 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
902 pats.extend(repeat(DUMMY_WILD_PAT).take(arity - before.len() - after.len()));
903 pats.extend(after.iter().map(|p| &**p));
906 Slice(length) if before.len() + after.len() == length => {
907 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
908 pats.extend(after.iter().map(|p| &**p));
911 SliceWithSubslice(prefix, suffix)
912 if before.len() == prefix
913 && after.len() == suffix
914 && slice.is_some() => {
915 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
916 pats.extend(after.iter().map(|p| &**p));
924 cx.tcx.sess.span_err(pat_span, "unexpanded macro");
928 head.map(|mut head| {
929 head.push_all(r.index(&(0..col)));
930 head.push_all(r.index(&((col + 1)..)));
935 fn check_local(cx: &mut MatchCheckCtxt, loc: &ast::Local) {
936 visit::walk_local(cx, loc);
938 let name = match loc.source {
939 ast::LocalLet => "local",
940 ast::LocalFor => "`for` loop"
943 let mut static_inliner = StaticInliner::new(cx.tcx);
944 is_refutable(cx, &*static_inliner.fold_pat(loc.pat.clone()), |pat| {
945 span_err!(cx.tcx.sess, loc.pat.span, E0005,
946 "refutable pattern in {} binding: `{}` not covered",
947 name, pat_to_string(pat)
951 // Check legality of move bindings and `@` patterns.
952 check_legality_of_move_bindings(cx, false, slice::ref_slice(&loc.pat));
953 check_legality_of_bindings_in_at_patterns(cx, &*loc.pat);
956 fn check_fn(cx: &mut MatchCheckCtxt,
963 visit::FkFnBlock => {}
964 _ => cx.param_env = ParameterEnvironment::for_item(cx.tcx, fn_id),
967 visit::walk_fn(cx, kind, decl, body, sp);
969 for input in decl.inputs.iter() {
970 is_refutable(cx, &*input.pat, |pat| {
971 span_err!(cx.tcx.sess, input.pat.span, E0006,
972 "refutable pattern in function argument: `{}` not covered",
976 check_legality_of_move_bindings(cx, false, slice::ref_slice(&input.pat));
977 check_legality_of_bindings_in_at_patterns(cx, &*input.pat);
981 fn is_refutable<A, F>(cx: &MatchCheckCtxt, pat: &Pat, refutable: F) -> Option<A> where
982 F: FnOnce(&Pat) -> A,
984 let pats = Matrix(vec!(vec!(pat)));
985 match is_useful(cx, &pats, &[DUMMY_WILD_PAT], ConstructWitness) {
986 UsefulWithWitness(pats) => {
987 assert_eq!(pats.len(), 1);
988 Some(refutable(&*pats[0]))
991 Useful => unreachable!()
995 // Legality of move bindings checking
996 fn check_legality_of_move_bindings(cx: &MatchCheckCtxt,
1000 let def_map = &tcx.def_map;
1001 let mut by_ref_span = None;
1002 for pat in pats.iter() {
1003 pat_bindings(def_map, &**pat, |bm, _, span, _path| {
1005 ast::BindByRef(_) => {
1006 by_ref_span = Some(span);
1008 ast::BindByValue(_) => {
1014 let check_move = |&: p: &Pat, sub: Option<&Pat>| {
1015 // check legality of moving out of the enum
1017 // x @ Foo(..) is legal, but x @ Foo(y) isn't.
1018 if sub.map_or(false, |p| pat_contains_bindings(def_map, &*p)) {
1019 span_err!(cx.tcx.sess, p.span, E0007, "cannot bind by-move with sub-bindings");
1020 } else if has_guard {
1021 span_err!(cx.tcx.sess, p.span, E0008, "cannot bind by-move into a pattern guard");
1022 } else if by_ref_span.is_some() {
1023 span_err!(cx.tcx.sess, p.span, E0009,
1024 "cannot bind by-move and by-ref in the same pattern");
1025 span_note!(cx.tcx.sess, by_ref_span.unwrap(), "by-ref binding occurs here");
1029 for pat in pats.iter() {
1030 walk_pat(&**pat, |p| {
1031 if pat_is_binding(def_map, &*p) {
1033 ast::PatIdent(ast::BindByValue(_), _, ref sub) => {
1034 let pat_ty = ty::node_id_to_type(tcx, p.id);
1035 if ty::type_moves_by_default(&cx.param_env, pat.span, pat_ty) {
1036 check_move(p, sub.as_ref().map(|p| &**p));
1039 ast::PatIdent(ast::BindByRef(_), _, _) => {
1042 cx.tcx.sess.span_bug(
1044 format!("binding pattern {} is not an \
1047 p.node).index(&FullRange));
1056 /// Ensures that a pattern guard doesn't borrow by mutable reference or
1058 fn check_for_mutation_in_guard<'a, 'tcx>(cx: &'a MatchCheckCtxt<'a, 'tcx>,
1059 guard: &ast::Expr) {
1060 let mut checker = MutationChecker {
1063 let mut visitor = ExprUseVisitor::new(&mut checker,
1064 &checker.cx.param_env);
1065 visitor.walk_expr(guard);
1068 struct MutationChecker<'a, 'tcx: 'a> {
1069 cx: &'a MatchCheckCtxt<'a, 'tcx>,
1072 impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> {
1073 fn matched_pat(&mut self, _: &Pat, _: cmt, _: euv::MatchMode) {}
1074 fn consume(&mut self, _: NodeId, _: Span, _: cmt, _: ConsumeMode) {}
1075 fn consume_pat(&mut self, _: &Pat, _: cmt, _: ConsumeMode) {}
1076 fn borrow(&mut self,
1089 "cannot mutably borrow in a pattern guard")
1091 ImmBorrow | UniqueImmBorrow => {}
1094 fn decl_without_init(&mut self, _: NodeId, _: Span) {}
1095 fn mutate(&mut self, _: NodeId, span: Span, _: cmt, mode: MutateMode) {
1097 JustWrite | WriteAndRead => {
1101 .span_err(span, "cannot assign in a pattern guard")
1108 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
1109 /// because of the way rvalues are handled in the borrow check. (See issue
1111 fn check_legality_of_bindings_in_at_patterns(cx: &MatchCheckCtxt, pat: &Pat) {
1112 AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
1115 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
1116 cx: &'a MatchCheckCtxt<'b, 'tcx>,
1117 bindings_allowed: bool
1120 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
1121 fn visit_pat(&mut self, pat: &Pat) {
1122 if !self.bindings_allowed && pat_is_binding(&self.cx.tcx.def_map, pat) {
1123 self.cx.tcx.sess.span_err(pat.span,
1124 "pattern bindings are not allowed \
1129 ast::PatIdent(_, _, Some(_)) => {
1130 let bindings_were_allowed = self.bindings_allowed;
1131 self.bindings_allowed = false;
1132 visit::walk_pat(self, pat);
1133 self.bindings_allowed = bindings_were_allowed;
1135 _ => visit::walk_pat(self, pat),