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::pat_util::*;
18 use std::gc::{Gc, GC};
19 use std::iter::AdditiveIterator;
20 use std::iter::range_inclusive;
22 use syntax::ast_util::{is_unguarded, walk_pat};
23 use syntax::codemap::{Span, Spanned, DUMMY_SP};
24 use syntax::fold::{Folder, noop_fold_pat};
25 use syntax::print::pprust::pat_to_string;
26 use syntax::parse::token;
28 use syntax::visit::{Visitor, FnKind};
29 use util::ppaux::ty_to_string;
31 struct Matrix(Vec<Vec<Gc<Pat>>>);
33 /// Pretty-printer for matrices of patterns, example:
34 /// ++++++++++++++++++++++++++
36 /// ++++++++++++++++++++++++++
37 /// + true + [First] +
38 /// ++++++++++++++++++++++++++
39 /// + true + [Second(true)] +
40 /// ++++++++++++++++++++++++++
42 /// ++++++++++++++++++++++++++
43 /// + _ + [_, _, ..tail] +
44 /// ++++++++++++++++++++++++++
45 impl fmt::Show for Matrix {
46 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
47 try!(write!(f, "\n"));
49 let &Matrix(ref m) = self;
50 let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| {
52 .map(|&pat| pat_to_string(&*pat))
53 .collect::<Vec<String>>()
56 let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0u);
57 assert!(m.iter().all(|row| row.len() == column_count));
58 let column_widths: Vec<uint> = range(0, column_count).map(|col| {
59 pretty_printed_matrix.iter().map(|row| row.get(col).len()).max().unwrap_or(0u)
62 let total_width = column_widths.iter().map(|n| *n).sum() + column_count * 3 + 1;
63 let br = String::from_char(total_width, '+');
64 try!(write!(f, "{}\n", br));
65 for row in pretty_printed_matrix.move_iter() {
67 for (column, pat_str) in row.move_iter().enumerate() {
69 f.width = Some(*column_widths.get(column));
70 try!(f.pad(pat_str.as_slice()));
71 try!(write!(f, " +"));
73 try!(write!(f, "\n"));
74 try!(write!(f, "{}\n", br));
80 impl FromIterator<Vec<Gc<Pat>>> for Matrix {
81 fn from_iter<T: Iterator<Vec<Gc<Pat>>>>(mut iterator: T) -> Matrix {
82 Matrix(iterator.collect())
86 pub struct MatchCheckCtxt<'a> {
90 #[deriving(Clone, PartialEq)]
91 pub enum Constructor {
92 /// The constructor of all patterns that don't vary by constructor,
93 /// e.g. struct patterns and fixed-length arrays.
98 ConstantValue(const_val),
99 /// Ranges of literal values (2..5).
100 ConstantRange(const_val, const_val),
101 /// Array patterns of length n.
105 #[deriving(Clone, PartialEq)]
108 UsefulWithWitness(Vec<Gc<Pat>>),
112 enum WitnessPreference {
117 impl<'a> Visitor<()> for MatchCheckCtxt<'a> {
118 fn visit_expr(&mut self, ex: &Expr, _: ()) {
119 check_expr(self, ex);
121 fn visit_local(&mut self, l: &Local, _: ()) {
122 check_local(self, l);
124 fn visit_fn(&mut self, fk: &FnKind, fd: &FnDecl, b: &Block, s: Span, _: NodeId, _: ()) {
125 check_fn(self, fk, fd, b, s);
129 pub fn check_crate(tcx: &ty::ctxt, krate: &Crate) {
130 let mut cx = MatchCheckCtxt { tcx: tcx };
131 visit::walk_crate(&mut cx, krate, ());
132 tcx.sess.abort_if_errors();
135 fn check_expr(cx: &mut MatchCheckCtxt, ex: &Expr) {
136 visit::walk_expr(cx, ex, ());
138 ExprMatch(scrut, ref arms) => {
139 // First, check legality of move bindings.
140 for arm in arms.iter() {
141 check_legality_of_move_bindings(cx,
143 arm.pats.as_slice());
146 // Second, check for unreachable arms.
147 check_arms(cx, arms.as_slice());
149 // Finally, check if the whole match expression is exhaustive.
150 // Check for empty enum, because is_useful only works on inhabited types.
151 let pat_ty = node_id_to_type(cx.tcx, scrut.id);
153 if !type_is_empty(cx.tcx, pat_ty) {
154 // We know the type is inhabited, so this must be wrong
155 span_err!(cx.tcx.sess, ex.span, E0002,
156 "non-exhaustive patterns: type {} is non-empty",
157 ty_to_string(cx.tcx, pat_ty)
160 // If the type *is* empty, it's vacuously exhaustive
164 let mut static_inliner = StaticInliner { tcx: cx.tcx };
165 let matrix: Matrix = arms
167 .filter(|&arm| is_unguarded(arm))
168 .flat_map(|arm| arm.pats.iter())
169 .map(|pat| vec![static_inliner.fold_pat(*pat)])
171 check_exhaustive(cx, ex.span, &matrix);
177 fn is_expr_const_nan(tcx: &ty::ctxt, expr: &Expr) -> bool {
178 match eval_const_expr(tcx, expr) {
179 const_float(f) => f.is_nan(),
184 // Check for unreachable patterns
185 fn check_arms(cx: &MatchCheckCtxt, arms: &[Arm]) {
186 let mut seen = Matrix(vec!());
187 let mut static_inliner = StaticInliner { tcx: cx.tcx };
188 for arm in arms.iter() {
189 for pat in arm.pats.iter() {
190 let inlined = static_inliner.fold_pat(*pat);
192 // Check that we do not match against a static NaN (#6804)
193 walk_pat(&*inlined, |p| {
195 PatLit(expr) if is_expr_const_nan(cx.tcx, &*expr) => {
196 span_warn!(cx.tcx.sess, pat.span, E0003,
197 "unmatchable NaN in pattern, \
198 use the is_nan method in a guard instead");
205 let v = vec![inlined];
206 match is_useful(cx, &seen, v.as_slice(), LeaveOutWitness) {
207 NotUseful => span_err!(cx.tcx.sess, pat.span, E0001, "unreachable pattern"),
209 UsefulWithWitness(_) => unreachable!()
211 if arm.guard.is_none() {
212 let Matrix(mut rows) = seen;
220 fn raw_pat(p: Gc<Pat>) -> Gc<Pat> {
222 PatIdent(_, _, Some(s)) => { raw_pat(s) }
227 fn check_exhaustive(cx: &MatchCheckCtxt, sp: Span, matrix: &Matrix) {
228 match is_useful(cx, matrix, [wild()], ConstructWitness) {
229 UsefulWithWitness(pats) => {
230 let witness = match pats.as_slice() {
231 [witness] => witness,
235 span_err!(cx.tcx.sess, sp, E0004,
236 "non-exhaustive patterns: `{}` not covered",
237 pat_to_string(&*witness)
241 // This is good, wildcard pattern isn't reachable
247 fn const_val_to_expr(value: &const_val) -> Gc<Expr> {
248 let node = match value {
249 &const_bool(b) => LitBool(b),
250 &const_nil => LitNil,
255 node: ExprLit(box(GC) Spanned { node: node, span: DUMMY_SP }),
260 pub struct StaticInliner<'a> {
261 pub tcx: &'a ty::ctxt
264 impl<'a> Folder for StaticInliner<'a> {
265 fn fold_pat(&mut self, pat: Gc<Pat>) -> Gc<Pat> {
267 PatIdent(..) | PatEnum(..) => {
268 let def = self.tcx.def_map.borrow().find_copy(&pat.id);
270 Some(DefStatic(did, _)) => {
271 let const_expr = lookup_const_by_id(self.tcx, did).unwrap();
272 const_expr_to_pat(self.tcx, const_expr)
274 _ => noop_fold_pat(pat, self)
277 _ => noop_fold_pat(pat, self)
282 /// Constructs a partial witness for a pattern given a list of
283 /// patterns expanded by the specialization step.
285 /// When a pattern P is discovered to be useful, this function is used bottom-up
286 /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
287 /// of values, V, where each value in that set is not covered by any previously
288 /// used patterns and is covered by the pattern P'. Examples:
290 /// left_ty: tuple of 3 elements
291 /// pats: [10, 20, _] => (10, 20, _)
293 /// left_ty: struct X { a: (bool, &'static str), b: uint}
294 /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 }
295 fn construct_witness(cx: &MatchCheckCtxt, ctor: &Constructor,
296 pats: Vec<Gc<Pat>>, left_ty: ty::t) -> Gc<Pat> {
297 let pat = match ty::get(left_ty).sty {
298 ty::ty_tup(_) => PatTup(pats),
300 ty::ty_enum(cid, _) | ty::ty_struct(cid, _) => {
301 let (vid, is_structure) = match ctor {
303 (vid, ty::enum_variant_with_id(cx.tcx, cid, vid).arg_names.is_some()),
305 (cid, ty::lookup_struct_fields(cx.tcx, cid).iter()
306 .any(|field| field.name != token::special_idents::unnamed_field.name))
309 let fields = ty::lookup_struct_fields(cx.tcx, vid);
310 let field_pats: Vec<FieldPat> = fields.move_iter()
312 .filter(|&(_, pat)| pat.node != PatWild)
313 .map(|(field, pat)| FieldPat {
314 ident: Ident::new(field.name),
317 let has_more_fields = field_pats.len() < pats.len();
318 PatStruct(def_to_path(cx.tcx, vid), field_pats, has_more_fields)
320 PatEnum(def_to_path(cx.tcx, vid), Some(pats))
324 ty::ty_rptr(_, ty::mt { ty: ty, .. }) => {
325 match ty::get(ty).sty {
326 ty::ty_vec(_, Some(n)) => match ctor {
328 assert_eq!(pats.len(), n);
329 PatVec(pats, None, vec!())
333 ty::ty_vec(_, None) => match ctor {
335 assert_eq!(pats.len(), n);
336 PatVec(pats, None, vec!())
340 ty::ty_str => PatWild,
343 assert_eq!(pats.len(), 1);
344 PatRegion(pats.get(0).clone())
350 assert_eq!(pats.len(), 1);
351 PatBox(pats.get(0).clone())
354 ty::ty_vec(_, Some(len)) => {
355 assert_eq!(pats.len(), len);
356 PatVec(pats, None, vec!())
361 ConstantValue(ref v) => PatLit(const_val_to_expr(v)),
374 fn missing_constructor(cx: &MatchCheckCtxt, &Matrix(ref rows): &Matrix,
375 left_ty: ty::t, max_slice_length: uint) -> Option<Constructor> {
376 let used_constructors: Vec<Constructor> = rows.iter()
377 .flat_map(|row| pat_constructors(cx, *row.get(0), left_ty, max_slice_length).move_iter())
379 all_constructors(cx, left_ty, max_slice_length)
381 .find(|c| !used_constructors.contains(c))
384 /// This determines the set of all possible constructors of a pattern matching
385 /// values of type `left_ty`. For vectors, this would normally be an infinite set
386 /// but is instead bounded by the maximum fixed length of slice patterns in
387 /// the column of patterns being analyzed.
388 fn all_constructors(cx: &MatchCheckCtxt, left_ty: ty::t,
389 max_slice_length: uint) -> Vec<Constructor> {
390 match ty::get(left_ty).sty {
392 [true, false].iter().map(|b| ConstantValue(const_bool(*b))).collect(),
395 vec!(ConstantValue(const_nil)),
397 ty::ty_rptr(_, ty::mt { ty: ty, .. }) => match ty::get(ty).sty {
398 ty::ty_vec(_, None) =>
399 range_inclusive(0, max_slice_length).map(|length| Slice(length)).collect(),
403 ty::ty_enum(eid, _) =>
404 ty::enum_variants(cx.tcx, eid)
406 .map(|va| Variant(va.id))
414 // Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
416 // Whether a vector `v` of patterns is 'useful' in relation to a set of such
417 // vectors `m` is defined as there being a set of inputs that will match `v`
418 // but not any of the sets in `m`.
420 // This is used both for reachability checking (if a pattern isn't useful in
421 // relation to preceding patterns, it is not reachable) and exhaustiveness
422 // checking (if a wildcard pattern is useful in relation to a matrix, the
423 // matrix isn't exhaustive).
425 // Note: is_useful doesn't work on empty types, as the paper notes.
426 // So it assumes that v is non-empty.
427 fn is_useful(cx: &MatchCheckCtxt, matrix @ &Matrix(ref rows): &Matrix,
428 v: &[Gc<Pat>], witness: WitnessPreference) -> Usefulness {
429 debug!("{:}", matrix);
430 if rows.len() == 0u {
431 return match witness {
432 ConstructWitness => UsefulWithWitness(vec!()),
433 LeaveOutWitness => Useful
436 if rows.get(0).len() == 0u {
439 let real_pat = match rows.iter().find(|r| r.get(0).id != 0) {
440 Some(r) => raw_pat(*r.get(0)),
441 None if v.len() == 0 => return NotUseful,
444 let left_ty = if real_pat.id == 0 {
447 ty::pat_ty(cx.tcx, &*real_pat)
450 let max_slice_length = rows.iter().filter_map(|row| match row.get(0).node {
451 PatVec(ref before, _, ref after) => Some(before.len() + after.len()),
453 }).max().map_or(0, |v| v + 1);
455 let constructors = pat_constructors(cx, v[0], left_ty, max_slice_length);
456 if constructors.is_empty() {
457 match missing_constructor(cx, matrix, left_ty, max_slice_length) {
459 all_constructors(cx, left_ty, max_slice_length).move_iter().map(|c| {
460 match is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness) {
461 UsefulWithWitness(pats) => UsefulWithWitness({
462 let arity = constructor_arity(cx, &c, left_ty);
464 let pat_slice = pats.as_slice();
465 Vec::from_fn(arity, |i| {
466 pat_slice.get(i).map(|p| p.clone())
467 .unwrap_or_else(|| wild())
470 let mut result = vec!(construct_witness(cx, &c, subpats, left_ty));
471 result.extend(pats.move_iter().skip(arity));
476 }).find(|result| result != &NotUseful).unwrap_or(NotUseful)
479 Some(constructor) => {
480 let matrix = rows.iter().filter_map(|r| default(cx, r.as_slice())).collect();
481 match is_useful(cx, &matrix, v.tail(), witness) {
482 UsefulWithWitness(pats) => {
483 let arity = constructor_arity(cx, &constructor, left_ty);
484 let wild_pats = Vec::from_elem(arity, wild());
485 let enum_pat = construct_witness(cx, &constructor, wild_pats, left_ty);
486 UsefulWithWitness(vec!(enum_pat).append(pats.as_slice()))
493 constructors.move_iter().map(|c|
494 is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness)
495 ).find(|result| result != &NotUseful).unwrap_or(NotUseful)
499 fn is_useful_specialized(cx: &MatchCheckCtxt, &Matrix(ref m): &Matrix, v: &[Gc<Pat>],
500 ctor: Constructor, lty: ty::t, witness: WitnessPreference) -> Usefulness {
501 let arity = constructor_arity(cx, &ctor, lty);
502 let matrix = Matrix(m.iter().filter_map(|r| {
503 specialize(cx, r.as_slice(), &ctor, 0u, arity)
505 match specialize(cx, v, &ctor, 0u, arity) {
506 Some(v) => is_useful(cx, &matrix, v.as_slice(), witness),
511 /// Determines the constructors that the given pattern can be specialized to.
513 /// In most cases, there's only one constructor that a specific pattern
514 /// represents, such as a specific enum variant or a specific literal value.
515 /// Slice patterns, however, can match slices of different lengths. For instance,
516 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
518 /// On the other hand, a wild pattern and an identifier pattern cannot be
519 /// specialized in any way.
520 fn pat_constructors(cx: &MatchCheckCtxt, p: Gc<Pat>,
521 left_ty: ty::t, max_slice_length: uint) -> Vec<Constructor> {
522 let pat = raw_pat(p);
525 match cx.tcx.def_map.borrow().find(&pat.id) {
526 Some(&DefStatic(..)) =>
527 cx.tcx.sess.span_bug(pat.span, "static pattern should've been rewritten"),
528 Some(&DefStruct(_)) => vec!(Single),
529 Some(&DefVariant(_, id, _)) => vec!(Variant(id)),
533 match cx.tcx.def_map.borrow().find(&pat.id) {
534 Some(&DefStatic(..)) =>
535 cx.tcx.sess.span_bug(pat.span, "static pattern should've been rewritten"),
536 Some(&DefVariant(_, id, _)) => vec!(Variant(id)),
540 match cx.tcx.def_map.borrow().find(&pat.id) {
541 Some(&DefStatic(..)) =>
542 cx.tcx.sess.span_bug(pat.span, "static pattern should've been rewritten"),
543 Some(&DefVariant(_, id, _)) => vec!(Variant(id)),
547 vec!(ConstantValue(eval_const_expr(cx.tcx, &*expr))),
549 vec!(ConstantRange(eval_const_expr(cx.tcx, &*lo), eval_const_expr(cx.tcx, &*hi))),
550 PatVec(ref before, ref slice, ref after) =>
551 match ty::get(left_ty).sty {
552 ty::ty_vec(_, Some(_)) => vec!(Single),
553 _ => if slice.is_some() {
554 range_inclusive(before.len() + after.len(), max_slice_length)
555 .map(|length| Slice(length))
558 vec!(Slice(before.len() + after.len()))
561 PatBox(_) | PatTup(_) | PatRegion(..) =>
563 PatWild | PatWildMulti =>
566 cx.tcx.sess.bug("unexpanded macro")
570 /// This computes the arity of a constructor. The arity of a constructor
571 /// is how many subpattern patterns of that constructor should be expanded to.
573 /// For instance, a tuple pattern (_, 42u, Some([])) has the arity of 3.
574 /// A struct pattern's arity is the number of fields it contains, etc.
575 pub fn constructor_arity(cx: &MatchCheckCtxt, ctor: &Constructor, ty: ty::t) -> uint {
576 match ty::get(ty).sty {
577 ty::ty_tup(ref fs) => fs.len(),
578 ty::ty_box(_) | ty::ty_uniq(_) => 1u,
579 ty::ty_rptr(_, ty::mt { ty: ty, .. }) => match ty::get(ty).sty {
580 ty::ty_vec(_, None) => match *ctor {
581 Slice(length) => length,
582 ConstantValue(_) => 0u,
588 ty::ty_enum(eid, _) => {
590 Variant(id) => enum_variant_with_id(cx.tcx, eid, id).args.len(),
594 ty::ty_struct(cid, _) => ty::lookup_struct_fields(cx.tcx, cid).len(),
595 ty::ty_vec(_, Some(n)) => n,
600 fn range_covered_by_constructor(ctor: &Constructor,
601 from: &const_val, to: &const_val) -> Option<bool> {
602 let (c_from, c_to) = match *ctor {
603 ConstantValue(ref value) => (value, value),
604 ConstantRange(ref from, ref to) => (from, to),
605 Single => return Some(true),
608 let cmp_from = compare_const_vals(c_from, from);
609 let cmp_to = compare_const_vals(c_to, to);
610 match (cmp_from, cmp_to) {
611 (Some(val1), Some(val2)) => Some(val1 >= 0 && val2 <= 0),
616 /// This is the main specialization step. It expands the first pattern in the given row
617 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
618 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
620 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
621 /// different patterns.
622 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
623 /// fields filled with wild patterns.
624 pub fn specialize(cx: &MatchCheckCtxt, r: &[Gc<Pat>],
625 constructor: &Constructor, col: uint, arity: uint) -> Option<Vec<Gc<Pat>>> {
627 id: pat_id, node: ref node, span: pat_span
628 } = &(*raw_pat(r[col]));
629 let head: Option<Vec<Gc<Pat>>> = match node {
631 Some(Vec::from_elem(arity, wild())),
634 Some(Vec::from_elem(arity, wild())),
636 &PatIdent(_, _, _) => {
637 let opt_def = cx.tcx.def_map.borrow().find_copy(&pat_id);
639 Some(DefStatic(..)) =>
640 cx.tcx.sess.span_bug(pat_span, "static pattern should've been rewritten"),
641 Some(DefVariant(_, id, _)) => if *constructor == Variant(id) {
646 _ => Some(Vec::from_elem(arity, wild()))
650 &PatEnum(_, ref args) => {
651 let def = cx.tcx.def_map.borrow().get_copy(&pat_id);
654 cx.tcx.sess.span_bug(pat_span, "static pattern should've been rewritten"),
655 DefVariant(_, id, _) if *constructor != Variant(id) => None,
656 DefVariant(..) | DefFn(..) | DefStruct(..) => {
658 &Some(ref args) => args.clone(),
659 &None => Vec::from_elem(arity, wild())
666 &PatStruct(_, ref pattern_fields, _) => {
667 // Is this a struct or an enum variant?
668 let def = cx.tcx.def_map.borrow().get_copy(&pat_id);
669 let class_id = match def {
671 cx.tcx.sess.span_bug(pat_span, "static pattern should've been rewritten"),
672 DefVariant(_, variant_id, _) => if *constructor == Variant(variant_id) {
678 // Assume this is a struct.
679 match ty::ty_to_def_id(node_id_to_type(cx.tcx, pat_id)) {
681 cx.tcx.sess.span_bug(pat_span,
682 "struct pattern wasn't of a \
683 type with a def ID?!")
685 Some(def_id) => Some(def_id),
689 class_id.map(|variant_id| {
690 let struct_fields = ty::lookup_struct_fields(cx.tcx, variant_id);
691 let args = struct_fields.iter().map(|sf| {
692 match pattern_fields.iter().find(|f| f.ident.name == sf.name) {
704 &PatBox(ref inner) | &PatRegion(ref inner) =>
705 Some(vec!(inner.clone())),
707 &PatLit(ref expr) => {
708 let expr_value = eval_const_expr(cx.tcx, &**expr);
709 match range_covered_by_constructor(constructor, &expr_value, &expr_value) {
710 Some(true) => Some(vec!()),
713 cx.tcx.sess.span_err(pat_span, "mismatched types between arms");
719 &PatRange(ref from, ref to) => {
720 let from_value = eval_const_expr(cx.tcx, &**from);
721 let to_value = eval_const_expr(cx.tcx, &**to);
722 match range_covered_by_constructor(constructor, &from_value, &to_value) {
723 Some(true) => Some(vec!()),
726 cx.tcx.sess.span_err(pat_span, "mismatched types between arms");
732 &PatVec(ref before, ref slice, ref after) => {
734 // Fixed-length vectors.
736 let mut pats = before.clone();
737 pats.grow_fn(arity - before.len() - after.len(), |_| wild());
738 pats.push_all(after.as_slice());
741 Slice(length) if before.len() + after.len() <= length && slice.is_some() => {
742 let mut pats = before.clone();
743 pats.grow_fn(arity - before.len() - after.len(), |_| wild());
744 pats.push_all(after.as_slice());
747 Slice(length) if before.len() + after.len() == length => {
748 let mut pats = before.clone();
749 pats.push_all(after.as_slice());
757 cx.tcx.sess.span_err(pat_span, "unexpanded macro");
761 head.map(|head| head.append(r.slice_to(col)).append(r.slice_from(col + 1)))
764 fn default(cx: &MatchCheckCtxt, r: &[Gc<Pat>]) -> Option<Vec<Gc<Pat>>> {
765 if pat_is_binding_or_wild(&cx.tcx.def_map, &*raw_pat(r[0])) {
766 Some(Vec::from_slice(r.tail()))
772 fn check_local(cx: &mut MatchCheckCtxt, loc: &Local) {
773 visit::walk_local(cx, loc, ());
775 let name = match loc.source {
777 LocalFor => "`for` loop"
780 let mut static_inliner = StaticInliner { tcx: cx.tcx };
781 match is_refutable(cx, static_inliner.fold_pat(loc.pat)) {
783 span_err!(cx.tcx.sess, loc.pat.span, E0005,
784 "refutable pattern in {} binding: `{}` not covered",
785 name, pat_to_string(&*pat)
791 // Check legality of move bindings.
792 check_legality_of_move_bindings(cx, false, [ loc.pat ]);
795 fn check_fn(cx: &mut MatchCheckCtxt,
800 visit::walk_fn(cx, kind, decl, body, sp, ());
801 for input in decl.inputs.iter() {
802 match is_refutable(cx, input.pat) {
804 span_err!(cx.tcx.sess, input.pat.span, E0006,
805 "refutable pattern in function argument: `{}` not covered",
811 check_legality_of_move_bindings(cx, false, [input.pat]);
815 fn is_refutable(cx: &MatchCheckCtxt, pat: Gc<Pat>) -> Option<Gc<Pat>> {
816 let pats = Matrix(vec!(vec!(pat)));
817 match is_useful(cx, &pats, [wild()], ConstructWitness) {
818 UsefulWithWitness(pats) => {
819 assert_eq!(pats.len(), 1);
820 Some(pats.get(0).clone())
823 Useful => unreachable!()
827 // Legality of move bindings checking
829 fn check_legality_of_move_bindings(cx: &MatchCheckCtxt,
833 let def_map = &tcx.def_map;
834 let mut by_ref_span = None;
835 for pat in pats.iter() {
836 pat_bindings(def_map, &**pat, |bm, _, span, _path| {
839 by_ref_span = Some(span);
847 let check_move: |&Pat, Option<Gc<Pat>>| = |p, sub| {
848 // check legality of moving out of the enum
850 // x @ Foo(..) is legal, but x @ Foo(y) isn't.
851 if sub.map_or(false, |p| pat_contains_bindings(def_map, &*p)) {
852 span_err!(cx.tcx.sess, p.span, E0007, "cannot bind by-move with sub-bindings");
853 } else if has_guard {
854 span_err!(cx.tcx.sess, p.span, E0008, "cannot bind by-move into a pattern guard");
855 } else if by_ref_span.is_some() {
856 span_err!(cx.tcx.sess, p.span, E0009,
857 "cannot bind by-move and by-ref in the same pattern");
858 span_note!(cx.tcx.sess, by_ref_span.unwrap(), "by-ref binding occurs here");
862 for pat in pats.iter() {
863 walk_pat(&**pat, |p| {
864 if pat_is_binding(def_map, &*p) {
866 PatIdent(BindByValue(_), _, sub) => {
867 let pat_ty = ty::node_id_to_type(tcx, p.id);
868 if ty::type_moves_by_default(tcx, pat_ty) {
872 PatIdent(BindByRef(_), _, _) => {
875 cx.tcx.sess.span_bug(
877 format!("binding pattern {} is not an \