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::def_id::{DefId};
21 use middle::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, Init};
22 use middle::expr_use_visitor::{JustWrite, LoanCause, MutateMode};
23 use middle::expr_use_visitor::WriteAndRead;
24 use middle::expr_use_visitor as euv;
26 use middle::mem_categorization::{cmt};
27 use middle::pat_util::*;
30 use std::cmp::Ordering;
32 use std::iter::{range_inclusive, FromIterator, IntoIterator, repeat};
34 use syntax::ast::{self, DUMMY_NODE_ID, NodeId, Pat};
36 use syntax::codemap::{Span, Spanned, DUMMY_SP};
37 use syntax::fold::{Folder, noop_fold_pat};
38 use syntax::print::pprust::pat_to_string;
40 use syntax::visit::{self, Visitor, FnKind};
41 use util::nodemap::FnvHashMap;
43 pub const DUMMY_WILD_PAT: &'static Pat = &Pat {
45 node: ast::PatWild(ast::PatWildSingle),
49 struct Matrix<'a>(Vec<Vec<&'a Pat>>);
51 /// Pretty-printer for matrices of patterns, example:
52 /// ++++++++++++++++++++++++++
54 /// ++++++++++++++++++++++++++
55 /// + true + [First] +
56 /// ++++++++++++++++++++++++++
57 /// + true + [Second(true)] +
58 /// ++++++++++++++++++++++++++
60 /// ++++++++++++++++++++++++++
61 /// + _ + [_, _, ..tail] +
62 /// ++++++++++++++++++++++++++
63 impl<'a> fmt::Debug for Matrix<'a> {
64 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
65 try!(write!(f, "\n"));
67 let &Matrix(ref m) = self;
68 let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| {
70 .map(|&pat| pat_to_string(&*pat))
71 .collect::<Vec<String>>()
74 let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0);
75 assert!(m.iter().all(|row| row.len() == column_count));
76 let column_widths: Vec<usize> = (0..column_count).map(|col| {
77 pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0)
80 let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1;
81 let br = repeat('+').take(total_width).collect::<String>();
82 try!(write!(f, "{}\n", br));
83 for row in pretty_printed_matrix {
85 for (column, pat_str) in row.into_iter().enumerate() {
87 try!(write!(f, "{:1$}", pat_str, column_widths[column]));
88 try!(write!(f, " +"));
90 try!(write!(f, "\n"));
91 try!(write!(f, "{}\n", br));
97 impl<'a> FromIterator<Vec<&'a Pat>> for Matrix<'a> {
98 fn from_iter<T: IntoIterator<Item=Vec<&'a Pat>>>(iter: T) -> Matrix<'a> {
99 Matrix(iter.into_iter().collect())
103 //NOTE: appears to be the only place other then InferCtxt to contain a ParamEnv
104 pub struct MatchCheckCtxt<'a, 'tcx: 'a> {
105 pub tcx: &'a ty::ctxt<'tcx>,
106 pub param_env: ParameterEnvironment<'a, 'tcx>,
109 #[derive(Clone, PartialEq)]
110 pub enum Constructor {
111 /// The constructor of all patterns that don't vary by constructor,
112 /// e.g. struct patterns and fixed-length arrays.
117 ConstantValue(ConstVal),
118 /// Ranges of literal values (2..5).
119 ConstantRange(ConstVal, ConstVal),
120 /// Array patterns of length n.
122 /// Array patterns with a subslice.
123 SliceWithSubslice(usize, usize)
126 #[derive(Clone, PartialEq)]
129 UsefulWithWitness(Vec<P<Pat>>),
133 #[derive(Copy, Clone)]
134 enum WitnessPreference {
139 impl<'a, 'tcx, 'v> Visitor<'v> for MatchCheckCtxt<'a, 'tcx> {
140 fn visit_expr(&mut self, ex: &ast::Expr) {
141 check_expr(self, ex);
143 fn visit_local(&mut self, l: &ast::Local) {
144 check_local(self, l);
146 fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v ast::FnDecl,
147 b: &'v ast::Block, s: Span, n: NodeId) {
148 check_fn(self, fk, fd, b, s, n);
152 pub fn check_crate(tcx: &ty::ctxt) {
153 visit::walk_crate(&mut MatchCheckCtxt {
155 param_env: tcx.empty_parameter_environment(),
157 tcx.sess.abort_if_errors();
160 fn check_expr(cx: &mut MatchCheckCtxt, ex: &ast::Expr) {
161 visit::walk_expr(cx, ex);
163 ast::ExprMatch(ref scrut, ref arms, source) => {
165 // First, check legality of move bindings.
166 check_legality_of_move_bindings(cx,
170 // Second, if there is a guard on each arm, make sure it isn't
171 // assigning or borrowing anything mutably.
173 Some(ref guard) => check_for_mutation_in_guard(cx, &**guard),
178 let mut static_inliner = StaticInliner::new(cx.tcx, None);
179 let inlined_arms = arms.iter().map(|arm| {
180 (arm.pats.iter().map(|pat| {
181 static_inliner.fold_pat((*pat).clone())
182 }).collect(), arm.guard.as_ref().map(|e| &**e))
183 }).collect::<Vec<(Vec<P<Pat>>, Option<&ast::Expr>)>>();
185 // Bail out early if inlining failed.
186 if static_inliner.failed {
190 for pat in inlined_arms
192 .flat_map(|&(ref pats, _)| pats) {
193 // Third, check legality of move bindings.
194 check_legality_of_bindings_in_at_patterns(cx, &**pat);
196 // Fourth, check if there are any references to NaN that we should warn about.
197 check_for_static_nan(cx, &**pat);
199 // Fifth, check if for any of the patterns that match an enumerated type
200 // are bindings with the same name as one of the variants of said type.
201 check_for_bindings_named_the_same_as_variants(cx, &**pat);
204 // Fourth, check for unreachable arms.
205 check_arms(cx, &inlined_arms[..], source);
207 // Finally, check if the whole match expression is exhaustive.
208 // Check for empty enum, because is_useful only works on inhabited types.
209 let pat_ty = cx.tcx.node_id_to_type(scrut.id);
210 if inlined_arms.is_empty() {
211 if !pat_ty.is_empty(cx.tcx) {
212 // We know the type is inhabited, so this must be wrong
213 span_err!(cx.tcx.sess, ex.span, E0002,
214 "non-exhaustive patterns: type {} is non-empty",
217 // If the type *is* empty, it's vacuously exhaustive
221 let matrix: Matrix = inlined_arms
223 .filter(|&&(_, guard)| guard.is_none())
224 .flat_map(|arm| &arm.0)
225 .map(|pat| vec![&**pat])
227 check_exhaustive(cx, ex.span, &matrix, source);
233 fn check_for_bindings_named_the_same_as_variants(cx: &MatchCheckCtxt, pat: &Pat) {
234 ast_util::walk_pat(pat, |p| {
236 ast::PatIdent(ast::BindByValue(ast::MutImmutable), ident, None) => {
237 let pat_ty = cx.tcx.pat_ty(p);
238 if let ty::TyEnum(edef, _) = pat_ty.sty {
239 let def = cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def());
240 if let Some(DefLocal(_)) = def {
241 if edef.variants.iter().any(|variant|
242 variant.name == ident.node.name
243 && variant.kind() == VariantKind::Unit
245 span_warn!(cx.tcx.sess, p.span, E0170,
246 "pattern binding `{}` is named the same as one \
247 of the variants of the type `{}`",
249 fileline_help!(cx.tcx.sess, p.span,
250 "if you meant to match on a variant, \
251 consider making the path in the pattern qualified: `{}::{}`",
263 // Check that we do not match against a static NaN (#6804)
264 fn check_for_static_nan(cx: &MatchCheckCtxt, pat: &Pat) {
265 ast_util::walk_pat(pat, |p| {
266 if let ast::PatLit(ref expr) = p.node {
267 match eval_const_expr_partial(cx.tcx, &**expr, ExprTypeChecked) {
268 Ok(ConstVal::Float(f)) if f.is_nan() => {
269 span_warn!(cx.tcx.sess, p.span, E0003,
270 "unmatchable NaN in pattern, \
271 use the is_nan method in a guard instead");
276 let subspan = p.span.lo <= err.span.lo && err.span.hi <= p.span.hi;
277 cx.tcx.sess.span_err(err.span,
278 &format!("constant evaluation error: {}",
281 cx.tcx.sess.span_note(p.span,
291 // Check for unreachable patterns
292 fn check_arms(cx: &MatchCheckCtxt,
293 arms: &[(Vec<P<Pat>>, Option<&ast::Expr>)],
294 source: ast::MatchSource) {
295 let mut seen = Matrix(vec![]);
296 let mut printed_if_let_err = false;
297 for &(ref pats, guard) in arms {
299 let v = vec![&**pat];
301 match is_useful(cx, &seen, &v[..], LeaveOutWitness) {
304 ast::MatchSource::IfLetDesugar { .. } => {
305 if printed_if_let_err {
306 // we already printed an irrefutable if-let pattern error.
307 // We don't want two, that's just confusing.
309 // find the first arm pattern so we can use its span
310 let &(ref first_arm_pats, _) = &arms[0];
311 let first_pat = &first_arm_pats[0];
312 let span = first_pat.span;
313 span_err!(cx.tcx.sess, span, E0162, "irrefutable if-let pattern");
314 printed_if_let_err = true;
318 ast::MatchSource::WhileLetDesugar => {
319 // find the first arm pattern so we can use its span
320 let &(ref first_arm_pats, _) = &arms[0];
321 let first_pat = &first_arm_pats[0];
322 let span = first_pat.span;
323 span_err!(cx.tcx.sess, span, E0165, "irrefutable while-let pattern");
326 ast::MatchSource::ForLoopDesugar => {
327 // this is a bug, because on `match iter.next()` we cover
328 // `Some(<head>)` and `None`. It's impossible to have an unreachable
330 // (see libsyntax/ext/expand.rs for the full expansion of a for loop)
331 cx.tcx.sess.span_bug(pat.span, "unreachable for-loop pattern")
334 ast::MatchSource::Normal => {
335 span_err!(cx.tcx.sess, pat.span, E0001, "unreachable pattern")
340 UsefulWithWitness(_) => unreachable!()
343 let Matrix(mut rows) = seen;
351 fn raw_pat<'a>(p: &'a Pat) -> &'a Pat {
353 ast::PatIdent(_, _, Some(ref s)) => raw_pat(&**s),
358 fn check_exhaustive(cx: &MatchCheckCtxt, sp: Span, matrix: &Matrix, source: ast::MatchSource) {
359 match is_useful(cx, matrix, &[DUMMY_WILD_PAT], ConstructWitness) {
360 UsefulWithWitness(pats) => {
361 let witness = match &pats[..] {
362 [ref witness] => &**witness,
363 [] => DUMMY_WILD_PAT,
367 ast::MatchSource::ForLoopDesugar => {
368 // `witness` has the form `Some(<head>)`, peel off the `Some`
369 let witness = match witness.node {
370 ast::PatEnum(_, Some(ref pats)) => match &pats[..] {
377 span_err!(cx.tcx.sess, sp, E0297,
378 "refutable pattern in `for` loop binding: \
380 pat_to_string(witness));
383 span_err!(cx.tcx.sess, sp, E0004,
384 "non-exhaustive patterns: `{}` not covered",
385 pat_to_string(witness)
391 // This is good, wildcard pattern isn't reachable
397 fn const_val_to_expr(value: &ConstVal) -> P<ast::Expr> {
398 let node = match value {
399 &ConstVal::Bool(b) => ast::LitBool(b),
404 node: ast::ExprLit(P(Spanned { node: node, span: DUMMY_SP })),
409 pub struct StaticInliner<'a, 'tcx: 'a> {
410 pub tcx: &'a ty::ctxt<'tcx>,
412 pub renaming_map: Option<&'a mut FnvHashMap<(NodeId, Span), NodeId>>,
415 impl<'a, 'tcx> StaticInliner<'a, 'tcx> {
416 pub fn new<'b>(tcx: &'b ty::ctxt<'tcx>,
417 renaming_map: Option<&'b mut FnvHashMap<(NodeId, Span), NodeId>>)
418 -> StaticInliner<'b, 'tcx> {
422 renaming_map: renaming_map
427 struct RenamingRecorder<'map> {
428 substituted_node_id: NodeId,
430 renaming_map: &'map mut FnvHashMap<(NodeId, Span), NodeId>
433 impl<'map> ast_util::IdVisitingOperation for RenamingRecorder<'map> {
434 fn visit_id(&mut self, node_id: NodeId) {
435 let key = (node_id, self.origin_span);
436 self.renaming_map.insert(key, self.substituted_node_id);
440 impl<'a, 'tcx> Folder for StaticInliner<'a, 'tcx> {
441 fn fold_pat(&mut self, pat: P<Pat>) -> P<Pat> {
442 return match pat.node {
443 ast::PatIdent(..) | ast::PatEnum(..) | ast::PatQPath(..) => {
444 let def = self.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def());
446 Some(DefAssociatedConst(did)) |
447 Some(DefConst(did)) => match lookup_const_by_id(self.tcx, did, Some(pat.id)) {
448 Some(const_expr) => {
449 const_expr_to_pat(self.tcx, const_expr, pat.span).map(|new_pat| {
451 if let Some(ref mut renaming_map) = self.renaming_map {
452 // Record any renamings we do here
453 record_renamings(const_expr, &pat, renaming_map);
461 span_err!(self.tcx.sess, pat.span, E0158,
462 "statics cannot be referenced in patterns");
466 _ => noop_fold_pat(pat, self)
469 _ => noop_fold_pat(pat, self)
472 fn record_renamings(const_expr: &ast::Expr,
473 substituted_pat: &ast::Pat,
474 renaming_map: &mut FnvHashMap<(NodeId, Span), NodeId>) {
475 let mut renaming_recorder = RenamingRecorder {
476 substituted_node_id: substituted_pat.id,
477 origin_span: substituted_pat.span,
478 renaming_map: renaming_map,
481 let mut id_visitor = ast_util::IdVisitor {
482 operation: &mut renaming_recorder,
483 pass_through_items: true,
484 visited_outermost: false,
487 id_visitor.visit_expr(const_expr);
492 /// Constructs a partial witness for a pattern given a list of
493 /// patterns expanded by the specialization step.
495 /// When a pattern P is discovered to be useful, this function is used bottom-up
496 /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
497 /// of values, V, where each value in that set is not covered by any previously
498 /// used patterns and is covered by the pattern P'. Examples:
500 /// left_ty: tuple of 3 elements
501 /// pats: [10, 20, _] => (10, 20, _)
503 /// left_ty: struct X { a: (bool, &'static str), b: usize}
504 /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 }
505 fn construct_witness<'a,'tcx>(cx: &MatchCheckCtxt<'a,'tcx>, ctor: &Constructor,
506 pats: Vec<&Pat>, left_ty: Ty<'tcx>) -> P<Pat> {
507 let pats_len = pats.len();
508 let mut pats = pats.into_iter().map(|p| P((*p).clone()));
509 let pat = match left_ty.sty {
510 ty::TyTuple(_) => ast::PatTup(pats.collect()),
512 ty::TyEnum(adt, _) | ty::TyStruct(adt, _) => {
513 let v = adt.variant_of_ctor(ctor);
514 if let VariantKind::Dict = v.kind() {
515 let field_pats: Vec<_> = v.fields.iter()
517 .filter(|&(_, ref pat)| pat.node != ast::PatWild(ast::PatWildSingle))
518 .map(|(field, pat)| Spanned {
520 node: ast::FieldPat {
521 ident: ast::Ident::new(field.name),
526 let has_more_fields = field_pats.len() < pats_len;
527 ast::PatStruct(def_to_path(cx.tcx, v.did), field_pats, has_more_fields)
529 ast::PatEnum(def_to_path(cx.tcx, v.did), Some(pats.collect()))
533 ty::TyRef(_, ty::TypeAndMut { ty, mutbl }) => {
535 ty::TyArray(_, n) => match ctor {
537 assert_eq!(pats_len, n);
538 ast::PatVec(pats.collect(), None, vec!())
542 ty::TySlice(_) => match ctor {
544 assert_eq!(pats_len, n);
545 ast::PatVec(pats.collect(), None, vec!())
549 ty::TyStr => ast::PatWild(ast::PatWildSingle),
552 assert_eq!(pats_len, 1);
553 ast::PatRegion(pats.nth(0).unwrap(), mutbl)
558 ty::TyArray(_, len) => {
559 assert_eq!(pats_len, len);
560 ast::PatVec(pats.collect(), None, vec![])
565 ConstantValue(ref v) => ast::PatLit(const_val_to_expr(v)),
566 _ => ast::PatWild(ast::PatWildSingle),
578 impl<'tcx, 'container> ty::AdtDefData<'tcx, 'container> {
579 fn variant_of_ctor(&self,
581 -> &VariantDefData<'tcx, 'container> {
583 &Variant(vid) => self.variant_with_id(vid),
584 _ => self.struct_variant()
589 fn missing_constructor(cx: &MatchCheckCtxt, &Matrix(ref rows): &Matrix,
590 left_ty: Ty, max_slice_length: usize) -> Option<Constructor> {
591 let used_constructors: Vec<Constructor> = rows.iter()
592 .flat_map(|row| pat_constructors(cx, row[0], left_ty, max_slice_length))
594 all_constructors(cx, left_ty, max_slice_length)
596 .find(|c| !used_constructors.contains(c))
599 /// This determines the set of all possible constructors of a pattern matching
600 /// values of type `left_ty`. For vectors, this would normally be an infinite set
601 /// but is instead bounded by the maximum fixed length of slice patterns in
602 /// the column of patterns being analyzed.
603 fn all_constructors(_cx: &MatchCheckCtxt, left_ty: Ty,
604 max_slice_length: usize) -> Vec<Constructor> {
607 [true, false].iter().map(|b| ConstantValue(ConstVal::Bool(*b))).collect(),
609 ty::TyRef(_, ty::TypeAndMut { ty, .. }) => match ty.sty {
611 range_inclusive(0, max_slice_length).map(|length| Slice(length)).collect(),
615 ty::TyEnum(def, _) => def.variants.iter().map(|v| Variant(v.did)).collect(),
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(adt, _) | ty::TyStruct(adt, _) => {
821 adt.variant_of_ctor(ctor).fields.len()
823 ty::TyArray(_, n) => n,
828 fn range_covered_by_constructor(ctor: &Constructor,
829 from: &ConstVal, to: &ConstVal) -> Option<bool> {
830 let (c_from, c_to) = match *ctor {
831 ConstantValue(ref value) => (value, value),
832 ConstantRange(ref from, ref to) => (from, to),
833 Single => return Some(true),
836 let cmp_from = compare_const_vals(c_from, from);
837 let cmp_to = compare_const_vals(c_to, to);
838 match (cmp_from, cmp_to) {
839 (Some(cmp_from), Some(cmp_to)) => {
840 Some(cmp_from != Ordering::Less && cmp_to != Ordering::Greater)
846 /// This is the main specialization step. It expands the first pattern in the given row
847 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
848 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
850 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
851 /// different patterns.
852 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
853 /// fields filled with wild patterns.
854 pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat],
855 constructor: &Constructor, col: usize, arity: usize) -> Option<Vec<&'a Pat>> {
857 id: pat_id, ref node, span: pat_span
859 let head: Option<Vec<&Pat>> = match *node {
861 Some(vec![DUMMY_WILD_PAT; arity]),
863 ast::PatIdent(_, _, _) => {
864 let opt_def = cx.tcx.def_map.borrow().get(&pat_id).map(|d| d.full_def());
866 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
867 cx.tcx.sess.span_bug(pat_span, "const pattern should've \
869 Some(DefVariant(_, id, _)) => if *constructor == Variant(id) {
874 _ => Some(vec![DUMMY_WILD_PAT; arity])
878 ast::PatEnum(_, ref args) => {
879 let def = cx.tcx.def_map.borrow().get(&pat_id).unwrap().full_def();
881 DefConst(..) | DefAssociatedConst(..) =>
882 cx.tcx.sess.span_bug(pat_span, "const pattern should've \
884 DefVariant(_, id, _) if *constructor != Variant(id) => None,
885 DefVariant(..) | DefStruct(..) => {
887 &Some(ref args) => args.iter().map(|p| &**p).collect(),
888 &None => vec![DUMMY_WILD_PAT; arity],
895 ast::PatQPath(_, _) => {
896 cx.tcx.sess.span_bug(pat_span, "const pattern should've \
900 ast::PatStruct(_, ref pattern_fields, _) => {
901 let def = cx.tcx.def_map.borrow().get(&pat_id).unwrap().full_def();
902 let adt = cx.tcx.node_id_to_type(pat_id).ty_adt_def().unwrap();
903 let variant = adt.variant_of_ctor(constructor);
904 let def_variant = adt.variant_of_def(def);
905 if variant.did == def_variant.did {
906 Some(variant.fields.iter().map(|sf| {
907 match pattern_fields.iter().find(|f| f.node.ident.name == sf.name) {
908 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 pat = StaticInliner::new(cx.tcx, None).fold_pat(loc.pat.clone());
996 check_irrefutable(cx, &pat, false);
998 // Check legality of move bindings and `@` patterns.
999 check_legality_of_move_bindings(cx, false, slice::ref_slice(&loc.pat));
1000 check_legality_of_bindings_in_at_patterns(cx, &*loc.pat);
1003 fn check_fn(cx: &mut MatchCheckCtxt,
1010 FnKind::Closure => {}
1011 _ => cx.param_env = ParameterEnvironment::for_item(cx.tcx, fn_id),
1014 visit::walk_fn(cx, kind, decl, body, sp);
1016 for input in &decl.inputs {
1017 check_irrefutable(cx, &input.pat, true);
1018 check_legality_of_move_bindings(cx, false, slice::ref_slice(&input.pat));
1019 check_legality_of_bindings_in_at_patterns(cx, &*input.pat);
1023 fn check_irrefutable(cx: &MatchCheckCtxt, pat: &Pat, is_fn_arg: bool) {
1024 let origin = if is_fn_arg {
1030 is_refutable(cx, pat, |uncovered_pat| {
1031 span_err!(cx.tcx.sess, pat.span, E0005,
1032 "refutable pattern in {}: `{}` not covered",
1034 pat_to_string(uncovered_pat),
1039 fn is_refutable<A, F>(cx: &MatchCheckCtxt, pat: &Pat, refutable: F) -> Option<A> where
1040 F: FnOnce(&Pat) -> A,
1042 let pats = Matrix(vec!(vec!(pat)));
1043 match is_useful(cx, &pats, &[DUMMY_WILD_PAT], ConstructWitness) {
1044 UsefulWithWitness(pats) => {
1045 assert_eq!(pats.len(), 1);
1046 Some(refutable(&*pats[0]))
1049 Useful => unreachable!()
1053 // Legality of move bindings checking
1054 fn check_legality_of_move_bindings(cx: &MatchCheckCtxt,
1058 let def_map = &tcx.def_map;
1059 let mut by_ref_span = None;
1061 pat_bindings(def_map, &**pat, |bm, _, span, _path| {
1063 ast::BindByRef(_) => {
1064 by_ref_span = Some(span);
1066 ast::BindByValue(_) => {
1072 let check_move = |p: &Pat, sub: Option<&Pat>| {
1073 // check legality of moving out of the enum
1075 // x @ Foo(..) is legal, but x @ Foo(y) isn't.
1076 if sub.map_or(false, |p| pat_contains_bindings(def_map, &*p)) {
1077 span_err!(cx.tcx.sess, p.span, E0007, "cannot bind by-move with sub-bindings");
1078 } else if has_guard {
1079 span_err!(cx.tcx.sess, p.span, E0008, "cannot bind by-move into a pattern guard");
1080 } else if by_ref_span.is_some() {
1081 span_err!(cx.tcx.sess, p.span, E0009,
1082 "cannot bind by-move and by-ref in the same pattern");
1083 span_note!(cx.tcx.sess, by_ref_span.unwrap(), "by-ref binding occurs here");
1088 ast_util::walk_pat(&**pat, |p| {
1089 if pat_is_binding(def_map, &*p) {
1091 ast::PatIdent(ast::BindByValue(_), _, ref sub) => {
1092 let pat_ty = tcx.node_id_to_type(p.id);
1093 //FIXME: (@jroesch) this code should be floated up as well
1094 let infcx = infer::new_infer_ctxt(cx.tcx,
1096 Some(cx.param_env.clone()),
1098 if infcx.type_moves_by_default(pat_ty, pat.span) {
1099 check_move(p, sub.as_ref().map(|p| &**p));
1102 ast::PatIdent(ast::BindByRef(_), _, _) => {
1105 cx.tcx.sess.span_bug(
1107 &format!("binding pattern {} is not an \
1119 /// Ensures that a pattern guard doesn't borrow by mutable reference or
1121 fn check_for_mutation_in_guard<'a, 'tcx>(cx: &'a MatchCheckCtxt<'a, 'tcx>,
1122 guard: &ast::Expr) {
1123 let mut checker = MutationChecker {
1127 let infcx = infer::new_infer_ctxt(cx.tcx,
1129 Some(checker.cx.param_env.clone()),
1132 let mut visitor = ExprUseVisitor::new(&mut checker, &infcx);
1133 visitor.walk_expr(guard);
1136 struct MutationChecker<'a, 'tcx: 'a> {
1137 cx: &'a MatchCheckCtxt<'a, 'tcx>,
1140 impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> {
1141 fn matched_pat(&mut self, _: &Pat, _: cmt, _: euv::MatchMode) {}
1142 fn consume(&mut self, _: NodeId, _: Span, _: cmt, _: ConsumeMode) {}
1143 fn consume_pat(&mut self, _: &Pat, _: cmt, _: ConsumeMode) {}
1144 fn borrow(&mut self,
1153 span_err!(self.cx.tcx.sess, span, E0301,
1154 "cannot mutably borrow in a pattern guard")
1156 ImmBorrow | UniqueImmBorrow => {}
1159 fn decl_without_init(&mut self, _: NodeId, _: Span) {}
1160 fn mutate(&mut self, _: NodeId, span: Span, _: cmt, mode: MutateMode) {
1162 JustWrite | WriteAndRead => {
1163 span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
1170 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
1171 /// because of the way rvalues are handled in the borrow check. (See issue
1173 fn check_legality_of_bindings_in_at_patterns(cx: &MatchCheckCtxt, pat: &Pat) {
1174 AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
1177 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
1178 cx: &'a MatchCheckCtxt<'b, 'tcx>,
1179 bindings_allowed: bool
1182 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
1183 fn visit_pat(&mut self, pat: &Pat) {
1184 if !self.bindings_allowed && pat_is_binding(&self.cx.tcx.def_map, pat) {
1185 span_err!(self.cx.tcx.sess, pat.span, E0303,
1186 "pattern bindings are not allowed \
1191 ast::PatIdent(_, _, Some(_)) => {
1192 let bindings_were_allowed = self.bindings_allowed;
1193 self.bindings_allowed = false;
1194 visit::walk_pat(self, pat);
1195 self.bindings_allowed = bindings_were_allowed;
1197 _ => visit::walk_pat(self, pat),