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};
36 use rustc_front::hir::Pat;
37 use rustc_front::visit::{self, Visitor, FnKind};
38 use rustc_front::util as front_util;
40 use syntax::ast::{self, DUMMY_NODE_ID, NodeId};
42 use syntax::codemap::{Span, Spanned, DUMMY_SP};
43 use rustc_front::fold::{Folder, noop_fold_pat};
44 use rustc_front::print::pprust::pat_to_string;
46 use util::nodemap::FnvHashMap;
48 pub const DUMMY_WILD_PAT: &'static Pat = &Pat {
50 node: hir::PatWild(hir::PatWildSingle),
54 struct Matrix<'a>(Vec<Vec<&'a Pat>>);
56 /// Pretty-printer for matrices of patterns, example:
57 /// ++++++++++++++++++++++++++
59 /// ++++++++++++++++++++++++++
60 /// + true + [First] +
61 /// ++++++++++++++++++++++++++
62 /// + true + [Second(true)] +
63 /// ++++++++++++++++++++++++++
65 /// ++++++++++++++++++++++++++
66 /// + _ + [_, _, ..tail] +
67 /// ++++++++++++++++++++++++++
68 impl<'a> fmt::Debug for Matrix<'a> {
69 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70 try!(write!(f, "\n"));
72 let &Matrix(ref m) = self;
73 let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| {
75 .map(|&pat| pat_to_string(&*pat))
76 .collect::<Vec<String>>()
79 let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0);
80 assert!(m.iter().all(|row| row.len() == column_count));
81 let column_widths: Vec<usize> = (0..column_count).map(|col| {
82 pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0)
85 let total_width = column_widths.iter().cloned().sum::<usize>() + column_count * 3 + 1;
86 let br = repeat('+').take(total_width).collect::<String>();
87 try!(write!(f, "{}\n", br));
88 for row in pretty_printed_matrix {
90 for (column, pat_str) in row.into_iter().enumerate() {
92 try!(write!(f, "{:1$}", pat_str, column_widths[column]));
93 try!(write!(f, " +"));
95 try!(write!(f, "\n"));
96 try!(write!(f, "{}\n", br));
102 impl<'a> FromIterator<Vec<&'a Pat>> for Matrix<'a> {
103 fn from_iter<T: IntoIterator<Item=Vec<&'a Pat>>>(iter: T) -> Matrix<'a> {
104 Matrix(iter.into_iter().collect())
108 //NOTE: appears to be the only place other then InferCtxt to contain a ParamEnv
109 pub struct MatchCheckCtxt<'a, 'tcx: 'a> {
110 pub tcx: &'a ty::ctxt<'tcx>,
111 pub param_env: ParameterEnvironment<'a, 'tcx>,
114 #[derive(Clone, PartialEq)]
115 pub enum Constructor {
116 /// The constructor of all patterns that don't vary by constructor,
117 /// e.g. struct patterns and fixed-length arrays.
122 ConstantValue(ConstVal),
123 /// Ranges of literal values (2..5).
124 ConstantRange(ConstVal, ConstVal),
125 /// Array patterns of length n.
127 /// Array patterns with a subslice.
128 SliceWithSubslice(usize, usize)
131 #[derive(Clone, PartialEq)]
134 UsefulWithWitness(Vec<P<Pat>>),
138 #[derive(Copy, Clone)]
139 enum WitnessPreference {
144 impl<'a, 'tcx, 'v> Visitor<'v> for MatchCheckCtxt<'a, 'tcx> {
145 fn visit_expr(&mut self, ex: &hir::Expr) {
146 check_expr(self, ex);
148 fn visit_local(&mut self, l: &hir::Local) {
149 check_local(self, l);
151 fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v hir::FnDecl,
152 b: &'v hir::Block, s: Span, n: NodeId) {
153 check_fn(self, fk, fd, b, s, n);
157 pub fn check_crate(tcx: &ty::ctxt) {
158 visit::walk_crate(&mut MatchCheckCtxt {
160 param_env: tcx.empty_parameter_environment(),
162 tcx.sess.abort_if_errors();
165 fn check_expr(cx: &mut MatchCheckCtxt, ex: &hir::Expr) {
166 visit::walk_expr(cx, ex);
168 hir::ExprMatch(ref scrut, ref arms, source) => {
170 // First, check legality of move bindings.
171 check_legality_of_move_bindings(cx,
175 // Second, if there is a guard on each arm, make sure it isn't
176 // assigning or borrowing anything mutably.
178 Some(ref guard) => check_for_mutation_in_guard(cx, &**guard),
183 let mut static_inliner = StaticInliner::new(cx.tcx, None);
184 let inlined_arms = arms.iter().map(|arm| {
185 (arm.pats.iter().map(|pat| {
186 static_inliner.fold_pat((*pat).clone())
187 }).collect(), arm.guard.as_ref().map(|e| &**e))
188 }).collect::<Vec<(Vec<P<Pat>>, Option<&hir::Expr>)>>();
190 // Bail out early if inlining failed.
191 if static_inliner.failed {
195 for pat in inlined_arms
197 .flat_map(|&(ref pats, _)| pats) {
198 // Third, check legality of move bindings.
199 check_legality_of_bindings_in_at_patterns(cx, &**pat);
201 // Fourth, check if there are any references to NaN that we should warn about.
202 check_for_static_nan(cx, &**pat);
204 // Fifth, check if for any of the patterns that match an enumerated type
205 // are bindings with the same name as one of the variants of said type.
206 check_for_bindings_named_the_same_as_variants(cx, &**pat);
209 // Fourth, check for unreachable arms.
210 check_arms(cx, &inlined_arms[..], source);
212 // Finally, check if the whole match expression is exhaustive.
213 // Check for empty enum, because is_useful only works on inhabited types.
214 let pat_ty = cx.tcx.node_id_to_type(scrut.id);
215 if inlined_arms.is_empty() {
216 if !pat_ty.is_empty(cx.tcx) {
217 // We know the type is inhabited, so this must be wrong
218 span_err!(cx.tcx.sess, ex.span, E0002,
219 "non-exhaustive patterns: type {} is non-empty",
222 // If the type *is* empty, it's vacuously exhaustive
226 let matrix: Matrix = inlined_arms
228 .filter(|&&(_, guard)| guard.is_none())
229 .flat_map(|arm| &arm.0)
230 .map(|pat| vec![&**pat])
232 check_exhaustive(cx, ex.span, &matrix, source);
238 fn check_for_bindings_named_the_same_as_variants(cx: &MatchCheckCtxt, pat: &Pat) {
239 front_util::walk_pat(pat, |p| {
241 hir::PatIdent(hir::BindByValue(hir::MutImmutable), ident, None) => {
242 let pat_ty = cx.tcx.pat_ty(p);
243 if let ty::TyEnum(edef, _) = pat_ty.sty {
244 let def = cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def());
245 if let Some(DefLocal(_)) = def {
246 if edef.variants.iter().any(|variant|
247 variant.name == ident.node.name
248 && variant.kind() == VariantKind::Unit
250 span_warn!(cx.tcx.sess, p.span, E0170,
251 "pattern binding `{}` is named the same as one \
252 of the variants of the type `{}`",
254 fileline_help!(cx.tcx.sess, p.span,
255 "if you meant to match on a variant, \
256 consider making the path in the pattern qualified: `{}::{}`",
268 // Check that we do not match against a static NaN (#6804)
269 fn check_for_static_nan(cx: &MatchCheckCtxt, pat: &Pat) {
270 front_util::walk_pat(pat, |p| {
271 if let hir::PatLit(ref expr) = p.node {
272 match eval_const_expr_partial(cx.tcx, &**expr, ExprTypeChecked) {
273 Ok(ConstVal::Float(f)) if f.is_nan() => {
274 span_warn!(cx.tcx.sess, p.span, E0003,
275 "unmatchable NaN in pattern, \
276 use the is_nan method in a guard instead");
281 let subspan = p.span.lo <= err.span.lo && err.span.hi <= p.span.hi;
282 cx.tcx.sess.span_err(err.span,
283 &format!("constant evaluation error: {}",
286 cx.tcx.sess.span_note(p.span,
296 // Check for unreachable patterns
297 fn check_arms(cx: &MatchCheckCtxt,
298 arms: &[(Vec<P<Pat>>, Option<&hir::Expr>)],
299 source: hir::MatchSource) {
300 let mut seen = Matrix(vec![]);
301 let mut printed_if_let_err = false;
302 for &(ref pats, guard) in arms {
304 let v = vec![&**pat];
306 match is_useful(cx, &seen, &v[..], LeaveOutWitness) {
309 hir::MatchSource::IfLetDesugar { .. } => {
310 if printed_if_let_err {
311 // we already printed an irrefutable if-let pattern error.
312 // We don't want two, that's just confusing.
314 // find the first arm pattern so we can use its span
315 let &(ref first_arm_pats, _) = &arms[0];
316 let first_pat = &first_arm_pats[0];
317 let span = first_pat.span;
318 span_err!(cx.tcx.sess, span, E0162, "irrefutable if-let pattern");
319 printed_if_let_err = true;
323 hir::MatchSource::WhileLetDesugar => {
324 // find the first arm pattern so we can use its span
325 let &(ref first_arm_pats, _) = &arms[0];
326 let first_pat = &first_arm_pats[0];
327 let span = first_pat.span;
328 span_err!(cx.tcx.sess, span, E0165, "irrefutable while-let pattern");
331 hir::MatchSource::ForLoopDesugar => {
332 // this is a bug, because on `match iter.next()` we cover
333 // `Some(<head>)` and `None`. It's impossible to have an unreachable
335 // (see libsyntax/ext/expand.rs for the full expansion of a for loop)
336 cx.tcx.sess.span_bug(pat.span, "unreachable for-loop pattern")
339 hir::MatchSource::Normal => {
340 span_err!(cx.tcx.sess, pat.span, E0001, "unreachable pattern")
345 UsefulWithWitness(_) => unreachable!()
348 let Matrix(mut rows) = seen;
356 fn raw_pat<'a>(p: &'a Pat) -> &'a Pat {
358 hir::PatIdent(_, _, Some(ref s)) => raw_pat(&**s),
363 fn check_exhaustive(cx: &MatchCheckCtxt, sp: Span, matrix: &Matrix, source: hir::MatchSource) {
364 match is_useful(cx, matrix, &[DUMMY_WILD_PAT], ConstructWitness) {
365 UsefulWithWitness(pats) => {
366 let witness = match &pats[..] {
367 [ref witness] => &**witness,
368 [] => DUMMY_WILD_PAT,
372 hir::MatchSource::ForLoopDesugar => {
373 // `witness` has the form `Some(<head>)`, peel off the `Some`
374 let witness = match witness.node {
375 hir::PatEnum(_, Some(ref pats)) => match &pats[..] {
382 span_err!(cx.tcx.sess, sp, E0297,
383 "refutable pattern in `for` loop binding: \
385 pat_to_string(witness));
388 span_err!(cx.tcx.sess, sp, E0004,
389 "non-exhaustive patterns: `{}` not covered",
390 pat_to_string(witness)
396 // This is good, wildcard pattern isn't reachable
402 fn const_val_to_expr(value: &ConstVal) -> P<hir::Expr> {
403 let node = match value {
404 &ConstVal::Bool(b) => hir::LitBool(b),
409 node: hir::ExprLit(P(Spanned { node: node, span: DUMMY_SP })),
414 pub struct StaticInliner<'a, 'tcx: 'a> {
415 pub tcx: &'a ty::ctxt<'tcx>,
417 pub renaming_map: Option<&'a mut FnvHashMap<(NodeId, Span), NodeId>>,
420 impl<'a, 'tcx> StaticInliner<'a, 'tcx> {
421 pub fn new<'b>(tcx: &'b ty::ctxt<'tcx>,
422 renaming_map: Option<&'b mut FnvHashMap<(NodeId, Span), NodeId>>)
423 -> StaticInliner<'b, 'tcx> {
427 renaming_map: renaming_map
432 struct RenamingRecorder<'map> {
433 substituted_node_id: NodeId,
435 renaming_map: &'map mut FnvHashMap<(NodeId, Span), NodeId>
438 impl<'map> ast_util::IdVisitingOperation for RenamingRecorder<'map> {
439 fn visit_id(&mut self, node_id: NodeId) {
440 let key = (node_id, self.origin_span);
441 self.renaming_map.insert(key, self.substituted_node_id);
445 impl<'a, 'tcx> Folder for StaticInliner<'a, 'tcx> {
446 fn fold_pat(&mut self, pat: P<Pat>) -> P<Pat> {
447 return match pat.node {
448 hir::PatIdent(..) | hir::PatEnum(..) | hir::PatQPath(..) => {
449 let def = self.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def());
451 Some(DefAssociatedConst(did)) |
452 Some(DefConst(did)) => match lookup_const_by_id(self.tcx, did, Some(pat.id)) {
453 Some(const_expr) => {
454 const_expr_to_pat(self.tcx, const_expr, pat.span).map(|new_pat| {
456 if let Some(ref mut renaming_map) = self.renaming_map {
457 // Record any renamings we do here
458 record_renamings(const_expr, &pat, renaming_map);
466 span_err!(self.tcx.sess, pat.span, E0158,
467 "statics cannot be referenced in patterns");
471 _ => noop_fold_pat(pat, self)
474 _ => noop_fold_pat(pat, self)
477 fn record_renamings(const_expr: &hir::Expr,
478 substituted_pat: &hir::Pat,
479 renaming_map: &mut FnvHashMap<(NodeId, Span), NodeId>) {
480 let mut renaming_recorder = RenamingRecorder {
481 substituted_node_id: substituted_pat.id,
482 origin_span: substituted_pat.span,
483 renaming_map: renaming_map,
486 let mut id_visitor = front_util::IdVisitor {
487 operation: &mut renaming_recorder,
488 pass_through_items: true,
489 visited_outermost: false,
492 id_visitor.visit_expr(const_expr);
497 /// Constructs a partial witness for a pattern given a list of
498 /// patterns expanded by the specialization step.
500 /// When a pattern P is discovered to be useful, this function is used bottom-up
501 /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
502 /// of values, V, where each value in that set is not covered by any previously
503 /// used patterns and is covered by the pattern P'. Examples:
505 /// left_ty: tuple of 3 elements
506 /// pats: [10, 20, _] => (10, 20, _)
508 /// left_ty: struct X { a: (bool, &'static str), b: usize}
509 /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 }
510 fn construct_witness<'a,'tcx>(cx: &MatchCheckCtxt<'a,'tcx>, ctor: &Constructor,
511 pats: Vec<&Pat>, left_ty: Ty<'tcx>) -> P<Pat> {
512 let pats_len = pats.len();
513 let mut pats = pats.into_iter().map(|p| P((*p).clone()));
514 let pat = match left_ty.sty {
515 ty::TyTuple(_) => hir::PatTup(pats.collect()),
517 ty::TyEnum(adt, _) | ty::TyStruct(adt, _) => {
518 let v = adt.variant_of_ctor(ctor);
519 if let VariantKind::Dict = v.kind() {
520 let field_pats: Vec<_> = v.fields.iter()
522 .filter(|&(_, ref pat)| pat.node != hir::PatWild(hir::PatWildSingle))
523 .map(|(field, pat)| Spanned {
525 node: hir::FieldPat {
526 ident: ast::Ident::new(field.name),
531 let has_more_fields = field_pats.len() < pats_len;
532 hir::PatStruct(def_to_path(cx.tcx, v.did), field_pats, has_more_fields)
534 hir::PatEnum(def_to_path(cx.tcx, v.did), Some(pats.collect()))
538 ty::TyRef(_, ty::TypeAndMut { ty, mutbl }) => {
540 ty::TyArray(_, n) => match ctor {
542 assert_eq!(pats_len, n);
543 hir::PatVec(pats.collect(), None, vec!())
547 ty::TySlice(_) => match ctor {
549 assert_eq!(pats_len, n);
550 hir::PatVec(pats.collect(), None, vec!())
554 ty::TyStr => hir::PatWild(hir::PatWildSingle),
557 assert_eq!(pats_len, 1);
558 hir::PatRegion(pats.nth(0).unwrap(), mutbl)
563 ty::TyArray(_, len) => {
564 assert_eq!(pats_len, len);
565 hir::PatVec(pats.collect(), None, vec![])
570 ConstantValue(ref v) => hir::PatLit(const_val_to_expr(v)),
571 _ => hir::PatWild(hir::PatWildSingle),
583 impl<'tcx, 'container> ty::AdtDefData<'tcx, 'container> {
584 fn variant_of_ctor(&self,
586 -> &VariantDefData<'tcx, 'container> {
588 &Variant(vid) => self.variant_with_id(vid),
589 _ => self.struct_variant()
594 fn missing_constructor(cx: &MatchCheckCtxt, &Matrix(ref rows): &Matrix,
595 left_ty: Ty, max_slice_length: usize) -> Option<Constructor> {
596 let used_constructors: Vec<Constructor> = rows.iter()
597 .flat_map(|row| pat_constructors(cx, row[0], left_ty, max_slice_length))
599 all_constructors(cx, left_ty, max_slice_length)
601 .find(|c| !used_constructors.contains(c))
604 /// This determines the set of all possible constructors of a pattern matching
605 /// values of type `left_ty`. For vectors, this would normally be an infinite set
606 /// but is instead bounded by the maximum fixed length of slice patterns in
607 /// the column of patterns being analyzed.
608 fn all_constructors(_cx: &MatchCheckCtxt, left_ty: Ty,
609 max_slice_length: usize) -> Vec<Constructor> {
612 [true, false].iter().map(|b| ConstantValue(ConstVal::Bool(*b))).collect(),
614 ty::TyRef(_, ty::TypeAndMut { ty, .. }) => match ty.sty {
616 range_inclusive(0, max_slice_length).map(|length| Slice(length)).collect(),
620 ty::TyEnum(def, _) => def.variants.iter().map(|v| Variant(v.did)).collect(),
625 // Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
627 // Whether a vector `v` of patterns is 'useful' in relation to a set of such
628 // vectors `m` is defined as there being a set of inputs that will match `v`
629 // but not any of the sets in `m`.
631 // This is used both for reachability checking (if a pattern isn't useful in
632 // relation to preceding patterns, it is not reachable) and exhaustiveness
633 // checking (if a wildcard pattern is useful in relation to a matrix, the
634 // matrix isn't exhaustive).
636 // Note: is_useful doesn't work on empty types, as the paper notes.
637 // So it assumes that v is non-empty.
638 fn is_useful(cx: &MatchCheckCtxt,
641 witness: WitnessPreference)
643 let &Matrix(ref rows) = matrix;
644 debug!("{:?}", matrix);
646 return match witness {
647 ConstructWitness => UsefulWithWitness(vec!()),
648 LeaveOutWitness => Useful
651 if rows[0].is_empty() {
654 assert!(rows.iter().all(|r| r.len() == v.len()));
655 let real_pat = match rows.iter().find(|r| (*r)[0].id != DUMMY_NODE_ID) {
656 Some(r) => raw_pat(r[0]),
657 None if v.is_empty() => return NotUseful,
660 let left_ty = if real_pat.id == DUMMY_NODE_ID {
663 let left_ty = cx.tcx.pat_ty(&*real_pat);
665 match real_pat.node {
666 hir::PatIdent(hir::BindByRef(..), _, _) => {
667 left_ty.builtin_deref(false).unwrap().ty
673 let max_slice_length = rows.iter().filter_map(|row| match row[0].node {
674 hir::PatVec(ref before, _, ref after) => Some(before.len() + after.len()),
676 }).max().map_or(0, |v| v + 1);
678 let constructors = pat_constructors(cx, v[0], left_ty, max_slice_length);
679 if constructors.is_empty() {
680 match missing_constructor(cx, matrix, left_ty, max_slice_length) {
682 all_constructors(cx, left_ty, max_slice_length).into_iter().map(|c| {
683 match is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness) {
684 UsefulWithWitness(pats) => UsefulWithWitness({
685 let arity = constructor_arity(cx, &c, left_ty);
687 let pat_slice = &pats[..];
688 let subpats: Vec<_> = (0..arity).map(|i| {
689 pat_slice.get(i).map_or(DUMMY_WILD_PAT, |p| &**p)
691 vec![construct_witness(cx, &c, subpats, left_ty)]
693 result.extend(pats.into_iter().skip(arity));
698 }).find(|result| result != &NotUseful).unwrap_or(NotUseful)
701 Some(constructor) => {
702 let matrix = rows.iter().filter_map(|r| {
703 if pat_is_binding_or_wild(&cx.tcx.def_map, raw_pat(r[0])) {
704 Some(r[1..].to_vec())
709 match is_useful(cx, &matrix, &v[1..], witness) {
710 UsefulWithWitness(pats) => {
711 let arity = constructor_arity(cx, &constructor, left_ty);
712 let wild_pats = vec![DUMMY_WILD_PAT; arity];
713 let enum_pat = construct_witness(cx, &constructor, wild_pats, left_ty);
714 let mut new_pats = vec![enum_pat];
715 new_pats.extend(pats);
716 UsefulWithWitness(new_pats)
723 constructors.into_iter().map(|c|
724 is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness)
725 ).find(|result| result != &NotUseful).unwrap_or(NotUseful)
729 fn is_useful_specialized(cx: &MatchCheckCtxt, &Matrix(ref m): &Matrix,
730 v: &[&Pat], ctor: Constructor, lty: Ty,
731 witness: WitnessPreference) -> Usefulness {
732 let arity = constructor_arity(cx, &ctor, lty);
733 let matrix = Matrix(m.iter().filter_map(|r| {
734 specialize(cx, &r[..], &ctor, 0, arity)
736 match specialize(cx, v, &ctor, 0, arity) {
737 Some(v) => is_useful(cx, &matrix, &v[..], witness),
742 /// Determines the constructors that the given pattern can be specialized to.
744 /// In most cases, there's only one constructor that a specific pattern
745 /// represents, such as a specific enum variant or a specific literal value.
746 /// Slice patterns, however, can match slices of different lengths. For instance,
747 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
749 /// On the other hand, a wild pattern and an identifier pattern cannot be
750 /// specialized in any way.
751 fn pat_constructors(cx: &MatchCheckCtxt, p: &Pat,
752 left_ty: Ty, max_slice_length: usize) -> Vec<Constructor> {
753 let pat = raw_pat(p);
756 match cx.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
757 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
758 cx.tcx.sess.span_bug(pat.span, "const pattern should've \
760 Some(DefStruct(_)) => vec!(Single),
761 Some(DefVariant(_, id, _)) => vec!(Variant(id)),
765 match cx.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
766 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
767 cx.tcx.sess.span_bug(pat.span, "const pattern should've \
769 Some(DefVariant(_, id, _)) => vec!(Variant(id)),
773 cx.tcx.sess.span_bug(pat.span, "const pattern should've \
775 hir::PatStruct(..) =>
776 match cx.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
777 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
778 cx.tcx.sess.span_bug(pat.span, "const pattern should've \
780 Some(DefVariant(_, id, _)) => vec!(Variant(id)),
783 hir::PatLit(ref expr) =>
784 vec!(ConstantValue(eval_const_expr(cx.tcx, &**expr))),
785 hir::PatRange(ref lo, ref hi) =>
786 vec!(ConstantRange(eval_const_expr(cx.tcx, &**lo), eval_const_expr(cx.tcx, &**hi))),
787 hir::PatVec(ref before, ref slice, ref after) =>
789 ty::TyArray(_, _) => vec!(Single),
790 _ => if slice.is_some() {
791 range_inclusive(before.len() + after.len(), max_slice_length)
792 .map(|length| Slice(length))
795 vec!(Slice(before.len() + after.len()))
798 hir::PatBox(_) | hir::PatTup(_) | hir::PatRegion(..) =>
805 /// This computes the arity of a constructor. The arity of a constructor
806 /// is how many subpattern patterns of that constructor should be expanded to.
808 /// For instance, a tuple pattern (_, 42, Some([])) has the arity of 3.
809 /// A struct pattern's arity is the number of fields it contains, etc.
810 pub fn constructor_arity(_cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> usize {
812 ty::TyTuple(ref fs) => fs.len(),
814 ty::TyRef(_, ty::TypeAndMut { ty, .. }) => match ty.sty {
815 ty::TySlice(_) => match *ctor {
816 Slice(length) => length,
817 ConstantValue(_) => 0,
823 ty::TyEnum(adt, _) | ty::TyStruct(adt, _) => {
824 adt.variant_of_ctor(ctor).fields.len()
826 ty::TyArray(_, n) => n,
831 fn range_covered_by_constructor(ctor: &Constructor,
832 from: &ConstVal, to: &ConstVal) -> Option<bool> {
833 let (c_from, c_to) = match *ctor {
834 ConstantValue(ref value) => (value, value),
835 ConstantRange(ref from, ref to) => (from, to),
836 Single => return Some(true),
839 let cmp_from = compare_const_vals(c_from, from);
840 let cmp_to = compare_const_vals(c_to, to);
841 match (cmp_from, cmp_to) {
842 (Some(cmp_from), Some(cmp_to)) => {
843 Some(cmp_from != Ordering::Less && cmp_to != Ordering::Greater)
849 /// This is the main specialization step. It expands the first pattern in the given row
850 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
851 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
853 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
854 /// different patterns.
855 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
856 /// fields filled with wild patterns.
857 pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat],
858 constructor: &Constructor, col: usize, arity: usize) -> Option<Vec<&'a Pat>> {
860 id: pat_id, ref node, span: pat_span
862 let head: Option<Vec<&Pat>> = match *node {
864 Some(vec![DUMMY_WILD_PAT; arity]),
866 hir::PatIdent(_, _, _) => {
867 let opt_def = cx.tcx.def_map.borrow().get(&pat_id).map(|d| d.full_def());
869 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
870 cx.tcx.sess.span_bug(pat_span, "const pattern should've \
872 Some(DefVariant(_, id, _)) => if *constructor == Variant(id) {
877 _ => Some(vec![DUMMY_WILD_PAT; arity])
881 hir::PatEnum(_, ref args) => {
882 let def = cx.tcx.def_map.borrow().get(&pat_id).unwrap().full_def();
884 DefConst(..) | DefAssociatedConst(..) =>
885 cx.tcx.sess.span_bug(pat_span, "const pattern should've \
887 DefVariant(_, id, _) if *constructor != Variant(id) => None,
888 DefVariant(..) | DefStruct(..) => {
890 &Some(ref args) => args.iter().map(|p| &**p).collect(),
891 &None => vec![DUMMY_WILD_PAT; arity],
898 hir::PatQPath(_, _) => {
899 cx.tcx.sess.span_bug(pat_span, "const pattern should've \
903 hir::PatStruct(_, ref pattern_fields, _) => {
904 let def = cx.tcx.def_map.borrow().get(&pat_id).unwrap().full_def();
905 let adt = cx.tcx.node_id_to_type(pat_id).ty_adt_def().unwrap();
906 let variant = adt.variant_of_ctor(constructor);
907 let def_variant = adt.variant_of_def(def);
908 if variant.did == def_variant.did {
909 Some(variant.fields.iter().map(|sf| {
910 match pattern_fields.iter().find(|f| f.node.ident.name == sf.name) {
911 Some(ref f) => &*f.node.pat,
920 hir::PatTup(ref args) =>
921 Some(args.iter().map(|p| &**p).collect()),
923 hir::PatBox(ref inner) | hir::PatRegion(ref inner, _) =>
924 Some(vec![&**inner]),
926 hir::PatLit(ref expr) => {
927 let expr_value = eval_const_expr(cx.tcx, &**expr);
928 match range_covered_by_constructor(constructor, &expr_value, &expr_value) {
929 Some(true) => Some(vec![]),
932 span_err!(cx.tcx.sess, pat_span, E0298, "mismatched types between arms");
938 hir::PatRange(ref from, ref to) => {
939 let from_value = eval_const_expr(cx.tcx, &**from);
940 let to_value = eval_const_expr(cx.tcx, &**to);
941 match range_covered_by_constructor(constructor, &from_value, &to_value) {
942 Some(true) => Some(vec![]),
945 span_err!(cx.tcx.sess, pat_span, E0299, "mismatched types between arms");
951 hir::PatVec(ref before, ref slice, ref after) => {
953 // Fixed-length vectors.
955 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
956 pats.extend(repeat(DUMMY_WILD_PAT).take(arity - before.len() - after.len()));
957 pats.extend(after.iter().map(|p| &**p));
960 Slice(length) if before.len() + after.len() <= length && slice.is_some() => {
961 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
962 pats.extend(repeat(DUMMY_WILD_PAT).take(arity - before.len() - after.len()));
963 pats.extend(after.iter().map(|p| &**p));
966 Slice(length) if before.len() + after.len() == length => {
967 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
968 pats.extend(after.iter().map(|p| &**p));
971 SliceWithSubslice(prefix, suffix)
972 if before.len() == prefix
973 && after.len() == suffix
974 && slice.is_some() => {
975 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
976 pats.extend(after.iter().map(|p| &**p));
983 head.map(|mut head| {
984 head.push_all(&r[..col]);
985 head.push_all(&r[col + 1..]);
990 fn check_local(cx: &mut MatchCheckCtxt, loc: &hir::Local) {
991 visit::walk_local(cx, loc);
993 let pat = StaticInliner::new(cx.tcx, None).fold_pat(loc.pat.clone());
994 check_irrefutable(cx, &pat, false);
996 // Check legality of move bindings and `@` patterns.
997 check_legality_of_move_bindings(cx, false, slice::ref_slice(&loc.pat));
998 check_legality_of_bindings_in_at_patterns(cx, &*loc.pat);
1001 fn check_fn(cx: &mut MatchCheckCtxt,
1008 FnKind::Closure => {}
1009 _ => cx.param_env = ParameterEnvironment::for_item(cx.tcx, fn_id),
1012 visit::walk_fn(cx, kind, decl, body, sp);
1014 for input in &decl.inputs {
1015 check_irrefutable(cx, &input.pat, true);
1016 check_legality_of_move_bindings(cx, false, slice::ref_slice(&input.pat));
1017 check_legality_of_bindings_in_at_patterns(cx, &*input.pat);
1021 fn check_irrefutable(cx: &MatchCheckCtxt, pat: &Pat, is_fn_arg: bool) {
1022 let origin = if is_fn_arg {
1028 is_refutable(cx, pat, |uncovered_pat| {
1029 span_err!(cx.tcx.sess, pat.span, E0005,
1030 "refutable pattern in {}: `{}` not covered",
1032 pat_to_string(uncovered_pat),
1037 fn is_refutable<A, F>(cx: &MatchCheckCtxt, pat: &Pat, refutable: F) -> Option<A> where
1038 F: FnOnce(&Pat) -> A,
1040 let pats = Matrix(vec!(vec!(pat)));
1041 match is_useful(cx, &pats, &[DUMMY_WILD_PAT], ConstructWitness) {
1042 UsefulWithWitness(pats) => {
1043 assert_eq!(pats.len(), 1);
1044 Some(refutable(&*pats[0]))
1047 Useful => unreachable!()
1051 // Legality of move bindings checking
1052 fn check_legality_of_move_bindings(cx: &MatchCheckCtxt,
1056 let def_map = &tcx.def_map;
1057 let mut by_ref_span = None;
1059 pat_bindings(def_map, &**pat, |bm, _, span, _path| {
1061 hir::BindByRef(_) => {
1062 by_ref_span = Some(span);
1064 hir::BindByValue(_) => {
1070 let check_move = |p: &Pat, sub: Option<&Pat>| {
1071 // check legality of moving out of the enum
1073 // x @ Foo(..) is legal, but x @ Foo(y) isn't.
1074 if sub.map_or(false, |p| pat_contains_bindings(def_map, &*p)) {
1075 span_err!(cx.tcx.sess, p.span, E0007, "cannot bind by-move with sub-bindings");
1076 } else if has_guard {
1077 span_err!(cx.tcx.sess, p.span, E0008, "cannot bind by-move into a pattern guard");
1078 } else if by_ref_span.is_some() {
1079 span_err!(cx.tcx.sess, p.span, E0009,
1080 "cannot bind by-move and by-ref in the same pattern");
1081 span_note!(cx.tcx.sess, by_ref_span.unwrap(), "by-ref binding occurs here");
1086 front_util::walk_pat(&**pat, |p| {
1087 if pat_is_binding(def_map, &*p) {
1089 hir::PatIdent(hir::BindByValue(_), _, ref sub) => {
1090 let pat_ty = tcx.node_id_to_type(p.id);
1091 //FIXME: (@jroesch) this code should be floated up as well
1092 let infcx = infer::new_infer_ctxt(cx.tcx,
1094 Some(cx.param_env.clone()),
1096 if infcx.type_moves_by_default(pat_ty, pat.span) {
1097 check_move(p, sub.as_ref().map(|p| &**p));
1100 hir::PatIdent(hir::BindByRef(_), _, _) => {
1103 cx.tcx.sess.span_bug(
1105 &format!("binding pattern {} is not an \
1117 /// Ensures that a pattern guard doesn't borrow by mutable reference or
1119 fn check_for_mutation_in_guard<'a, 'tcx>(cx: &'a MatchCheckCtxt<'a, 'tcx>,
1120 guard: &hir::Expr) {
1121 let mut checker = MutationChecker {
1125 let infcx = infer::new_infer_ctxt(cx.tcx,
1127 Some(checker.cx.param_env.clone()),
1130 let mut visitor = ExprUseVisitor::new(&mut checker, &infcx);
1131 visitor.walk_expr(guard);
1134 struct MutationChecker<'a, 'tcx: 'a> {
1135 cx: &'a MatchCheckCtxt<'a, 'tcx>,
1138 impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> {
1139 fn matched_pat(&mut self, _: &Pat, _: cmt, _: euv::MatchMode) {}
1140 fn consume(&mut self, _: NodeId, _: Span, _: cmt, _: ConsumeMode) {}
1141 fn consume_pat(&mut self, _: &Pat, _: cmt, _: ConsumeMode) {}
1142 fn borrow(&mut self,
1151 span_err!(self.cx.tcx.sess, span, E0301,
1152 "cannot mutably borrow in a pattern guard")
1154 ImmBorrow | UniqueImmBorrow => {}
1157 fn decl_without_init(&mut self, _: NodeId, _: Span) {}
1158 fn mutate(&mut self, _: NodeId, span: Span, _: cmt, mode: MutateMode) {
1160 JustWrite | WriteAndRead => {
1161 span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
1168 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
1169 /// because of the way rvalues are handled in the borrow check. (See issue
1171 fn check_legality_of_bindings_in_at_patterns(cx: &MatchCheckCtxt, pat: &Pat) {
1172 AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
1175 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
1176 cx: &'a MatchCheckCtxt<'b, 'tcx>,
1177 bindings_allowed: bool
1180 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
1181 fn visit_pat(&mut self, pat: &Pat) {
1182 if !self.bindings_allowed && pat_is_binding(&self.cx.tcx.def_map, pat) {
1183 span_err!(self.cx.tcx.sess, pat.span, E0303,
1184 "pattern bindings are not allowed \
1189 hir::PatIdent(_, _, Some(_)) => {
1190 let bindings_were_allowed = self.bindings_allowed;
1191 self.bindings_allowed = false;
1192 visit::walk_pat(self, pat);
1193 self.bindings_allowed = bindings_were_allowed;
1195 _ => visit::walk_pat(self, pat),