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::*;
26 use std::cmp::Ordering;
28 use std::iter::{range_inclusive, AdditiveIterator, FromIterator, IntoIterator, repeat};
31 use syntax::ast::{self, DUMMY_NODE_ID, NodeId, 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::{self, Visitor, FnKind};
39 use util::ppaux::ty_to_string;
40 use util::nodemap::FnvHashMap;
42 pub const DUMMY_WILD_PAT: &'static Pat = &Pat {
44 node: ast::PatWild(ast::PatWildSingle),
48 struct Matrix<'a>(Vec<Vec<&'a Pat>>);
50 /// Pretty-printer for matrices of patterns, example:
51 /// ++++++++++++++++++++++++++
53 /// ++++++++++++++++++++++++++
54 /// + true + [First] +
55 /// ++++++++++++++++++++++++++
56 /// + true + [Second(true)] +
57 /// ++++++++++++++++++++++++++
59 /// ++++++++++++++++++++++++++
60 /// + _ + [_, _, ..tail] +
61 /// ++++++++++++++++++++++++++
62 impl<'a> fmt::Debug for Matrix<'a> {
63 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64 try!(write!(f, "\n"));
66 let &Matrix(ref m) = self;
67 let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| {
69 .map(|&pat| pat_to_string(&*pat))
70 .collect::<Vec<String>>()
73 let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0);
74 assert!(m.iter().all(|row| row.len() == column_count));
75 let column_widths: Vec<uint> = (0..column_count).map(|col| {
76 pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0)
79 let total_width = column_widths.iter().cloned().sum() + column_count * 3 + 1;
80 let br = repeat('+').take(total_width).collect::<String>();
81 try!(write!(f, "{}\n", br));
82 for row in pretty_printed_matrix {
84 for (column, pat_str) in row.into_iter().enumerate() {
86 try!(write!(f, "{:1$}", pat_str, column_widths[column]));
87 try!(write!(f, " +"));
89 try!(write!(f, "\n"));
90 try!(write!(f, "{}\n", br));
96 impl<'a> FromIterator<Vec<&'a Pat>> for Matrix<'a> {
97 fn from_iter<T: IntoIterator<Item=Vec<&'a Pat>>>(iter: T) -> Matrix<'a> {
98 Matrix(iter.into_iter().collect())
102 pub struct MatchCheckCtxt<'a, 'tcx: 'a> {
103 pub tcx: &'a ty::ctxt<'tcx>,
104 pub param_env: ParameterEnvironment<'a, 'tcx>,
107 #[derive(Clone, PartialEq)]
108 pub enum Constructor {
109 /// The constructor of all patterns that don't vary by constructor,
110 /// e.g. struct patterns and fixed-length arrays.
115 ConstantValue(const_val),
116 /// Ranges of literal values (2..5).
117 ConstantRange(const_val, const_val),
118 /// Array patterns of length n.
120 /// Array patterns with a subslice.
121 SliceWithSubslice(uint, uint)
124 #[derive(Clone, PartialEq)]
127 UsefulWithWitness(Vec<P<Pat>>),
132 enum WitnessPreference {
137 impl<'a, 'tcx, 'v> Visitor<'v> for MatchCheckCtxt<'a, 'tcx> {
138 fn visit_expr(&mut self, ex: &ast::Expr) {
139 check_expr(self, ex);
141 fn visit_local(&mut self, l: &ast::Local) {
142 check_local(self, l);
144 fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v ast::FnDecl,
145 b: &'v ast::Block, s: Span, n: NodeId) {
146 check_fn(self, fk, fd, b, s, n);
150 pub fn check_crate(tcx: &ty::ctxt) {
151 visit::walk_crate(&mut MatchCheckCtxt {
153 param_env: ty::empty_parameter_environment(tcx),
155 tcx.sess.abort_if_errors();
158 fn check_expr(cx: &mut MatchCheckCtxt, ex: &ast::Expr) {
159 visit::walk_expr(cx, ex);
161 ast::ExprMatch(ref scrut, ref arms, source) => {
163 // First, check legality of move bindings.
164 check_legality_of_move_bindings(cx,
168 // Second, if there is a guard on each arm, make sure it isn't
169 // assigning or borrowing anything mutably.
171 Some(ref guard) => check_for_mutation_in_guard(cx, &**guard),
176 let mut static_inliner = StaticInliner::new(cx.tcx, None);
177 let inlined_arms = arms.iter().map(|arm| {
178 (arm.pats.iter().map(|pat| {
179 static_inliner.fold_pat((*pat).clone())
180 }).collect(), arm.guard.as_ref().map(|e| &**e))
181 }).collect::<Vec<(Vec<P<Pat>>, Option<&ast::Expr>)>>();
183 // Bail out early if inlining failed.
184 if static_inliner.failed {
188 for pat in inlined_arms
190 .flat_map(|&(ref pats, _)| pats.iter()) {
191 // Third, check legality of move bindings.
192 check_legality_of_bindings_in_at_patterns(cx, &**pat);
194 // Fourth, check if there are any references to NaN that we should warn about.
195 check_for_static_nan(cx, &**pat);
197 // Fifth, check if for any of the patterns that match an enumerated type
198 // are bindings with the same name as one of the variants of said type.
199 check_for_bindings_named_the_same_as_variants(cx, &**pat);
202 // Fourth, check for unreachable arms.
203 check_arms(cx, &inlined_arms[..], source);
205 // Finally, check if the whole match expression is exhaustive.
206 // Check for empty enum, because is_useful only works on inhabited types.
207 let pat_ty = node_id_to_type(cx.tcx, scrut.id);
208 if inlined_arms.is_empty() {
209 if !type_is_empty(cx.tcx, pat_ty) {
210 // We know the type is inhabited, so this must be wrong
211 span_err!(cx.tcx.sess, ex.span, E0002,
212 "non-exhaustive patterns: type {} is non-empty",
213 ty_to_string(cx.tcx, pat_ty)
216 // If the type *is* empty, it's vacuously exhaustive
220 let matrix: Matrix = inlined_arms
222 .filter(|&&(_, guard)| guard.is_none())
223 .flat_map(|arm| arm.0.iter())
224 .map(|pat| vec![&**pat])
226 check_exhaustive(cx, ex.span, &matrix, source);
232 fn is_expr_const_nan(tcx: &ty::ctxt, expr: &ast::Expr) -> bool {
233 match eval_const_expr(tcx, expr) {
234 const_float(f) => f.is_nan(),
239 fn check_for_bindings_named_the_same_as_variants(cx: &MatchCheckCtxt, pat: &Pat) {
240 ast_util::walk_pat(pat, |p| {
242 ast::PatIdent(ast::BindByValue(ast::MutImmutable), ident, None) => {
243 let pat_ty = ty::pat_ty(cx.tcx, p);
244 if let ty::ty_enum(def_id, _) = pat_ty.sty {
245 let def = cx.tcx.def_map.borrow().get(&p.id).cloned();
246 if let Some(DefLocal(_)) = def {
247 if ty::enum_variants(cx.tcx, def_id).iter().any(|variant|
248 token::get_name(variant.name) == token::get_name(ident.node.name)
249 && variant.args.len() == 0
251 span_warn!(cx.tcx.sess, p.span, E0170,
252 "pattern binding `{}` is named the same as one \
253 of the variants of the type `{}`",
254 &token::get_ident(ident.node), ty_to_string(cx.tcx, pat_ty));
255 span_help!(cx.tcx.sess, p.span,
256 "if you meant to match on a variant, \
257 consider making the path in the pattern qualified: `{}::{}`",
258 ty_to_string(cx.tcx, pat_ty), &token::get_ident(ident.node));
269 // Check that we do not match against a static NaN (#6804)
270 fn check_for_static_nan(cx: &MatchCheckCtxt, pat: &Pat) {
271 ast_util::walk_pat(pat, |p| {
273 ast::PatLit(ref expr) if is_expr_const_nan(cx.tcx, &**expr) => {
274 span_warn!(cx.tcx.sess, p.span, E0003,
275 "unmatchable NaN in pattern, \
276 use the is_nan method in a guard instead");
284 // Check for unreachable patterns
285 fn check_arms(cx: &MatchCheckCtxt,
286 arms: &[(Vec<P<Pat>>, Option<&ast::Expr>)],
287 source: ast::MatchSource) {
288 let mut seen = Matrix(vec![]);
289 let mut printed_if_let_err = false;
290 for &(ref pats, guard) in arms {
292 let v = vec![&**pat];
294 match is_useful(cx, &seen, &v[..], LeaveOutWitness) {
297 ast::MatchSource::IfLetDesugar { .. } => {
298 if printed_if_let_err {
299 // we already printed an irrefutable if-let pattern error.
300 // We don't want two, that's just confusing.
302 // find the first arm pattern so we can use its span
303 let &(ref first_arm_pats, _) = &arms[0];
304 let first_pat = &first_arm_pats[0];
305 let span = first_pat.span;
306 span_err!(cx.tcx.sess, span, E0162, "irrefutable if-let pattern");
307 printed_if_let_err = true;
311 ast::MatchSource::WhileLetDesugar => {
312 // find the first arm pattern so we can use its span
313 let &(ref first_arm_pats, _) = &arms[0];
314 let first_pat = &first_arm_pats[0];
315 let span = first_pat.span;
316 span_err!(cx.tcx.sess, span, E0165, "irrefutable while-let pattern");
319 ast::MatchSource::ForLoopDesugar => {
320 // this is a bug, because on `match iter.next()` we cover
321 // `Some(<head>)` and `None`. It's impossible to have an unreachable
323 // (see libsyntax/ext/expand.rs for the full expansion of a for loop)
324 cx.tcx.sess.span_bug(pat.span, "unreachable for-loop pattern")
327 ast::MatchSource::Normal => {
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, source: ast::MatchSource) {
352 match is_useful(cx, matrix, &[DUMMY_WILD_PAT], ConstructWitness) {
353 UsefulWithWitness(pats) => {
354 let witness = match &pats[..] {
355 [ref witness] => &**witness,
356 [] => DUMMY_WILD_PAT,
360 ast::MatchSource::ForLoopDesugar => {
361 // `witness` has the form `Some(<head>)`, peel off the `Some`
362 let witness = match witness.node {
363 ast::PatEnum(_, Some(ref pats)) => match &pats[..] {
370 span_err!(cx.tcx.sess, sp, E0297,
371 "refutable pattern in `for` loop binding: \
373 pat_to_string(witness));
376 span_err!(cx.tcx.sess, sp, E0004,
377 "non-exhaustive patterns: `{}` not covered",
378 pat_to_string(witness)
384 // This is good, wildcard pattern isn't reachable
390 fn const_val_to_expr(value: &const_val) -> P<ast::Expr> {
391 let node = match value {
392 &const_bool(b) => ast::LitBool(b),
397 node: ast::ExprLit(P(Spanned { node: node, span: DUMMY_SP })),
402 pub struct StaticInliner<'a, 'tcx: 'a> {
403 pub tcx: &'a ty::ctxt<'tcx>,
405 pub renaming_map: Option<&'a mut FnvHashMap<(NodeId, Span), NodeId>>,
408 impl<'a, 'tcx> StaticInliner<'a, 'tcx> {
409 pub fn new<'b>(tcx: &'b ty::ctxt<'tcx>,
410 renaming_map: Option<&'b mut FnvHashMap<(NodeId, Span), NodeId>>)
411 -> StaticInliner<'b, 'tcx> {
415 renaming_map: renaming_map
420 struct RenamingRecorder<'map> {
421 substituted_node_id: NodeId,
423 renaming_map: &'map mut FnvHashMap<(NodeId, Span), NodeId>
426 impl<'map> ast_util::IdVisitingOperation for RenamingRecorder<'map> {
427 fn visit_id(&mut self, node_id: NodeId) {
428 let key = (node_id, self.origin_span);
429 self.renaming_map.insert(key, self.substituted_node_id);
433 impl<'a, 'tcx> Folder for StaticInliner<'a, 'tcx> {
434 fn fold_pat(&mut self, pat: P<Pat>) -> P<Pat> {
435 return match pat.node {
436 ast::PatIdent(..) | ast::PatEnum(..) => {
437 let def = self.tcx.def_map.borrow().get(&pat.id).cloned();
439 Some(DefConst(did)) => match lookup_const_by_id(self.tcx, did) {
440 Some(const_expr) => {
441 const_expr_to_pat(self.tcx, const_expr, pat.span).map(|new_pat| {
443 if let Some(ref mut renaming_map) = self.renaming_map {
444 // Record any renamings we do here
445 record_renamings(const_expr, &pat, renaming_map);
453 span_err!(self.tcx.sess, pat.span, E0158,
454 "statics cannot be referenced in patterns");
458 _ => noop_fold_pat(pat, self)
461 _ => noop_fold_pat(pat, self)
464 fn record_renamings(const_expr: &ast::Expr,
465 substituted_pat: &ast::Pat,
466 renaming_map: &mut FnvHashMap<(NodeId, Span), NodeId>) {
467 let mut renaming_recorder = RenamingRecorder {
468 substituted_node_id: substituted_pat.id,
469 origin_span: substituted_pat.span,
470 renaming_map: renaming_map,
473 let mut id_visitor = ast_util::IdVisitor {
474 operation: &mut renaming_recorder,
475 pass_through_items: true,
476 visited_outermost: false,
479 id_visitor.visit_expr(const_expr);
484 /// Constructs a partial witness for a pattern given a list of
485 /// patterns expanded by the specialization step.
487 /// When a pattern P is discovered to be useful, this function is used bottom-up
488 /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
489 /// of values, V, where each value in that set is not covered by any previously
490 /// used patterns and is covered by the pattern P'. Examples:
492 /// left_ty: tuple of 3 elements
493 /// pats: [10, 20, _] => (10, 20, _)
495 /// left_ty: struct X { a: (bool, &'static str), b: uint}
496 /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 }
497 fn construct_witness(cx: &MatchCheckCtxt, ctor: &Constructor,
498 pats: Vec<&Pat>, left_ty: Ty) -> P<Pat> {
499 let pats_len = pats.len();
500 let mut pats = pats.into_iter().map(|p| P((*p).clone()));
501 let pat = match left_ty.sty {
502 ty::ty_tup(_) => ast::PatTup(pats.collect()),
504 ty::ty_enum(cid, _) | ty::ty_struct(cid, _) => {
505 let (vid, is_structure) = match ctor {
507 (vid, ty::enum_variant_with_id(cx.tcx, cid, vid).arg_names.is_some()),
509 (cid, !ty::is_tuple_struct(cx.tcx, cid))
512 let fields = ty::lookup_struct_fields(cx.tcx, vid);
513 let field_pats: Vec<_> = fields.into_iter()
515 .filter(|&(_, ref pat)| pat.node != ast::PatWild(ast::PatWildSingle))
516 .map(|(field, pat)| Spanned {
518 node: ast::FieldPat {
519 ident: ast::Ident::new(field.name),
524 let has_more_fields = field_pats.len() < pats_len;
525 ast::PatStruct(def_to_path(cx.tcx, vid), field_pats, has_more_fields)
527 ast::PatEnum(def_to_path(cx.tcx, vid), Some(pats.collect()))
531 ty::ty_rptr(_, ty::mt { ty, mutbl }) => {
533 ty::ty_vec(_, Some(n)) => match ctor {
535 assert_eq!(pats_len, n);
536 ast::PatVec(pats.collect(), None, vec!())
540 ty::ty_vec(_, None) => match ctor {
542 assert_eq!(pats_len, n);
543 ast::PatVec(pats.collect(), None, vec!())
547 ty::ty_str => ast::PatWild(ast::PatWildSingle),
550 assert_eq!(pats_len, 1);
551 ast::PatRegion(pats.nth(0).unwrap(), mutbl)
556 ty::ty_vec(_, Some(len)) => {
557 assert_eq!(pats_len, len);
558 ast::PatVec(pats.collect(), None, vec![])
563 ConstantValue(ref v) => ast::PatLit(const_val_to_expr(v)),
564 _ => ast::PatWild(ast::PatWildSingle),
576 fn missing_constructor(cx: &MatchCheckCtxt, &Matrix(ref rows): &Matrix,
577 left_ty: Ty, max_slice_length: uint) -> Option<Constructor> {
578 let used_constructors: Vec<Constructor> = rows.iter()
579 .flat_map(|row| pat_constructors(cx, row[0], left_ty, max_slice_length).into_iter())
581 all_constructors(cx, left_ty, max_slice_length)
583 .find(|c| !used_constructors.contains(c))
586 /// This determines the set of all possible constructors of a pattern matching
587 /// values of type `left_ty`. For vectors, this would normally be an infinite set
588 /// but is instead bounded by the maximum fixed length of slice patterns in
589 /// the column of patterns being analyzed.
590 fn all_constructors(cx: &MatchCheckCtxt, left_ty: Ty,
591 max_slice_length: uint) -> Vec<Constructor> {
594 [true, false].iter().map(|b| ConstantValue(const_bool(*b))).collect(),
596 ty::ty_rptr(_, ty::mt { ty, .. }) => match ty.sty {
597 ty::ty_vec(_, None) =>
598 range_inclusive(0, max_slice_length).map(|length| Slice(length)).collect(),
602 ty::ty_enum(eid, _) =>
603 ty::enum_variants(cx.tcx, eid)
605 .map(|va| Variant(va.id))
613 // Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
615 // Whether a vector `v` of patterns is 'useful' in relation to a set of such
616 // vectors `m` is defined as there being a set of inputs that will match `v`
617 // but not any of the sets in `m`.
619 // This is used both for reachability checking (if a pattern isn't useful in
620 // relation to preceding patterns, it is not reachable) and exhaustiveness
621 // checking (if a wildcard pattern is useful in relation to a matrix, the
622 // matrix isn't exhaustive).
624 // Note: is_useful doesn't work on empty types, as the paper notes.
625 // So it assumes that v is non-empty.
626 fn is_useful(cx: &MatchCheckCtxt,
629 witness: WitnessPreference)
631 let &Matrix(ref rows) = matrix;
632 debug!("{:?}", matrix);
634 return match witness {
635 ConstructWitness => UsefulWithWitness(vec!()),
636 LeaveOutWitness => Useful
639 if rows[0].len() == 0 {
642 let real_pat = match rows.iter().find(|r| (*r)[0].id != DUMMY_NODE_ID) {
643 Some(r) => raw_pat(r[0]),
644 None if v.len() == 0 => return NotUseful,
647 let left_ty = if real_pat.id == DUMMY_NODE_ID {
650 ty::pat_ty(cx.tcx, &*real_pat)
653 let max_slice_length = rows.iter().filter_map(|row| match row[0].node {
654 ast::PatVec(ref before, _, ref after) => Some(before.len() + after.len()),
656 }).max().map_or(0, |v| v + 1);
658 let constructors = pat_constructors(cx, v[0], left_ty, max_slice_length);
659 if constructors.is_empty() {
660 match missing_constructor(cx, matrix, left_ty, max_slice_length) {
662 all_constructors(cx, left_ty, max_slice_length).into_iter().map(|c| {
663 match is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness) {
664 UsefulWithWitness(pats) => UsefulWithWitness({
665 let arity = constructor_arity(cx, &c, left_ty);
667 let pat_slice = &pats[..];
668 let subpats: Vec<_> = (0..arity).map(|i| {
669 pat_slice.get(i).map_or(DUMMY_WILD_PAT, |p| &**p)
671 vec![construct_witness(cx, &c, subpats, left_ty)]
673 result.extend(pats.into_iter().skip(arity));
678 }).find(|result| result != &NotUseful).unwrap_or(NotUseful)
681 Some(constructor) => {
682 let matrix = rows.iter().filter_map(|r| {
683 if pat_is_binding_or_wild(&cx.tcx.def_map, raw_pat(r[0])) {
684 Some(r.tail().to_vec())
689 match is_useful(cx, &matrix, v.tail(), witness) {
690 UsefulWithWitness(pats) => {
691 let arity = constructor_arity(cx, &constructor, left_ty);
692 let wild_pats: Vec<_> = repeat(DUMMY_WILD_PAT).take(arity).collect();
693 let enum_pat = construct_witness(cx, &constructor, wild_pats, left_ty);
694 let mut new_pats = vec![enum_pat];
695 new_pats.extend(pats.into_iter());
696 UsefulWithWitness(new_pats)
703 constructors.into_iter().map(|c|
704 is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness)
705 ).find(|result| result != &NotUseful).unwrap_or(NotUseful)
709 fn is_useful_specialized(cx: &MatchCheckCtxt, &Matrix(ref m): &Matrix,
710 v: &[&Pat], ctor: Constructor, lty: Ty,
711 witness: WitnessPreference) -> Usefulness {
712 let arity = constructor_arity(cx, &ctor, lty);
713 let matrix = Matrix(m.iter().filter_map(|r| {
714 specialize(cx, &r[..], &ctor, 0, arity)
716 match specialize(cx, v, &ctor, 0, arity) {
717 Some(v) => is_useful(cx, &matrix, &v[..], witness),
722 /// Determines the constructors that the given pattern can be specialized to.
724 /// In most cases, there's only one constructor that a specific pattern
725 /// represents, such as a specific enum variant or a specific literal value.
726 /// Slice patterns, however, can match slices of different lengths. For instance,
727 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
729 /// On the other hand, a wild pattern and an identifier pattern cannot be
730 /// specialized in any way.
731 fn pat_constructors(cx: &MatchCheckCtxt, p: &Pat,
732 left_ty: Ty, max_slice_length: uint) -> Vec<Constructor> {
733 let pat = raw_pat(p);
736 match cx.tcx.def_map.borrow().get(&pat.id) {
737 Some(&DefConst(..)) =>
738 cx.tcx.sess.span_bug(pat.span, "const pattern should've \
740 Some(&DefStruct(_)) => vec!(Single),
741 Some(&DefVariant(_, id, _)) => vec!(Variant(id)),
745 match cx.tcx.def_map.borrow().get(&pat.id) {
746 Some(&DefConst(..)) =>
747 cx.tcx.sess.span_bug(pat.span, "const pattern should've \
749 Some(&DefVariant(_, id, _)) => vec!(Variant(id)),
752 ast::PatStruct(..) =>
753 match cx.tcx.def_map.borrow().get(&pat.id) {
754 Some(&DefConst(..)) =>
755 cx.tcx.sess.span_bug(pat.span, "const pattern should've \
757 Some(&DefVariant(_, id, _)) => vec!(Variant(id)),
760 ast::PatLit(ref expr) =>
761 vec!(ConstantValue(eval_const_expr(cx.tcx, &**expr))),
762 ast::PatRange(ref lo, ref hi) =>
763 vec!(ConstantRange(eval_const_expr(cx.tcx, &**lo), eval_const_expr(cx.tcx, &**hi))),
764 ast::PatVec(ref before, ref slice, ref after) =>
766 ty::ty_vec(_, Some(_)) => vec!(Single),
767 _ => if slice.is_some() {
768 range_inclusive(before.len() + after.len(), max_slice_length)
769 .map(|length| Slice(length))
772 vec!(Slice(before.len() + after.len()))
775 ast::PatBox(_) | ast::PatTup(_) | ast::PatRegion(..) =>
780 cx.tcx.sess.bug("unexpanded macro")
784 /// This computes the arity of a constructor. The arity of a constructor
785 /// is how many subpattern patterns of that constructor should be expanded to.
787 /// For instance, a tuple pattern (_, 42, Some([])) has the arity of 3.
788 /// A struct pattern's arity is the number of fields it contains, etc.
789 pub fn constructor_arity(cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> uint {
791 ty::ty_tup(ref fs) => fs.len(),
793 ty::ty_rptr(_, ty::mt { ty, .. }) => match ty.sty {
794 ty::ty_vec(_, None) => match *ctor {
795 Slice(length) => length,
796 ConstantValue(_) => 0,
802 ty::ty_enum(eid, _) => {
804 Variant(id) => enum_variant_with_id(cx.tcx, eid, id).args.len(),
808 ty::ty_struct(cid, _) => ty::lookup_struct_fields(cx.tcx, cid).len(),
809 ty::ty_vec(_, Some(n)) => n,
814 fn range_covered_by_constructor(ctor: &Constructor,
815 from: &const_val, to: &const_val) -> Option<bool> {
816 let (c_from, c_to) = match *ctor {
817 ConstantValue(ref value) => (value, value),
818 ConstantRange(ref from, ref to) => (from, to),
819 Single => return Some(true),
822 let cmp_from = compare_const_vals(c_from, from);
823 let cmp_to = compare_const_vals(c_to, to);
824 match (cmp_from, cmp_to) {
825 (Some(cmp_from), Some(cmp_to)) => {
826 Some(cmp_from != Ordering::Less && cmp_to != Ordering::Greater)
832 /// This is the main specialization step. It expands the first pattern in the given row
833 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
834 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
836 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
837 /// different patterns.
838 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
839 /// fields filled with wild patterns.
840 pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat],
841 constructor: &Constructor, col: uint, arity: uint) -> Option<Vec<&'a Pat>> {
843 id: pat_id, ref node, span: pat_span
845 let head: Option<Vec<&Pat>> = match *node {
847 Some(repeat(DUMMY_WILD_PAT).take(arity).collect()),
849 ast::PatIdent(_, _, _) => {
850 let opt_def = cx.tcx.def_map.borrow().get(&pat_id).cloned();
852 Some(DefConst(..)) =>
853 cx.tcx.sess.span_bug(pat_span, "const pattern should've \
855 Some(DefVariant(_, id, _)) => if *constructor == Variant(id) {
860 _ => Some(repeat(DUMMY_WILD_PAT).take(arity).collect())
864 ast::PatEnum(_, ref args) => {
865 let def = cx.tcx.def_map.borrow()[pat_id].clone();
868 cx.tcx.sess.span_bug(pat_span, "const pattern should've \
870 DefVariant(_, id, _) if *constructor != Variant(id) => None,
871 DefVariant(..) | DefStruct(..) => {
873 &Some(ref args) => args.iter().map(|p| &**p).collect(),
874 &None => repeat(DUMMY_WILD_PAT).take(arity).collect(),
881 ast::PatStruct(_, ref pattern_fields, _) => {
882 // Is this a struct or an enum variant?
883 let def = cx.tcx.def_map.borrow()[pat_id].clone();
884 let class_id = match def {
886 cx.tcx.sess.span_bug(pat_span, "const pattern should've \
888 DefVariant(_, variant_id, _) => if *constructor == Variant(variant_id) {
894 // Assume this is a struct.
895 match ty::ty_to_def_id(node_id_to_type(cx.tcx, pat_id)) {
897 cx.tcx.sess.span_bug(pat_span,
898 "struct pattern wasn't of a \
899 type with a def ID?!")
901 Some(def_id) => Some(def_id),
905 class_id.map(|variant_id| {
906 let struct_fields = ty::lookup_struct_fields(cx.tcx, variant_id);
907 let args = struct_fields.iter().map(|sf| {
908 match pattern_fields.iter().find(|f| f.node.ident.name == sf.name) {
909 Some(ref f) => &*f.node.pat,
917 ast::PatTup(ref args) =>
918 Some(args.iter().map(|p| &**p).collect()),
920 ast::PatBox(ref inner) | ast::PatRegion(ref inner, _) =>
921 Some(vec![&**inner]),
923 ast::PatLit(ref expr) => {
924 let expr_value = eval_const_expr(cx.tcx, &**expr);
925 match range_covered_by_constructor(constructor, &expr_value, &expr_value) {
926 Some(true) => Some(vec![]),
929 span_err!(cx.tcx.sess, pat_span, E0298, "mismatched types between arms");
935 ast::PatRange(ref from, ref to) => {
936 let from_value = eval_const_expr(cx.tcx, &**from);
937 let to_value = eval_const_expr(cx.tcx, &**to);
938 match range_covered_by_constructor(constructor, &from_value, &to_value) {
939 Some(true) => Some(vec![]),
942 span_err!(cx.tcx.sess, pat_span, E0299, "mismatched types between arms");
948 ast::PatVec(ref before, ref slice, ref after) => {
950 // Fixed-length vectors.
952 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
953 pats.extend(repeat(DUMMY_WILD_PAT).take(arity - before.len() - after.len()));
954 pats.extend(after.iter().map(|p| &**p));
957 Slice(length) if before.len() + after.len() <= length && slice.is_some() => {
958 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
959 pats.extend(repeat(DUMMY_WILD_PAT).take(arity - before.len() - after.len()));
960 pats.extend(after.iter().map(|p| &**p));
963 Slice(length) if before.len() + after.len() == length => {
964 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
965 pats.extend(after.iter().map(|p| &**p));
968 SliceWithSubslice(prefix, suffix)
969 if before.len() == prefix
970 && after.len() == suffix
971 && slice.is_some() => {
972 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
973 pats.extend(after.iter().map(|p| &**p));
981 span_err!(cx.tcx.sess, pat_span, E0300, "unexpanded macro");
985 head.map(|mut head| {
986 head.push_all(&r[..col]);
987 head.push_all(&r[col + 1..]);
992 fn check_local(cx: &mut MatchCheckCtxt, loc: &ast::Local) {
993 visit::walk_local(cx, loc);
995 let name = match loc.source {
996 ast::LocalLet => "local",
997 ast::LocalFor => "`for` loop"
1000 let mut static_inliner = StaticInliner::new(cx.tcx, None);
1001 is_refutable(cx, &*static_inliner.fold_pat(loc.pat.clone()), |pat| {
1002 span_err!(cx.tcx.sess, loc.pat.span, E0005,
1003 "refutable pattern in {} binding: `{}` not covered",
1004 name, pat_to_string(pat)
1008 // Check legality of move bindings and `@` patterns.
1009 check_legality_of_move_bindings(cx, false, slice::ref_slice(&loc.pat));
1010 check_legality_of_bindings_in_at_patterns(cx, &*loc.pat);
1013 fn check_fn(cx: &mut MatchCheckCtxt,
1020 visit::FkFnBlock => {}
1021 _ => cx.param_env = ParameterEnvironment::for_item(cx.tcx, fn_id),
1024 visit::walk_fn(cx, kind, decl, body, sp);
1026 for input in &decl.inputs {
1027 is_refutable(cx, &*input.pat, |pat| {
1028 span_err!(cx.tcx.sess, input.pat.span, E0006,
1029 "refutable pattern in function argument: `{}` not covered",
1033 check_legality_of_move_bindings(cx, false, slice::ref_slice(&input.pat));
1034 check_legality_of_bindings_in_at_patterns(cx, &*input.pat);
1038 fn is_refutable<A, F>(cx: &MatchCheckCtxt, pat: &Pat, refutable: F) -> Option<A> where
1039 F: FnOnce(&Pat) -> A,
1041 let pats = Matrix(vec!(vec!(pat)));
1042 match is_useful(cx, &pats, &[DUMMY_WILD_PAT], ConstructWitness) {
1043 UsefulWithWitness(pats) => {
1044 assert_eq!(pats.len(), 1);
1045 Some(refutable(&*pats[0]))
1048 Useful => unreachable!()
1052 // Legality of move bindings checking
1053 fn check_legality_of_move_bindings(cx: &MatchCheckCtxt,
1057 let def_map = &tcx.def_map;
1058 let mut by_ref_span = None;
1060 pat_bindings(def_map, &**pat, |bm, _, span, _path| {
1062 ast::BindByRef(_) => {
1063 by_ref_span = Some(span);
1065 ast::BindByValue(_) => {
1071 let check_move = |p: &Pat, sub: Option<&Pat>| {
1072 // check legality of moving out of the enum
1074 // x @ Foo(..) is legal, but x @ Foo(y) isn't.
1075 if sub.map_or(false, |p| pat_contains_bindings(def_map, &*p)) {
1076 span_err!(cx.tcx.sess, p.span, E0007, "cannot bind by-move with sub-bindings");
1077 } else if has_guard {
1078 span_err!(cx.tcx.sess, p.span, E0008, "cannot bind by-move into a pattern guard");
1079 } else if by_ref_span.is_some() {
1080 span_err!(cx.tcx.sess, p.span, E0009,
1081 "cannot bind by-move and by-ref in the same pattern");
1082 span_note!(cx.tcx.sess, by_ref_span.unwrap(), "by-ref binding occurs here");
1087 ast_util::walk_pat(&**pat, |p| {
1088 if pat_is_binding(def_map, &*p) {
1090 ast::PatIdent(ast::BindByValue(_), _, ref sub) => {
1091 let pat_ty = ty::node_id_to_type(tcx, p.id);
1092 if ty::type_moves_by_default(&cx.param_env, pat.span, pat_ty) {
1093 check_move(p, sub.as_ref().map(|p| &**p));
1096 ast::PatIdent(ast::BindByRef(_), _, _) => {
1099 cx.tcx.sess.span_bug(
1101 &format!("binding pattern {} is not an \
1113 /// Ensures that a pattern guard doesn't borrow by mutable reference or
1115 fn check_for_mutation_in_guard<'a, 'tcx>(cx: &'a MatchCheckCtxt<'a, 'tcx>,
1116 guard: &ast::Expr) {
1117 let mut checker = MutationChecker {
1120 let mut visitor = ExprUseVisitor::new(&mut checker,
1121 &checker.cx.param_env);
1122 visitor.walk_expr(guard);
1125 struct MutationChecker<'a, 'tcx: 'a> {
1126 cx: &'a MatchCheckCtxt<'a, 'tcx>,
1129 impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> {
1130 fn matched_pat(&mut self, _: &Pat, _: cmt, _: euv::MatchMode) {}
1131 fn consume(&mut self, _: NodeId, _: Span, _: cmt, _: ConsumeMode) {}
1132 fn consume_pat(&mut self, _: &Pat, _: cmt, _: ConsumeMode) {}
1133 fn borrow(&mut self,
1142 span_err!(self.cx.tcx.sess, span, E0301,
1143 "cannot mutably borrow in a pattern guard")
1145 ImmBorrow | UniqueImmBorrow => {}
1148 fn decl_without_init(&mut self, _: NodeId, _: Span) {}
1149 fn mutate(&mut self, _: NodeId, span: Span, _: cmt, mode: MutateMode) {
1151 JustWrite | WriteAndRead => {
1152 span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
1159 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
1160 /// because of the way rvalues are handled in the borrow check. (See issue
1162 fn check_legality_of_bindings_in_at_patterns(cx: &MatchCheckCtxt, pat: &Pat) {
1163 AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
1166 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
1167 cx: &'a MatchCheckCtxt<'b, 'tcx>,
1168 bindings_allowed: bool
1171 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
1172 fn visit_pat(&mut self, pat: &Pat) {
1173 if !self.bindings_allowed && pat_is_binding(&self.cx.tcx.def_map, pat) {
1174 span_err!(self.cx.tcx.sess, pat.span, E0303,
1175 "pattern bindings are not allowed \
1180 ast::PatIdent(_, _, Some(_)) => {
1181 let bindings_were_allowed = self.bindings_allowed;
1182 self.bindings_allowed = false;
1183 visit::walk_pat(self, pat);
1184 self.bindings_allowed = bindings_were_allowed;
1186 _ => visit::walk_pat(self, pat),