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, ConstVal};
16 use middle::const_eval::{eval_const_expr, eval_const_expr_partial};
17 use middle::const_eval::{const_expr_to_pat, lookup_const_by_id};
18 use middle::const_eval::EvalHint::ExprTypeChecked;
20 use middle::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, Init};
21 use middle::expr_use_visitor::{JustWrite, LoanCause, MutateMode};
22 use middle::expr_use_visitor::WriteAndRead;
23 use middle::expr_use_visitor as euv;
25 use middle::mem_categorization::{cmt};
26 use middle::pat_util::*;
29 use std::cmp::Ordering;
31 use std::iter::{range_inclusive, FromIterator, IntoIterator, repeat};
33 use syntax::ast::{self, DUMMY_NODE_ID, NodeId, Pat};
35 use syntax::codemap::{Span, Spanned, DUMMY_SP};
36 use syntax::fold::{Folder, noop_fold_pat};
37 use syntax::print::pprust::pat_to_string;
39 use syntax::visit::{self, Visitor, FnKind};
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<usize> = (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::<usize>() + 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 //NOTE: appears to be the only place other then InferCtxt to contain a ParamEnv
103 pub struct MatchCheckCtxt<'a, 'tcx: 'a> {
104 pub tcx: &'a ty::ctxt<'tcx>,
105 pub param_env: ParameterEnvironment<'a, 'tcx>,
108 #[derive(Clone, PartialEq)]
109 pub enum Constructor {
110 /// The constructor of all patterns that don't vary by constructor,
111 /// e.g. struct patterns and fixed-length arrays.
116 ConstantValue(ConstVal),
117 /// Ranges of literal values (2..5).
118 ConstantRange(ConstVal, ConstVal),
119 /// Array patterns of length n.
121 /// Array patterns with a subslice.
122 SliceWithSubslice(usize, usize)
125 #[derive(Clone, PartialEq)]
128 UsefulWithWitness(Vec<P<Pat>>),
132 #[derive(Copy, Clone)]
133 enum WitnessPreference {
138 impl<'a, 'tcx, 'v> Visitor<'v> for MatchCheckCtxt<'a, 'tcx> {
139 fn visit_expr(&mut self, ex: &ast::Expr) {
140 check_expr(self, ex);
142 fn visit_local(&mut self, l: &ast::Local) {
143 check_local(self, l);
145 fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v ast::FnDecl,
146 b: &'v ast::Block, s: Span, n: NodeId) {
147 check_fn(self, fk, fd, b, s, n);
151 pub fn check_crate(tcx: &ty::ctxt) {
152 visit::walk_crate(&mut MatchCheckCtxt {
154 param_env: tcx.empty_parameter_environment(),
156 tcx.sess.abort_if_errors();
159 fn check_expr(cx: &mut MatchCheckCtxt, ex: &ast::Expr) {
160 visit::walk_expr(cx, ex);
162 ast::ExprMatch(ref scrut, ref arms, source) => {
164 // First, check legality of move bindings.
165 check_legality_of_move_bindings(cx,
169 // Second, if there is a guard on each arm, make sure it isn't
170 // assigning or borrowing anything mutably.
172 Some(ref guard) => check_for_mutation_in_guard(cx, &**guard),
177 let mut static_inliner = StaticInliner::new(cx.tcx, None);
178 let inlined_arms = arms.iter().map(|arm| {
179 (arm.pats.iter().map(|pat| {
180 static_inliner.fold_pat((*pat).clone())
181 }).collect(), arm.guard.as_ref().map(|e| &**e))
182 }).collect::<Vec<(Vec<P<Pat>>, Option<&ast::Expr>)>>();
184 // Bail out early if inlining failed.
185 if static_inliner.failed {
189 for pat in inlined_arms
191 .flat_map(|&(ref pats, _)| pats) {
192 // Third, check legality of move bindings.
193 check_legality_of_bindings_in_at_patterns(cx, &**pat);
195 // Fourth, check if there are any references to NaN that we should warn about.
196 check_for_static_nan(cx, &**pat);
198 // Fifth, check if for any of the patterns that match an enumerated type
199 // are bindings with the same name as one of the variants of said type.
200 check_for_bindings_named_the_same_as_variants(cx, &**pat);
203 // Fourth, check for unreachable arms.
204 check_arms(cx, &inlined_arms[..], source);
206 // Finally, check if the whole match expression is exhaustive.
207 // Check for empty enum, because is_useful only works on inhabited types.
208 let pat_ty = cx.tcx.node_id_to_type(scrut.id);
209 if inlined_arms.is_empty() {
210 if !pat_ty.is_empty(cx.tcx) {
211 // We know the type is inhabited, so this must be wrong
212 span_err!(cx.tcx.sess, ex.span, E0002,
213 "non-exhaustive patterns: type {} is non-empty",
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)
224 .map(|pat| vec![&**pat])
226 check_exhaustive(cx, ex.span, &matrix, source);
232 fn check_for_bindings_named_the_same_as_variants(cx: &MatchCheckCtxt, pat: &Pat) {
233 ast_util::walk_pat(pat, |p| {
235 ast::PatIdent(ast::BindByValue(ast::MutImmutable), ident, None) => {
236 let pat_ty = cx.tcx.pat_ty(p);
237 if let ty::TyEnum(def_id, _) = pat_ty.sty {
238 let def = cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def());
239 if let Some(DefLocal(_)) = def {
240 if cx.tcx.enum_variants(def_id).iter().any(|variant|
241 variant.name == ident.node.name
242 && variant.args.is_empty()
244 span_warn!(cx.tcx.sess, p.span, E0170,
245 "pattern binding `{}` is named the same as one \
246 of the variants of the type `{}`",
248 fileline_help!(cx.tcx.sess, p.span,
249 "if you meant to match on a variant, \
250 consider making the path in the pattern qualified: `{}::{}`",
262 // Check that we do not match against a static NaN (#6804)
263 fn check_for_static_nan(cx: &MatchCheckCtxt, pat: &Pat) {
264 ast_util::walk_pat(pat, |p| {
265 if let ast::PatLit(ref expr) = p.node {
266 match eval_const_expr_partial(cx.tcx, &**expr, ExprTypeChecked) {
267 Ok(ConstVal::Float(f)) if f.is_nan() => {
268 span_warn!(cx.tcx.sess, p.span, E0003,
269 "unmatchable NaN in pattern, \
270 use the is_nan method in a guard instead");
275 let subspan = p.span.lo <= err.span.lo && err.span.hi <= p.span.hi;
276 cx.tcx.sess.span_err(err.span,
277 &format!("constant evaluation error: {}",
280 cx.tcx.sess.span_note(p.span,
290 // Check for unreachable patterns
291 fn check_arms(cx: &MatchCheckCtxt,
292 arms: &[(Vec<P<Pat>>, Option<&ast::Expr>)],
293 source: ast::MatchSource) {
294 let mut seen = Matrix(vec![]);
295 let mut printed_if_let_err = false;
296 for &(ref pats, guard) in arms {
298 let v = vec![&**pat];
300 match is_useful(cx, &seen, &v[..], LeaveOutWitness) {
303 ast::MatchSource::IfLetDesugar { .. } => {
304 if printed_if_let_err {
305 // we already printed an irrefutable if-let pattern error.
306 // We don't want two, that's just confusing.
308 // find the first arm pattern so we can use its span
309 let &(ref first_arm_pats, _) = &arms[0];
310 let first_pat = &first_arm_pats[0];
311 let span = first_pat.span;
312 span_err!(cx.tcx.sess, span, E0162, "irrefutable if-let pattern");
313 printed_if_let_err = true;
317 ast::MatchSource::WhileLetDesugar => {
318 // find the first arm pattern so we can use its span
319 let &(ref first_arm_pats, _) = &arms[0];
320 let first_pat = &first_arm_pats[0];
321 let span = first_pat.span;
322 span_err!(cx.tcx.sess, span, E0165, "irrefutable while-let pattern");
325 ast::MatchSource::ForLoopDesugar => {
326 // this is a bug, because on `match iter.next()` we cover
327 // `Some(<head>)` and `None`. It's impossible to have an unreachable
329 // (see libsyntax/ext/expand.rs for the full expansion of a for loop)
330 cx.tcx.sess.span_bug(pat.span, "unreachable for-loop pattern")
333 ast::MatchSource::Normal => {
334 span_err!(cx.tcx.sess, pat.span, E0001, "unreachable pattern")
339 UsefulWithWitness(_) => unreachable!()
342 let Matrix(mut rows) = seen;
350 fn raw_pat<'a>(p: &'a Pat) -> &'a Pat {
352 ast::PatIdent(_, _, Some(ref s)) => raw_pat(&**s),
357 fn check_exhaustive(cx: &MatchCheckCtxt, sp: Span, matrix: &Matrix, source: ast::MatchSource) {
358 match is_useful(cx, matrix, &[DUMMY_WILD_PAT], ConstructWitness) {
359 UsefulWithWitness(pats) => {
360 let witness = match &pats[..] {
361 [ref witness] => &**witness,
362 [] => DUMMY_WILD_PAT,
366 ast::MatchSource::ForLoopDesugar => {
367 // `witness` has the form `Some(<head>)`, peel off the `Some`
368 let witness = match witness.node {
369 ast::PatEnum(_, Some(ref pats)) => match &pats[..] {
376 span_err!(cx.tcx.sess, sp, E0297,
377 "refutable pattern in `for` loop binding: \
379 pat_to_string(witness));
382 span_err!(cx.tcx.sess, sp, E0004,
383 "non-exhaustive patterns: `{}` not covered",
384 pat_to_string(witness)
390 // This is good, wildcard pattern isn't reachable
396 fn const_val_to_expr(value: &ConstVal) -> P<ast::Expr> {
397 let node = match value {
398 &ConstVal::Bool(b) => ast::LitBool(b),
403 node: ast::ExprLit(P(Spanned { node: node, span: DUMMY_SP })),
408 pub struct StaticInliner<'a, 'tcx: 'a> {
409 pub tcx: &'a ty::ctxt<'tcx>,
411 pub renaming_map: Option<&'a mut FnvHashMap<(NodeId, Span), NodeId>>,
414 impl<'a, 'tcx> StaticInliner<'a, 'tcx> {
415 pub fn new<'b>(tcx: &'b ty::ctxt<'tcx>,
416 renaming_map: Option<&'b mut FnvHashMap<(NodeId, Span), NodeId>>)
417 -> StaticInliner<'b, 'tcx> {
421 renaming_map: renaming_map
426 struct RenamingRecorder<'map> {
427 substituted_node_id: NodeId,
429 renaming_map: &'map mut FnvHashMap<(NodeId, Span), NodeId>
432 impl<'map> ast_util::IdVisitingOperation for RenamingRecorder<'map> {
433 fn visit_id(&mut self, node_id: NodeId) {
434 let key = (node_id, self.origin_span);
435 self.renaming_map.insert(key, self.substituted_node_id);
439 impl<'a, 'tcx> Folder for StaticInliner<'a, 'tcx> {
440 fn fold_pat(&mut self, pat: P<Pat>) -> P<Pat> {
441 return match pat.node {
442 ast::PatIdent(..) | ast::PatEnum(..) | ast::PatQPath(..) => {
443 let def = self.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def());
445 Some(DefAssociatedConst(did)) |
446 Some(DefConst(did)) => match lookup_const_by_id(self.tcx, did, Some(pat.id)) {
447 Some(const_expr) => {
448 const_expr_to_pat(self.tcx, const_expr, pat.span).map(|new_pat| {
450 if let Some(ref mut renaming_map) = self.renaming_map {
451 // Record any renamings we do here
452 record_renamings(const_expr, &pat, renaming_map);
460 span_err!(self.tcx.sess, pat.span, E0158,
461 "statics cannot be referenced in patterns");
465 _ => noop_fold_pat(pat, self)
468 _ => noop_fold_pat(pat, self)
471 fn record_renamings(const_expr: &ast::Expr,
472 substituted_pat: &ast::Pat,
473 renaming_map: &mut FnvHashMap<(NodeId, Span), NodeId>) {
474 let mut renaming_recorder = RenamingRecorder {
475 substituted_node_id: substituted_pat.id,
476 origin_span: substituted_pat.span,
477 renaming_map: renaming_map,
480 let mut id_visitor = ast_util::IdVisitor {
481 operation: &mut renaming_recorder,
482 pass_through_items: true,
483 visited_outermost: false,
486 id_visitor.visit_expr(const_expr);
491 /// Constructs a partial witness for a pattern given a list of
492 /// patterns expanded by the specialization step.
494 /// When a pattern P is discovered to be useful, this function is used bottom-up
495 /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
496 /// of values, V, where each value in that set is not covered by any previously
497 /// used patterns and is covered by the pattern P'. Examples:
499 /// left_ty: tuple of 3 elements
500 /// pats: [10, 20, _] => (10, 20, _)
502 /// left_ty: struct X { a: (bool, &'static str), b: usize}
503 /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 }
504 fn construct_witness(cx: &MatchCheckCtxt, ctor: &Constructor,
505 pats: Vec<&Pat>, left_ty: Ty) -> P<Pat> {
506 let pats_len = pats.len();
507 let mut pats = pats.into_iter().map(|p| P((*p).clone()));
508 let pat = match left_ty.sty {
509 ty::TyTuple(_) => ast::PatTup(pats.collect()),
511 ty::TyEnum(cid, _) | ty::TyStruct(cid, _) => {
512 let (vid, is_structure) = match ctor {
514 (vid, cx.tcx.enum_variant_with_id(cid, vid).arg_names.is_some()),
516 (cid, !cx.tcx.is_tuple_struct(cid))
519 let fields = cx.tcx.lookup_struct_fields(vid);
520 let field_pats: Vec<_> = fields.into_iter()
522 .filter(|&(_, ref pat)| pat.node != ast::PatWild(ast::PatWildSingle))
523 .map(|(field, pat)| Spanned {
525 node: ast::FieldPat {
526 ident: ast::Ident::new(field.name),
531 let has_more_fields = field_pats.len() < pats_len;
532 ast::PatStruct(def_to_path(cx.tcx, vid), field_pats, has_more_fields)
534 ast::PatEnum(def_to_path(cx.tcx, vid), Some(pats.collect()))
538 ty::TyRef(_, ty::TypeAndMut { ty, mutbl }) => {
540 ty::TyArray(_, n) => match ctor {
542 assert_eq!(pats_len, n);
543 ast::PatVec(pats.collect(), None, vec!())
547 ty::TySlice(_) => match ctor {
549 assert_eq!(pats_len, n);
550 ast::PatVec(pats.collect(), None, vec!())
554 ty::TyStr => ast::PatWild(ast::PatWildSingle),
557 assert_eq!(pats_len, 1);
558 ast::PatRegion(pats.nth(0).unwrap(), mutbl)
563 ty::TyArray(_, len) => {
564 assert_eq!(pats_len, len);
565 ast::PatVec(pats.collect(), None, vec![])
570 ConstantValue(ref v) => ast::PatLit(const_val_to_expr(v)),
571 _ => ast::PatWild(ast::PatWildSingle),
583 fn missing_constructor(cx: &MatchCheckCtxt, &Matrix(ref rows): &Matrix,
584 left_ty: Ty, max_slice_length: usize) -> Option<Constructor> {
585 let used_constructors: Vec<Constructor> = rows.iter()
586 .flat_map(|row| pat_constructors(cx, row[0], left_ty, max_slice_length))
588 all_constructors(cx, left_ty, max_slice_length)
590 .find(|c| !used_constructors.contains(c))
593 /// This determines the set of all possible constructors of a pattern matching
594 /// values of type `left_ty`. For vectors, this would normally be an infinite set
595 /// but is instead bounded by the maximum fixed length of slice patterns in
596 /// the column of patterns being analyzed.
597 fn all_constructors(cx: &MatchCheckCtxt, left_ty: Ty,
598 max_slice_length: usize) -> Vec<Constructor> {
601 [true, false].iter().map(|b| ConstantValue(ConstVal::Bool(*b))).collect(),
603 ty::TyRef(_, ty::TypeAndMut { ty, .. }) => match ty.sty {
605 range_inclusive(0, max_slice_length).map(|length| Slice(length)).collect(),
609 ty::TyEnum(eid, _) =>
610 cx.tcx.enum_variants(eid)
612 .map(|va| Variant(va.id))
620 // Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
622 // Whether a vector `v` of patterns is 'useful' in relation to a set of such
623 // vectors `m` is defined as there being a set of inputs that will match `v`
624 // but not any of the sets in `m`.
626 // This is used both for reachability checking (if a pattern isn't useful in
627 // relation to preceding patterns, it is not reachable) and exhaustiveness
628 // checking (if a wildcard pattern is useful in relation to a matrix, the
629 // matrix isn't exhaustive).
631 // Note: is_useful doesn't work on empty types, as the paper notes.
632 // So it assumes that v is non-empty.
633 fn is_useful(cx: &MatchCheckCtxt,
636 witness: WitnessPreference)
638 let &Matrix(ref rows) = matrix;
639 debug!("{:?}", matrix);
641 return match witness {
642 ConstructWitness => UsefulWithWitness(vec!()),
643 LeaveOutWitness => Useful
646 if rows[0].is_empty() {
649 assert!(rows.iter().all(|r| r.len() == v.len()));
650 let real_pat = match rows.iter().find(|r| (*r)[0].id != DUMMY_NODE_ID) {
651 Some(r) => raw_pat(r[0]),
652 None if v.is_empty() => return NotUseful,
655 let left_ty = if real_pat.id == DUMMY_NODE_ID {
658 let left_ty = cx.tcx.pat_ty(&*real_pat);
660 match real_pat.node {
661 ast::PatIdent(ast::BindByRef(..), _, _) => {
662 left_ty.builtin_deref(false).unwrap().ty
668 let max_slice_length = rows.iter().filter_map(|row| match row[0].node {
669 ast::PatVec(ref before, _, ref after) => Some(before.len() + after.len()),
671 }).max().map_or(0, |v| v + 1);
673 let constructors = pat_constructors(cx, v[0], left_ty, max_slice_length);
674 if constructors.is_empty() {
675 match missing_constructor(cx, matrix, left_ty, max_slice_length) {
677 all_constructors(cx, left_ty, max_slice_length).into_iter().map(|c| {
678 match is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness) {
679 UsefulWithWitness(pats) => UsefulWithWitness({
680 let arity = constructor_arity(cx, &c, left_ty);
682 let pat_slice = &pats[..];
683 let subpats: Vec<_> = (0..arity).map(|i| {
684 pat_slice.get(i).map_or(DUMMY_WILD_PAT, |p| &**p)
686 vec![construct_witness(cx, &c, subpats, left_ty)]
688 result.extend(pats.into_iter().skip(arity));
693 }).find(|result| result != &NotUseful).unwrap_or(NotUseful)
696 Some(constructor) => {
697 let matrix = rows.iter().filter_map(|r| {
698 if pat_is_binding_or_wild(&cx.tcx.def_map, raw_pat(r[0])) {
699 Some(r[1..].to_vec())
704 match is_useful(cx, &matrix, &v[1..], witness) {
705 UsefulWithWitness(pats) => {
706 let arity = constructor_arity(cx, &constructor, left_ty);
707 let wild_pats = vec![DUMMY_WILD_PAT; arity];
708 let enum_pat = construct_witness(cx, &constructor, wild_pats, left_ty);
709 let mut new_pats = vec![enum_pat];
710 new_pats.extend(pats);
711 UsefulWithWitness(new_pats)
718 constructors.into_iter().map(|c|
719 is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness)
720 ).find(|result| result != &NotUseful).unwrap_or(NotUseful)
724 fn is_useful_specialized(cx: &MatchCheckCtxt, &Matrix(ref m): &Matrix,
725 v: &[&Pat], ctor: Constructor, lty: Ty,
726 witness: WitnessPreference) -> Usefulness {
727 let arity = constructor_arity(cx, &ctor, lty);
728 let matrix = Matrix(m.iter().filter_map(|r| {
729 specialize(cx, &r[..], &ctor, 0, arity)
731 match specialize(cx, v, &ctor, 0, arity) {
732 Some(v) => is_useful(cx, &matrix, &v[..], witness),
737 /// Determines the constructors that the given pattern can be specialized to.
739 /// In most cases, there's only one constructor that a specific pattern
740 /// represents, such as a specific enum variant or a specific literal value.
741 /// Slice patterns, however, can match slices of different lengths. For instance,
742 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
744 /// On the other hand, a wild pattern and an identifier pattern cannot be
745 /// specialized in any way.
746 fn pat_constructors(cx: &MatchCheckCtxt, p: &Pat,
747 left_ty: Ty, max_slice_length: usize) -> Vec<Constructor> {
748 let pat = raw_pat(p);
751 match cx.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
752 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
753 cx.tcx.sess.span_bug(pat.span, "const pattern should've \
755 Some(DefStruct(_)) => vec!(Single),
756 Some(DefVariant(_, id, _)) => vec!(Variant(id)),
760 match cx.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
761 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
762 cx.tcx.sess.span_bug(pat.span, "const pattern should've \
764 Some(DefVariant(_, id, _)) => vec!(Variant(id)),
768 cx.tcx.sess.span_bug(pat.span, "const pattern should've \
770 ast::PatStruct(..) =>
771 match cx.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
772 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
773 cx.tcx.sess.span_bug(pat.span, "const pattern should've \
775 Some(DefVariant(_, id, _)) => vec!(Variant(id)),
778 ast::PatLit(ref expr) =>
779 vec!(ConstantValue(eval_const_expr(cx.tcx, &**expr))),
780 ast::PatRange(ref lo, ref hi) =>
781 vec!(ConstantRange(eval_const_expr(cx.tcx, &**lo), eval_const_expr(cx.tcx, &**hi))),
782 ast::PatVec(ref before, ref slice, ref after) =>
784 ty::TyArray(_, _) => vec!(Single),
785 _ => if slice.is_some() {
786 range_inclusive(before.len() + after.len(), max_slice_length)
787 .map(|length| Slice(length))
790 vec!(Slice(before.len() + after.len()))
793 ast::PatBox(_) | ast::PatTup(_) | ast::PatRegion(..) =>
798 cx.tcx.sess.bug("unexpanded macro")
802 /// This computes the arity of a constructor. The arity of a constructor
803 /// is how many subpattern patterns of that constructor should be expanded to.
805 /// For instance, a tuple pattern (_, 42, Some([])) has the arity of 3.
806 /// A struct pattern's arity is the number of fields it contains, etc.
807 pub fn constructor_arity(cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> usize {
809 ty::TyTuple(ref fs) => fs.len(),
811 ty::TyRef(_, ty::TypeAndMut { ty, .. }) => match ty.sty {
812 ty::TySlice(_) => match *ctor {
813 Slice(length) => length,
814 ConstantValue(_) => 0,
820 ty::TyEnum(eid, _) => {
822 Variant(id) => cx.tcx.enum_variant_with_id(eid, id).args.len(),
826 ty::TyStruct(cid, _) => cx.tcx.lookup_struct_fields(cid).len(),
827 ty::TyArray(_, n) => n,
832 fn range_covered_by_constructor(ctor: &Constructor,
833 from: &ConstVal, to: &ConstVal) -> Option<bool> {
834 let (c_from, c_to) = match *ctor {
835 ConstantValue(ref value) => (value, value),
836 ConstantRange(ref from, ref to) => (from, to),
837 Single => return Some(true),
840 let cmp_from = compare_const_vals(c_from, from);
841 let cmp_to = compare_const_vals(c_to, to);
842 match (cmp_from, cmp_to) {
843 (Some(cmp_from), Some(cmp_to)) => {
844 Some(cmp_from != Ordering::Less && cmp_to != Ordering::Greater)
850 /// This is the main specialization step. It expands the first pattern in the given row
851 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
852 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
854 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
855 /// different patterns.
856 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
857 /// fields filled with wild patterns.
858 pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat],
859 constructor: &Constructor, col: usize, arity: usize) -> Option<Vec<&'a Pat>> {
861 id: pat_id, ref node, span: pat_span
863 let head: Option<Vec<&Pat>> = match *node {
865 Some(vec![DUMMY_WILD_PAT; arity]),
867 ast::PatIdent(_, _, _) => {
868 let opt_def = cx.tcx.def_map.borrow().get(&pat_id).map(|d| d.full_def());
870 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
871 cx.tcx.sess.span_bug(pat_span, "const pattern should've \
873 Some(DefVariant(_, id, _)) => if *constructor == Variant(id) {
878 _ => Some(vec![DUMMY_WILD_PAT; arity])
882 ast::PatEnum(_, ref args) => {
883 let def = cx.tcx.def_map.borrow().get(&pat_id).unwrap().full_def();
885 DefConst(..) | DefAssociatedConst(..) =>
886 cx.tcx.sess.span_bug(pat_span, "const pattern should've \
888 DefVariant(_, id, _) if *constructor != Variant(id) => None,
889 DefVariant(..) | DefStruct(..) => {
891 &Some(ref args) => args.iter().map(|p| &**p).collect(),
892 &None => vec![DUMMY_WILD_PAT; arity],
899 ast::PatQPath(_, _) => {
900 cx.tcx.sess.span_bug(pat_span, "const pattern should've \
904 ast::PatStruct(_, ref pattern_fields, _) => {
905 // Is this a struct or an enum variant?
906 let def = cx.tcx.def_map.borrow().get(&pat_id).unwrap().full_def();
907 let class_id = match def {
908 DefConst(..) | DefAssociatedConst(..) =>
909 cx.tcx.sess.span_bug(pat_span, "const pattern should've \
911 DefVariant(_, variant_id, _) => if *constructor == Variant(variant_id) {
917 // Assume this is a struct.
918 match cx.tcx.node_id_to_type(pat_id).ty_to_def_id() {
920 cx.tcx.sess.span_bug(pat_span,
921 "struct pattern wasn't of a \
922 type with a def ID?!")
924 Some(def_id) => Some(def_id),
928 class_id.map(|variant_id| {
929 let struct_fields = cx.tcx.lookup_struct_fields(variant_id);
930 let args = struct_fields.iter().map(|sf| {
931 match pattern_fields.iter().find(|f| f.node.ident.name == sf.name) {
932 Some(ref f) => &*f.node.pat,
940 ast::PatTup(ref args) =>
941 Some(args.iter().map(|p| &**p).collect()),
943 ast::PatBox(ref inner) | ast::PatRegion(ref inner, _) =>
944 Some(vec![&**inner]),
946 ast::PatLit(ref expr) => {
947 let expr_value = eval_const_expr(cx.tcx, &**expr);
948 match range_covered_by_constructor(constructor, &expr_value, &expr_value) {
949 Some(true) => Some(vec![]),
952 span_err!(cx.tcx.sess, pat_span, E0298, "mismatched types between arms");
958 ast::PatRange(ref from, ref to) => {
959 let from_value = eval_const_expr(cx.tcx, &**from);
960 let to_value = eval_const_expr(cx.tcx, &**to);
961 match range_covered_by_constructor(constructor, &from_value, &to_value) {
962 Some(true) => Some(vec![]),
965 span_err!(cx.tcx.sess, pat_span, E0299, "mismatched types between arms");
971 ast::PatVec(ref before, ref slice, ref after) => {
973 // Fixed-length vectors.
975 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
976 pats.extend(repeat(DUMMY_WILD_PAT).take(arity - before.len() - after.len()));
977 pats.extend(after.iter().map(|p| &**p));
980 Slice(length) if before.len() + after.len() <= length && slice.is_some() => {
981 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
982 pats.extend(repeat(DUMMY_WILD_PAT).take(arity - before.len() - after.len()));
983 pats.extend(after.iter().map(|p| &**p));
986 Slice(length) if before.len() + after.len() == length => {
987 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
988 pats.extend(after.iter().map(|p| &**p));
991 SliceWithSubslice(prefix, suffix)
992 if before.len() == prefix
993 && after.len() == suffix
994 && slice.is_some() => {
995 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
996 pats.extend(after.iter().map(|p| &**p));
1004 span_err!(cx.tcx.sess, pat_span, E0300, "unexpanded macro");
1008 head.map(|mut head| {
1009 head.push_all(&r[..col]);
1010 head.push_all(&r[col + 1..]);
1015 fn check_local(cx: &mut MatchCheckCtxt, loc: &ast::Local) {
1016 visit::walk_local(cx, loc);
1018 let pat = StaticInliner::new(cx.tcx, None).fold_pat(loc.pat.clone());
1019 check_irrefutable(cx, &pat, false);
1021 // Check legality of move bindings and `@` patterns.
1022 check_legality_of_move_bindings(cx, false, slice::ref_slice(&loc.pat));
1023 check_legality_of_bindings_in_at_patterns(cx, &*loc.pat);
1026 fn check_fn(cx: &mut MatchCheckCtxt,
1033 visit::FkFnBlock => {}
1034 _ => cx.param_env = ParameterEnvironment::for_item(cx.tcx, fn_id),
1037 visit::walk_fn(cx, kind, decl, body, sp);
1039 for input in &decl.inputs {
1040 check_irrefutable(cx, &input.pat, true);
1041 check_legality_of_move_bindings(cx, false, slice::ref_slice(&input.pat));
1042 check_legality_of_bindings_in_at_patterns(cx, &*input.pat);
1046 fn check_irrefutable(cx: &MatchCheckCtxt, pat: &Pat, is_fn_arg: bool) {
1047 let origin = if is_fn_arg {
1053 is_refutable(cx, pat, |uncovered_pat| {
1054 span_err!(cx.tcx.sess, pat.span, E0005,
1055 "refutable pattern in {}: `{}` not covered",
1057 pat_to_string(uncovered_pat),
1062 fn is_refutable<A, F>(cx: &MatchCheckCtxt, pat: &Pat, refutable: F) -> Option<A> where
1063 F: FnOnce(&Pat) -> A,
1065 let pats = Matrix(vec!(vec!(pat)));
1066 match is_useful(cx, &pats, &[DUMMY_WILD_PAT], ConstructWitness) {
1067 UsefulWithWitness(pats) => {
1068 assert_eq!(pats.len(), 1);
1069 Some(refutable(&*pats[0]))
1072 Useful => unreachable!()
1076 // Legality of move bindings checking
1077 fn check_legality_of_move_bindings(cx: &MatchCheckCtxt,
1081 let def_map = &tcx.def_map;
1082 let mut by_ref_span = None;
1084 pat_bindings(def_map, &**pat, |bm, _, span, _path| {
1086 ast::BindByRef(_) => {
1087 by_ref_span = Some(span);
1089 ast::BindByValue(_) => {
1095 let check_move = |p: &Pat, sub: Option<&Pat>| {
1096 // check legality of moving out of the enum
1098 // x @ Foo(..) is legal, but x @ Foo(y) isn't.
1099 if sub.map_or(false, |p| pat_contains_bindings(def_map, &*p)) {
1100 span_err!(cx.tcx.sess, p.span, E0007, "cannot bind by-move with sub-bindings");
1101 } else if has_guard {
1102 span_err!(cx.tcx.sess, p.span, E0008, "cannot bind by-move into a pattern guard");
1103 } else if by_ref_span.is_some() {
1104 span_err!(cx.tcx.sess, p.span, E0009,
1105 "cannot bind by-move and by-ref in the same pattern");
1106 span_note!(cx.tcx.sess, by_ref_span.unwrap(), "by-ref binding occurs here");
1111 ast_util::walk_pat(&**pat, |p| {
1112 if pat_is_binding(def_map, &*p) {
1114 ast::PatIdent(ast::BindByValue(_), _, ref sub) => {
1115 let pat_ty = tcx.node_id_to_type(p.id);
1116 //FIXME: (@jroesch) this code should be floated up as well
1117 let infcx = infer::new_infer_ctxt(cx.tcx,
1119 Some(cx.param_env.clone()),
1121 if infcx.type_moves_by_default(pat_ty, pat.span) {
1122 check_move(p, sub.as_ref().map(|p| &**p));
1125 ast::PatIdent(ast::BindByRef(_), _, _) => {
1128 cx.tcx.sess.span_bug(
1130 &format!("binding pattern {} is not an \
1142 /// Ensures that a pattern guard doesn't borrow by mutable reference or
1144 fn check_for_mutation_in_guard<'a, 'tcx>(cx: &'a MatchCheckCtxt<'a, 'tcx>,
1145 guard: &ast::Expr) {
1146 let mut checker = MutationChecker {
1150 let infcx = infer::new_infer_ctxt(cx.tcx,
1152 Some(checker.cx.param_env.clone()),
1155 let mut visitor = ExprUseVisitor::new(&mut checker, &infcx);
1156 visitor.walk_expr(guard);
1159 struct MutationChecker<'a, 'tcx: 'a> {
1160 cx: &'a MatchCheckCtxt<'a, 'tcx>,
1163 impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> {
1164 fn matched_pat(&mut self, _: &Pat, _: cmt, _: euv::MatchMode) {}
1165 fn consume(&mut self, _: NodeId, _: Span, _: cmt, _: ConsumeMode) {}
1166 fn consume_pat(&mut self, _: &Pat, _: cmt, _: ConsumeMode) {}
1167 fn borrow(&mut self,
1176 span_err!(self.cx.tcx.sess, span, E0301,
1177 "cannot mutably borrow in a pattern guard")
1179 ImmBorrow | UniqueImmBorrow => {}
1182 fn decl_without_init(&mut self, _: NodeId, _: Span) {}
1183 fn mutate(&mut self, _: NodeId, span: Span, _: cmt, mode: MutateMode) {
1185 JustWrite | WriteAndRead => {
1186 span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
1193 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
1194 /// because of the way rvalues are handled in the borrow check. (See issue
1196 fn check_legality_of_bindings_in_at_patterns(cx: &MatchCheckCtxt, pat: &Pat) {
1197 AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
1200 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
1201 cx: &'a MatchCheckCtxt<'b, 'tcx>,
1202 bindings_allowed: bool
1205 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
1206 fn visit_pat(&mut self, pat: &Pat) {
1207 if !self.bindings_allowed && pat_is_binding(&self.cx.tcx.def_map, pat) {
1208 span_err!(self.cx.tcx.sess, pat.span, E0303,
1209 "pattern bindings are not allowed \
1214 ast::PatIdent(_, _, Some(_)) => {
1215 let bindings_were_allowed = self.bindings_allowed;
1216 self.bindings_allowed = false;
1217 visit::walk_pat(self, pat);
1218 self.bindings_allowed = bindings_were_allowed;
1220 _ => visit::walk_pat(self, pat),