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(edef, _) = 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 edef.variants.iter().any(|variant|
241 variant.name == ident.node.name
242 && variant.kind() == VariantKind::Unit
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<'a,'tcx>(cx: &MatchCheckCtxt<'a,'tcx>, ctor: &Constructor,
505 pats: Vec<&Pat>, left_ty: Ty<'tcx>) -> 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(adt, _) | ty::TyStruct(adt, _) => {
512 let v = adt.variant_of_ctor(ctor);
513 if let VariantKind::Dict = v.kind() {
514 let field_pats: Vec<_> = v.fields.iter()
516 .filter(|&(_, ref pat)| pat.node != ast::PatWild(ast::PatWildSingle))
517 .map(|(field, pat)| Spanned {
519 node: ast::FieldPat {
520 ident: ast::Ident::new(field.name),
525 let has_more_fields = field_pats.len() < pats_len;
526 ast::PatStruct(def_to_path(cx.tcx, v.did), field_pats, has_more_fields)
528 ast::PatEnum(def_to_path(cx.tcx, v.did), Some(pats.collect()))
532 ty::TyRef(_, ty::TypeAndMut { ty, mutbl }) => {
534 ty::TyArray(_, n) => match ctor {
536 assert_eq!(pats_len, n);
537 ast::PatVec(pats.collect(), None, vec!())
541 ty::TySlice(_) => match ctor {
543 assert_eq!(pats_len, n);
544 ast::PatVec(pats.collect(), None, vec!())
548 ty::TyStr => ast::PatWild(ast::PatWildSingle),
551 assert_eq!(pats_len, 1);
552 ast::PatRegion(pats.nth(0).unwrap(), mutbl)
557 ty::TyArray(_, len) => {
558 assert_eq!(pats_len, len);
559 ast::PatVec(pats.collect(), None, vec![])
564 ConstantValue(ref v) => ast::PatLit(const_val_to_expr(v)),
565 _ => ast::PatWild(ast::PatWildSingle),
577 impl<'tcx> ADTDef<'tcx> {
578 fn variant_of_ctor(&'tcx self, ctor: &Constructor) -> &'tcx VariantDef<'tcx> {
580 &Variant(vid) => self.variant_with_id(vid),
581 _ => self.struct_variant()
586 fn missing_constructor(cx: &MatchCheckCtxt, &Matrix(ref rows): &Matrix,
587 left_ty: Ty, max_slice_length: usize) -> Option<Constructor> {
588 let used_constructors: Vec<Constructor> = rows.iter()
589 .flat_map(|row| pat_constructors(cx, row[0], left_ty, max_slice_length))
591 all_constructors(cx, left_ty, max_slice_length)
593 .find(|c| !used_constructors.contains(c))
596 /// This determines the set of all possible constructors of a pattern matching
597 /// values of type `left_ty`. For vectors, this would normally be an infinite set
598 /// but is instead bounded by the maximum fixed length of slice patterns in
599 /// the column of patterns being analyzed.
600 fn all_constructors(_cx: &MatchCheckCtxt, left_ty: Ty,
601 max_slice_length: usize) -> Vec<Constructor> {
604 [true, false].iter().map(|b| ConstantValue(ConstVal::Bool(*b))).collect(),
606 ty::TyRef(_, ty::TypeAndMut { ty, .. }) => match ty.sty {
608 range_inclusive(0, max_slice_length).map(|length| Slice(length)).collect(),
612 ty::TyEnum(def, _) => def.variants.iter().map(|v| Variant(v.did)).collect(),
617 // Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
619 // Whether a vector `v` of patterns is 'useful' in relation to a set of such
620 // vectors `m` is defined as there being a set of inputs that will match `v`
621 // but not any of the sets in `m`.
623 // This is used both for reachability checking (if a pattern isn't useful in
624 // relation to preceding patterns, it is not reachable) and exhaustiveness
625 // checking (if a wildcard pattern is useful in relation to a matrix, the
626 // matrix isn't exhaustive).
628 // Note: is_useful doesn't work on empty types, as the paper notes.
629 // So it assumes that v is non-empty.
630 fn is_useful(cx: &MatchCheckCtxt,
633 witness: WitnessPreference)
635 let &Matrix(ref rows) = matrix;
636 debug!("{:?}", matrix);
638 return match witness {
639 ConstructWitness => UsefulWithWitness(vec!()),
640 LeaveOutWitness => Useful
643 if rows[0].is_empty() {
646 assert!(rows.iter().all(|r| r.len() == v.len()));
647 let real_pat = match rows.iter().find(|r| (*r)[0].id != DUMMY_NODE_ID) {
648 Some(r) => raw_pat(r[0]),
649 None if v.is_empty() => return NotUseful,
652 let left_ty = if real_pat.id == DUMMY_NODE_ID {
655 let left_ty = cx.tcx.pat_ty(&*real_pat);
657 match real_pat.node {
658 ast::PatIdent(ast::BindByRef(..), _, _) => {
659 left_ty.builtin_deref(false).unwrap().ty
665 let max_slice_length = rows.iter().filter_map(|row| match row[0].node {
666 ast::PatVec(ref before, _, ref after) => Some(before.len() + after.len()),
668 }).max().map_or(0, |v| v + 1);
670 let constructors = pat_constructors(cx, v[0], left_ty, max_slice_length);
671 if constructors.is_empty() {
672 match missing_constructor(cx, matrix, left_ty, max_slice_length) {
674 all_constructors(cx, left_ty, max_slice_length).into_iter().map(|c| {
675 match is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness) {
676 UsefulWithWitness(pats) => UsefulWithWitness({
677 let arity = constructor_arity(cx, &c, left_ty);
679 let pat_slice = &pats[..];
680 let subpats: Vec<_> = (0..arity).map(|i| {
681 pat_slice.get(i).map_or(DUMMY_WILD_PAT, |p| &**p)
683 vec![construct_witness(cx, &c, subpats, left_ty)]
685 result.extend(pats.into_iter().skip(arity));
690 }).find(|result| result != &NotUseful).unwrap_or(NotUseful)
693 Some(constructor) => {
694 let matrix = rows.iter().filter_map(|r| {
695 if pat_is_binding_or_wild(&cx.tcx.def_map, raw_pat(r[0])) {
696 Some(r[1..].to_vec())
701 match is_useful(cx, &matrix, &v[1..], witness) {
702 UsefulWithWitness(pats) => {
703 let arity = constructor_arity(cx, &constructor, left_ty);
704 let wild_pats = vec![DUMMY_WILD_PAT; arity];
705 let enum_pat = construct_witness(cx, &constructor, wild_pats, left_ty);
706 let mut new_pats = vec![enum_pat];
707 new_pats.extend(pats);
708 UsefulWithWitness(new_pats)
715 constructors.into_iter().map(|c|
716 is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness)
717 ).find(|result| result != &NotUseful).unwrap_or(NotUseful)
721 fn is_useful_specialized(cx: &MatchCheckCtxt, &Matrix(ref m): &Matrix,
722 v: &[&Pat], ctor: Constructor, lty: Ty,
723 witness: WitnessPreference) -> Usefulness {
724 let arity = constructor_arity(cx, &ctor, lty);
725 let matrix = Matrix(m.iter().filter_map(|r| {
726 specialize(cx, &r[..], &ctor, 0, arity)
728 match specialize(cx, v, &ctor, 0, arity) {
729 Some(v) => is_useful(cx, &matrix, &v[..], witness),
734 /// Determines the constructors that the given pattern can be specialized to.
736 /// In most cases, there's only one constructor that a specific pattern
737 /// represents, such as a specific enum variant or a specific literal value.
738 /// Slice patterns, however, can match slices of different lengths. For instance,
739 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
741 /// On the other hand, a wild pattern and an identifier pattern cannot be
742 /// specialized in any way.
743 fn pat_constructors(cx: &MatchCheckCtxt, p: &Pat,
744 left_ty: Ty, max_slice_length: usize) -> Vec<Constructor> {
745 let pat = raw_pat(p);
748 match cx.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
749 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
750 cx.tcx.sess.span_bug(pat.span, "const pattern should've \
752 Some(DefStruct(_)) => vec!(Single),
753 Some(DefVariant(_, id, _)) => vec!(Variant(id)),
757 match cx.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
758 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
759 cx.tcx.sess.span_bug(pat.span, "const pattern should've \
761 Some(DefVariant(_, id, _)) => vec!(Variant(id)),
765 cx.tcx.sess.span_bug(pat.span, "const pattern should've \
767 ast::PatStruct(..) =>
768 match cx.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
769 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
770 cx.tcx.sess.span_bug(pat.span, "const pattern should've \
772 Some(DefVariant(_, id, _)) => vec!(Variant(id)),
775 ast::PatLit(ref expr) =>
776 vec!(ConstantValue(eval_const_expr(cx.tcx, &**expr))),
777 ast::PatRange(ref lo, ref hi) =>
778 vec!(ConstantRange(eval_const_expr(cx.tcx, &**lo), eval_const_expr(cx.tcx, &**hi))),
779 ast::PatVec(ref before, ref slice, ref after) =>
781 ty::TyArray(_, _) => vec!(Single),
782 _ => if slice.is_some() {
783 range_inclusive(before.len() + after.len(), max_slice_length)
784 .map(|length| Slice(length))
787 vec!(Slice(before.len() + after.len()))
790 ast::PatBox(_) | ast::PatTup(_) | ast::PatRegion(..) =>
795 cx.tcx.sess.bug("unexpanded macro")
799 /// This computes the arity of a constructor. The arity of a constructor
800 /// is how many subpattern patterns of that constructor should be expanded to.
802 /// For instance, a tuple pattern (_, 42, Some([])) has the arity of 3.
803 /// A struct pattern's arity is the number of fields it contains, etc.
804 pub fn constructor_arity(_cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> usize {
806 ty::TyTuple(ref fs) => fs.len(),
808 ty::TyRef(_, ty::TypeAndMut { ty, .. }) => match ty.sty {
809 ty::TySlice(_) => match *ctor {
810 Slice(length) => length,
811 ConstantValue(_) => 0,
817 ty::TyEnum(adt, _) | ty::TyStruct(adt, _) => {
818 adt.variant_of_ctor(ctor).fields.len()
820 ty::TyArray(_, n) => n,
825 fn range_covered_by_constructor(ctor: &Constructor,
826 from: &ConstVal, to: &ConstVal) -> Option<bool> {
827 let (c_from, c_to) = match *ctor {
828 ConstantValue(ref value) => (value, value),
829 ConstantRange(ref from, ref to) => (from, to),
830 Single => return Some(true),
833 let cmp_from = compare_const_vals(c_from, from);
834 let cmp_to = compare_const_vals(c_to, to);
835 match (cmp_from, cmp_to) {
836 (Some(cmp_from), Some(cmp_to)) => {
837 Some(cmp_from != Ordering::Less && cmp_to != Ordering::Greater)
843 /// This is the main specialization step. It expands the first pattern in the given row
844 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
845 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
847 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
848 /// different patterns.
849 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
850 /// fields filled with wild patterns.
851 pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat],
852 constructor: &Constructor, col: usize, arity: usize) -> Option<Vec<&'a Pat>> {
854 id: pat_id, ref node, span: pat_span
856 let head: Option<Vec<&Pat>> = match *node {
858 Some(vec![DUMMY_WILD_PAT; arity]),
860 ast::PatIdent(_, _, _) => {
861 let opt_def = cx.tcx.def_map.borrow().get(&pat_id).map(|d| d.full_def());
863 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
864 cx.tcx.sess.span_bug(pat_span, "const pattern should've \
866 Some(DefVariant(_, id, _)) => if *constructor == Variant(id) {
871 _ => Some(vec![DUMMY_WILD_PAT; arity])
875 ast::PatEnum(_, ref args) => {
876 let def = cx.tcx.def_map.borrow().get(&pat_id).unwrap().full_def();
878 DefConst(..) | DefAssociatedConst(..) =>
879 cx.tcx.sess.span_bug(pat_span, "const pattern should've \
881 DefVariant(_, id, _) if *constructor != Variant(id) => None,
882 DefVariant(..) | DefStruct(..) => {
884 &Some(ref args) => args.iter().map(|p| &**p).collect(),
885 &None => vec![DUMMY_WILD_PAT; arity],
892 ast::PatQPath(_, _) => {
893 cx.tcx.sess.span_bug(pat_span, "const pattern should've \
897 ast::PatStruct(_, ref pattern_fields, _) => {
898 let def = cx.tcx.def_map.borrow().get(&pat_id).unwrap().full_def();
899 let adt = cx.tcx.node_id_to_type(pat_id).ty_adt_def().unwrap();
900 let variant = adt.variant_of_ctor(constructor);
901 let def_variant = adt.variant_of_def(def);
902 if variant.did == def_variant.did {
903 Some(variant.fields.iter().map(|sf| {
904 match pattern_fields.iter().find(|f| f.node.ident.name == sf.name) {
905 Some(ref f) => &*f.node.pat,
914 ast::PatTup(ref args) =>
915 Some(args.iter().map(|p| &**p).collect()),
917 ast::PatBox(ref inner) | ast::PatRegion(ref inner, _) =>
918 Some(vec![&**inner]),
920 ast::PatLit(ref expr) => {
921 let expr_value = eval_const_expr(cx.tcx, &**expr);
922 match range_covered_by_constructor(constructor, &expr_value, &expr_value) {
923 Some(true) => Some(vec![]),
926 span_err!(cx.tcx.sess, pat_span, E0298, "mismatched types between arms");
932 ast::PatRange(ref from, ref to) => {
933 let from_value = eval_const_expr(cx.tcx, &**from);
934 let to_value = eval_const_expr(cx.tcx, &**to);
935 match range_covered_by_constructor(constructor, &from_value, &to_value) {
936 Some(true) => Some(vec![]),
939 span_err!(cx.tcx.sess, pat_span, E0299, "mismatched types between arms");
945 ast::PatVec(ref before, ref slice, ref after) => {
947 // Fixed-length vectors.
949 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
950 pats.extend(repeat(DUMMY_WILD_PAT).take(arity - before.len() - after.len()));
951 pats.extend(after.iter().map(|p| &**p));
954 Slice(length) if before.len() + after.len() <= length && slice.is_some() => {
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 => {
961 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
962 pats.extend(after.iter().map(|p| &**p));
965 SliceWithSubslice(prefix, suffix)
966 if before.len() == prefix
967 && after.len() == suffix
968 && slice.is_some() => {
969 let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
970 pats.extend(after.iter().map(|p| &**p));
978 span_err!(cx.tcx.sess, pat_span, E0300, "unexpanded macro");
982 head.map(|mut head| {
983 head.push_all(&r[..col]);
984 head.push_all(&r[col + 1..]);
989 fn check_local(cx: &mut MatchCheckCtxt, loc: &ast::Local) {
990 visit::walk_local(cx, loc);
992 let pat = StaticInliner::new(cx.tcx, None).fold_pat(loc.pat.clone());
993 check_irrefutable(cx, &pat, false);
995 // Check legality of move bindings and `@` patterns.
996 check_legality_of_move_bindings(cx, false, slice::ref_slice(&loc.pat));
997 check_legality_of_bindings_in_at_patterns(cx, &*loc.pat);
1000 fn check_fn(cx: &mut MatchCheckCtxt,
1007 visit::FkFnBlock => {}
1008 _ => cx.param_env = ParameterEnvironment::for_item(cx.tcx, fn_id),
1011 visit::walk_fn(cx, kind, decl, body, sp);
1013 for input in &decl.inputs {
1014 check_irrefutable(cx, &input.pat, true);
1015 check_legality_of_move_bindings(cx, false, slice::ref_slice(&input.pat));
1016 check_legality_of_bindings_in_at_patterns(cx, &*input.pat);
1020 fn check_irrefutable(cx: &MatchCheckCtxt, pat: &Pat, is_fn_arg: bool) {
1021 let origin = if is_fn_arg {
1027 is_refutable(cx, pat, |uncovered_pat| {
1028 span_err!(cx.tcx.sess, pat.span, E0005,
1029 "refutable pattern in {}: `{}` not covered",
1031 pat_to_string(uncovered_pat),
1036 fn is_refutable<A, F>(cx: &MatchCheckCtxt, pat: &Pat, refutable: F) -> Option<A> where
1037 F: FnOnce(&Pat) -> A,
1039 let pats = Matrix(vec!(vec!(pat)));
1040 match is_useful(cx, &pats, &[DUMMY_WILD_PAT], ConstructWitness) {
1041 UsefulWithWitness(pats) => {
1042 assert_eq!(pats.len(), 1);
1043 Some(refutable(&*pats[0]))
1046 Useful => unreachable!()
1050 // Legality of move bindings checking
1051 fn check_legality_of_move_bindings(cx: &MatchCheckCtxt,
1055 let def_map = &tcx.def_map;
1056 let mut by_ref_span = None;
1058 pat_bindings(def_map, &**pat, |bm, _, span, _path| {
1060 ast::BindByRef(_) => {
1061 by_ref_span = Some(span);
1063 ast::BindByValue(_) => {
1069 let check_move = |p: &Pat, sub: Option<&Pat>| {
1070 // check legality of moving out of the enum
1072 // x @ Foo(..) is legal, but x @ Foo(y) isn't.
1073 if sub.map_or(false, |p| pat_contains_bindings(def_map, &*p)) {
1074 span_err!(cx.tcx.sess, p.span, E0007, "cannot bind by-move with sub-bindings");
1075 } else if has_guard {
1076 span_err!(cx.tcx.sess, p.span, E0008, "cannot bind by-move into a pattern guard");
1077 } else if by_ref_span.is_some() {
1078 span_err!(cx.tcx.sess, p.span, E0009,
1079 "cannot bind by-move and by-ref in the same pattern");
1080 span_note!(cx.tcx.sess, by_ref_span.unwrap(), "by-ref binding occurs here");
1085 ast_util::walk_pat(&**pat, |p| {
1086 if pat_is_binding(def_map, &*p) {
1088 ast::PatIdent(ast::BindByValue(_), _, ref sub) => {
1089 let pat_ty = tcx.node_id_to_type(p.id);
1090 //FIXME: (@jroesch) this code should be floated up as well
1091 let infcx = infer::new_infer_ctxt(cx.tcx,
1093 Some(cx.param_env.clone()),
1095 if infcx.type_moves_by_default(pat_ty, pat.span) {
1096 check_move(p, sub.as_ref().map(|p| &**p));
1099 ast::PatIdent(ast::BindByRef(_), _, _) => {
1102 cx.tcx.sess.span_bug(
1104 &format!("binding pattern {} is not an \
1116 /// Ensures that a pattern guard doesn't borrow by mutable reference or
1118 fn check_for_mutation_in_guard<'a, 'tcx>(cx: &'a MatchCheckCtxt<'a, 'tcx>,
1119 guard: &ast::Expr) {
1120 let mut checker = MutationChecker {
1124 let infcx = infer::new_infer_ctxt(cx.tcx,
1126 Some(checker.cx.param_env.clone()),
1129 let mut visitor = ExprUseVisitor::new(&mut checker, &infcx);
1130 visitor.walk_expr(guard);
1133 struct MutationChecker<'a, 'tcx: 'a> {
1134 cx: &'a MatchCheckCtxt<'a, 'tcx>,
1137 impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> {
1138 fn matched_pat(&mut self, _: &Pat, _: cmt, _: euv::MatchMode) {}
1139 fn consume(&mut self, _: NodeId, _: Span, _: cmt, _: ConsumeMode) {}
1140 fn consume_pat(&mut self, _: &Pat, _: cmt, _: ConsumeMode) {}
1141 fn borrow(&mut self,
1150 span_err!(self.cx.tcx.sess, span, E0301,
1151 "cannot mutably borrow in a pattern guard")
1153 ImmBorrow | UniqueImmBorrow => {}
1156 fn decl_without_init(&mut self, _: NodeId, _: Span) {}
1157 fn mutate(&mut self, _: NodeId, span: Span, _: cmt, mode: MutateMode) {
1159 JustWrite | WriteAndRead => {
1160 span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
1167 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
1168 /// because of the way rvalues are handled in the borrow check. (See issue
1170 fn check_legality_of_bindings_in_at_patterns(cx: &MatchCheckCtxt, pat: &Pat) {
1171 AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
1174 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
1175 cx: &'a MatchCheckCtxt<'b, 'tcx>,
1176 bindings_allowed: bool
1179 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
1180 fn visit_pat(&mut self, pat: &Pat) {
1181 if !self.bindings_allowed && pat_is_binding(&self.cx.tcx.def_map, pat) {
1182 span_err!(self.cx.tcx.sess, pat.span, E0303,
1183 "pattern bindings are not allowed \
1188 ast::PatIdent(_, _, Some(_)) => {
1189 let bindings_were_allowed = self.bindings_allowed;
1190 self.bindings_allowed = false;
1191 visit::walk_pat(self, pat);
1192 self.bindings_allowed = bindings_were_allowed;
1194 _ => visit::walk_pat(self, pat),