]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/check_match.rs
Refined error message to truncate at 3 and hint at number of hidden patterns for...
[rust.git] / src / librustc / middle / check_match.rs
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.
4 //
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.
10
11 pub use self::Constructor::*;
12 use self::Usefulness::*;
13 use self::WitnessPreference::*;
14
15 use dep_graph::DepNode;
16 use middle::const_eval::{compare_const_vals, ConstVal};
17 use middle::const_eval::{eval_const_expr, eval_const_expr_partial};
18 use middle::const_eval::{const_expr_to_pat, lookup_const_by_id};
19 use middle::const_eval::EvalHint::ExprTypeChecked;
20 use middle::def::*;
21 use middle::def_id::{DefId};
22 use middle::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor};
23 use middle::expr_use_visitor::{LoanCause, MutateMode};
24 use middle::expr_use_visitor as euv;
25 use middle::infer;
26 use middle::mem_categorization::{cmt};
27 use middle::pat_util::*;
28 use middle::ty::*;
29 use middle::ty;
30 use std::cmp::Ordering;
31 use std::fmt;
32 use std::iter::{FromIterator, IntoIterator, repeat};
33
34 use rustc_front::hir;
35 use rustc_front::hir::Pat;
36 use rustc_front::intravisit::{self, Visitor, FnKind};
37 use rustc_front::util as front_util;
38 use rustc_back::slice;
39
40 use syntax::ast::{self, DUMMY_NODE_ID, NodeId};
41 use syntax::ast_util;
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;
45 use syntax::ptr::P;
46 use util::nodemap::FnvHashMap;
47
48 pub const DUMMY_WILD_PAT: &'static Pat = &Pat {
49     id: DUMMY_NODE_ID,
50     node: hir::PatWild,
51     span: DUMMY_SP
52 };
53
54 struct Matrix<'a>(Vec<Vec<&'a Pat>>);
55
56 /// Pretty-printer for matrices of patterns, example:
57 /// ++++++++++++++++++++++++++
58 /// + _     + []             +
59 /// ++++++++++++++++++++++++++
60 /// + true  + [First]        +
61 /// ++++++++++++++++++++++++++
62 /// + true  + [Second(true)] +
63 /// ++++++++++++++++++++++++++
64 /// + false + [_]            +
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"));
71
72         let &Matrix(ref m) = self;
73         let pretty_printed_matrix: Vec<Vec<String>> = m.iter().map(|row| {
74             row.iter()
75                .map(|&pat| pat_to_string(&*pat))
76                .collect::<Vec<String>>()
77         }).collect();
78
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)
83         }).collect();
84
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 {
89             try!(write!(f, "+"));
90             for (column, pat_str) in row.into_iter().enumerate() {
91                 try!(write!(f, " "));
92                 try!(write!(f, "{:1$}", pat_str, column_widths[column]));
93                 try!(write!(f, " +"));
94             }
95             try!(write!(f, "\n"));
96             try!(write!(f, "{}\n", br));
97         }
98         Ok(())
99     }
100 }
101
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())
105     }
106 }
107
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>,
112 }
113
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.
118     Single,
119     /// Enum variants.
120     Variant(DefId),
121     /// Literal values.
122     ConstantValue(ConstVal),
123     /// Ranges of literal values (2..5).
124     ConstantRange(ConstVal, ConstVal),
125     /// Array patterns of length n.
126     Slice(usize),
127     /// Array patterns with a subslice.
128     SliceWithSubslice(usize, usize)
129 }
130
131 #[derive(Clone, PartialEq)]
132 enum Usefulness {
133     Useful,
134     UsefulWithWitness(Vec<P<Pat>>),
135     NotUseful
136 }
137
138 #[derive(Copy, Clone)]
139 enum WitnessPreference {
140     ConstructWitness,
141     LeaveOutWitness
142 }
143
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);
147     }
148     fn visit_local(&mut self, l: &hir::Local) {
149         check_local(self, l);
150     }
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);
154     }
155 }
156
157 pub fn check_crate(tcx: &ty::ctxt) {
158     tcx.visit_all_items_in_krate(DepNode::MatchCheck, &mut MatchCheckCtxt {
159         tcx: tcx,
160         param_env: tcx.empty_parameter_environment(),
161     });
162     tcx.sess.abort_if_errors();
163 }
164
165 fn check_expr(cx: &mut MatchCheckCtxt, ex: &hir::Expr) {
166     intravisit::walk_expr(cx, ex);
167     match ex.node {
168         hir::ExprMatch(ref scrut, ref arms, source) => {
169             for arm in arms {
170                 // First, check legality of move bindings.
171                 check_legality_of_move_bindings(cx,
172                                                 arm.guard.is_some(),
173                                                 &arm.pats);
174
175                 // Second, if there is a guard on each arm, make sure it isn't
176                 // assigning or borrowing anything mutably.
177                 match arm.guard {
178                     Some(ref guard) => check_for_mutation_in_guard(cx, &**guard),
179                     None => {}
180                 }
181             }
182
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>)>>();
189
190             // Bail out early if inlining failed.
191             if static_inliner.failed {
192                 return;
193             }
194
195             for pat in inlined_arms
196                 .iter()
197                 .flat_map(|&(ref pats, _)| pats) {
198                 // Third, check legality of move bindings.
199                 check_legality_of_bindings_in_at_patterns(cx, &**pat);
200
201                 // Fourth, check if there are any references to NaN that we should warn about.
202                 check_for_static_nan(cx, &**pat);
203
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);
207             }
208
209             // Fourth, check for unreachable arms.
210             check_arms(cx, &inlined_arms[..], source);
211
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                     let mut err = struct_span_err!(cx.tcx.sess, ex.span, E0002,
219                                                    "non-exhaustive patterns: type {} is non-empty",
220                                                    pat_ty);
221                     span_help!(&mut err, ex.span,
222                         "Please ensure that all possible cases are being handled; \
223                          possibly adding wildcards or more match arms.");
224                     err.emit();
225                 }
226                 // If the type *is* empty, it's vacuously exhaustive
227                 return;
228             }
229
230             let matrix: Matrix = inlined_arms
231                 .iter()
232                 .filter(|&&(_, guard)| guard.is_none())
233                 .flat_map(|arm| &arm.0)
234                 .map(|pat| vec![&**pat])
235                 .collect();
236             check_exhaustive(cx, ex.span, &matrix, source);
237         },
238         _ => ()
239     }
240 }
241
242 fn check_for_bindings_named_the_same_as_variants(cx: &MatchCheckCtxt, pat: &Pat) {
243     front_util::walk_pat(pat, |p| {
244         match p.node {
245             hir::PatIdent(hir::BindByValue(hir::MutImmutable), ident, None) => {
246                 let pat_ty = cx.tcx.pat_ty(p);
247                 if let ty::TyEnum(edef, _) = pat_ty.sty {
248                     let def = cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def());
249                     if let Some(DefLocal(..)) = def {
250                         if edef.variants.iter().any(|variant|
251                             variant.name == ident.node.unhygienic_name
252                                 && variant.kind() == VariantKind::Unit
253                         ) {
254                             let ty_path = cx.tcx.item_path_str(edef.did);
255                             let mut err = struct_span_warn!(cx.tcx.sess, p.span, E0170,
256                                 "pattern binding `{}` is named the same as one \
257                                  of the variants of the type `{}`",
258                                 ident.node, ty_path);
259                             fileline_help!(err, p.span,
260                                 "if you meant to match on a variant, \
261                                  consider making the path in the pattern qualified: `{}::{}`",
262                                 ty_path, ident.node);
263                             err.emit();
264                         }
265                     }
266                 }
267             }
268             _ => ()
269         }
270         true
271     });
272 }
273
274 // Check that we do not match against a static NaN (#6804)
275 fn check_for_static_nan(cx: &MatchCheckCtxt, pat: &Pat) {
276     front_util::walk_pat(pat, |p| {
277         if let hir::PatLit(ref expr) = p.node {
278             match eval_const_expr_partial(cx.tcx, &**expr, ExprTypeChecked, None) {
279                 Ok(ConstVal::Float(f)) if f.is_nan() => {
280                     span_warn!(cx.tcx.sess, p.span, E0003,
281                                "unmatchable NaN in pattern, \
282                                 use the is_nan method in a guard instead");
283                 }
284                 Ok(_) => {}
285
286                 Err(err) => {
287                     let mut diag = struct_span_err!(cx.tcx.sess, err.span, E0471,
288                                                     "constant evaluation error: {}",
289                                                     err.description());
290                     if !p.span.contains(err.span) {
291                         diag.span_note(p.span, "in pattern here");
292                     }
293                     diag.emit();
294                 }
295             }
296         }
297         true
298     });
299 }
300
301 // Check for unreachable patterns
302 fn check_arms(cx: &MatchCheckCtxt,
303               arms: &[(Vec<P<Pat>>, Option<&hir::Expr>)],
304               source: hir::MatchSource) {
305     let mut seen = Matrix(vec![]);
306     let mut printed_if_let_err = false;
307     for &(ref pats, guard) in arms {
308         for pat in pats {
309             let v = vec![&**pat];
310
311             match is_useful(cx, &seen, &v[..], LeaveOutWitness) {
312                 NotUseful => {
313                     match source {
314                         hir::MatchSource::IfLetDesugar { .. } => {
315                             if printed_if_let_err {
316                                 // we already printed an irrefutable if-let pattern error.
317                                 // We don't want two, that's just confusing.
318                             } else {
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, E0162, "irrefutable if-let pattern");
324                                 printed_if_let_err = true;
325                             }
326                         },
327
328                         hir::MatchSource::WhileLetDesugar => {
329                             // find the first arm pattern so we can use its span
330                             let &(ref first_arm_pats, _) = &arms[0];
331                             let first_pat = &first_arm_pats[0];
332                             let span = first_pat.span;
333                             span_err!(cx.tcx.sess, span, E0165, "irrefutable while-let pattern");
334                         },
335
336                         hir::MatchSource::ForLoopDesugar => {
337                             // this is a bug, because on `match iter.next()` we cover
338                             // `Some(<head>)` and `None`. It's impossible to have an unreachable
339                             // pattern
340                             // (see libsyntax/ext/expand.rs for the full expansion of a for loop)
341                             cx.tcx.sess.span_bug(pat.span, "unreachable for-loop pattern")
342                         },
343
344                         hir::MatchSource::Normal => {
345                             span_err!(cx.tcx.sess, pat.span, E0001, "unreachable pattern")
346                         },
347                     }
348                 }
349                 Useful => (),
350                 UsefulWithWitness(_) => unreachable!()
351             }
352             if guard.is_none() {
353                 let Matrix(mut rows) = seen;
354                 rows.push(v);
355                 seen = Matrix(rows);
356             }
357         }
358     }
359 }
360
361 fn raw_pat<'a>(p: &'a Pat) -> &'a Pat {
362     match p.node {
363         hir::PatIdent(_, _, Some(ref s)) => raw_pat(&**s),
364         _ => p
365     }
366 }
367
368 fn check_exhaustive(cx: &MatchCheckCtxt, sp: Span, matrix: &Matrix, source: hir::MatchSource) {
369     match is_useful(cx, matrix, &[DUMMY_WILD_PAT], ConstructWitness) {
370         UsefulWithWitness(pats) => {
371             let witnesses = if pats.is_empty() {
372                 vec![DUMMY_WILD_PAT]
373             } else {
374                 pats.iter().map(|w| &**w ).collect()
375             };
376             match source {
377                 hir::MatchSource::ForLoopDesugar => {
378                     // `witnesses[0]` has the form `Some(<head>)`, peel off the `Some`
379                     let witness = match witnesses[0].node {
380                         hir::PatEnum(_, Some(ref pats)) => match &pats[..] {
381                             [ref pat] => &**pat,
382                             _ => unreachable!(),
383                         },
384                         _ => unreachable!(),
385                     };
386                     span_err!(cx.tcx.sess, sp, E0297,
387                         "refutable pattern in `for` loop binding: \
388                                 `{}` not covered",
389                                 pat_to_string(witness));
390                 },
391                 _ => {
392                     let pattern_strings: Vec<_> = witnesses.iter().map(|w| {
393                         pat_to_string(w)
394                     }).collect();
395                     const LIMIT: usize = 3;
396                     let joined_patterns = match pattern_strings.len() {
397                         0 => unreachable!(),
398                         1 => format!("`{}`", pattern_strings[0]),
399                         2...LIMIT => {
400                             let (tail, head) = pattern_strings.split_last().unwrap();
401                             format!("`{}`", head.join("`, `") + "` and `" + tail)
402                         },
403                         _ => {
404                             let (head, tail) = pattern_strings.split_at(LIMIT);
405                             format!("`{}` and {} more", head.join("`, `"), tail.len())
406                         }
407                     };
408                     span_err!(cx.tcx.sess, sp, E0004,
409                         "non-exhaustive patterns: {} not covered",
410                         joined_patterns
411                     );
412                 },
413             }
414         }
415         NotUseful => {
416             // This is good, wildcard pattern isn't reachable
417         },
418         _ => unreachable!()
419     }
420 }
421
422 fn const_val_to_expr(value: &ConstVal) -> P<hir::Expr> {
423     let node = match value {
424         &ConstVal::Bool(b) => ast::LitBool(b),
425         _ => unreachable!()
426     };
427     P(hir::Expr {
428         id: 0,
429         node: hir::ExprLit(P(Spanned { node: node, span: DUMMY_SP })),
430         span: DUMMY_SP,
431         attrs: None,
432     })
433 }
434
435 pub struct StaticInliner<'a, 'tcx: 'a> {
436     pub tcx: &'a ty::ctxt<'tcx>,
437     pub failed: bool,
438     pub renaming_map: Option<&'a mut FnvHashMap<(NodeId, Span), NodeId>>,
439 }
440
441 impl<'a, 'tcx> StaticInliner<'a, 'tcx> {
442     pub fn new<'b>(tcx: &'b ty::ctxt<'tcx>,
443                    renaming_map: Option<&'b mut FnvHashMap<(NodeId, Span), NodeId>>)
444                    -> StaticInliner<'b, 'tcx> {
445         StaticInliner {
446             tcx: tcx,
447             failed: false,
448             renaming_map: renaming_map
449         }
450     }
451 }
452
453 struct RenamingRecorder<'map> {
454     substituted_node_id: NodeId,
455     origin_span: Span,
456     renaming_map: &'map mut FnvHashMap<(NodeId, Span), NodeId>
457 }
458
459 impl<'map> ast_util::IdVisitingOperation for RenamingRecorder<'map> {
460     fn visit_id(&mut self, node_id: NodeId) {
461         let key = (node_id, self.origin_span);
462         self.renaming_map.insert(key, self.substituted_node_id);
463     }
464 }
465
466 impl<'a, 'tcx> Folder for StaticInliner<'a, 'tcx> {
467     fn fold_pat(&mut self, pat: P<Pat>) -> P<Pat> {
468         return match pat.node {
469             hir::PatIdent(..) | hir::PatEnum(..) | hir::PatQPath(..) => {
470                 let def = self.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def());
471                 match def {
472                     Some(DefAssociatedConst(did)) |
473                     Some(DefConst(did)) => match lookup_const_by_id(self.tcx, did,
474                                                                     Some(pat.id), None) {
475                         Some(const_expr) => {
476                             const_expr_to_pat(self.tcx, const_expr, pat.span).map(|new_pat| {
477
478                                 if let Some(ref mut renaming_map) = self.renaming_map {
479                                     // Record any renamings we do here
480                                     record_renamings(const_expr, &pat, renaming_map);
481                                 }
482
483                                 new_pat
484                             })
485                         }
486                         None => {
487                             self.failed = true;
488                             span_err!(self.tcx.sess, pat.span, E0158,
489                                 "statics cannot be referenced in patterns");
490                             pat
491                         }
492                     },
493                     _ => noop_fold_pat(pat, self)
494                 }
495             }
496             _ => noop_fold_pat(pat, self)
497         };
498
499         fn record_renamings(const_expr: &hir::Expr,
500                             substituted_pat: &hir::Pat,
501                             renaming_map: &mut FnvHashMap<(NodeId, Span), NodeId>) {
502             let mut renaming_recorder = RenamingRecorder {
503                 substituted_node_id: substituted_pat.id,
504                 origin_span: substituted_pat.span,
505                 renaming_map: renaming_map,
506             };
507
508             let mut id_visitor = front_util::IdVisitor::new(&mut renaming_recorder);
509
510             id_visitor.visit_expr(const_expr);
511         }
512     }
513 }
514
515 /// Constructs a partial witness for a pattern given a list of
516 /// patterns expanded by the specialization step.
517 ///
518 /// When a pattern P is discovered to be useful, this function is used bottom-up
519 /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset
520 /// of values, V, where each value in that set is not covered by any previously
521 /// used patterns and is covered by the pattern P'. Examples:
522 ///
523 /// left_ty: tuple of 3 elements
524 /// pats: [10, 20, _]           => (10, 20, _)
525 ///
526 /// left_ty: struct X { a: (bool, &'static str), b: usize}
527 /// pats: [(false, "foo"), 42]  => X { a: (false, "foo"), b: 42 }
528 fn construct_witness<'a,'tcx>(cx: &MatchCheckCtxt<'a,'tcx>, ctor: &Constructor,
529                               pats: Vec<&Pat>, left_ty: Ty<'tcx>) -> P<Pat> {
530     let pats_len = pats.len();
531     let mut pats = pats.into_iter().map(|p| P((*p).clone()));
532     let pat = match left_ty.sty {
533         ty::TyTuple(_) => hir::PatTup(pats.collect()),
534
535         ty::TyEnum(adt, _) | ty::TyStruct(adt, _)  => {
536             let v = adt.variant_of_ctor(ctor);
537             if let VariantKind::Struct = v.kind() {
538                 let field_pats: hir::HirVec<_> = v.fields.iter()
539                     .zip(pats)
540                     .filter(|&(_, ref pat)| pat.node != hir::PatWild)
541                     .map(|(field, pat)| Spanned {
542                         span: DUMMY_SP,
543                         node: hir::FieldPat {
544                             name: field.name,
545                             pat: pat,
546                             is_shorthand: false,
547                         }
548                     }).collect();
549                 let has_more_fields = field_pats.len() < pats_len;
550                 hir::PatStruct(def_to_path(cx.tcx, v.did), field_pats, has_more_fields)
551             } else {
552                 hir::PatEnum(def_to_path(cx.tcx, v.did), Some(pats.collect()))
553             }
554         }
555
556         ty::TyRef(_, ty::TypeAndMut { ty, mutbl }) => {
557             match ty.sty {
558                ty::TyArray(_, n) => match ctor {
559                     &Single => {
560                         assert_eq!(pats_len, n);
561                         hir::PatVec(pats.collect(), None, hir::HirVec::new())
562                     },
563                     _ => unreachable!()
564                 },
565                 ty::TySlice(_) => match ctor {
566                     &Slice(n) => {
567                         assert_eq!(pats_len, n);
568                         hir::PatVec(pats.collect(), None, hir::HirVec::new())
569                     },
570                     _ => unreachable!()
571                 },
572                 ty::TyStr => hir::PatWild,
573
574                 _ => {
575                     assert_eq!(pats_len, 1);
576                     hir::PatRegion(pats.nth(0).unwrap(), mutbl)
577                 }
578             }
579         }
580
581         ty::TyArray(_, len) => {
582             assert_eq!(pats_len, len);
583             hir::PatVec(pats.collect(), None, hir::HirVec::new())
584         }
585
586         _ => {
587             match *ctor {
588                 ConstantValue(ref v) => hir::PatLit(const_val_to_expr(v)),
589                 _ => hir::PatWild,
590             }
591         }
592     };
593
594     P(hir::Pat {
595         id: 0,
596         node: pat,
597         span: DUMMY_SP
598     })
599 }
600
601 impl<'tcx, 'container> ty::AdtDefData<'tcx, 'container> {
602     fn variant_of_ctor(&self,
603                        ctor: &Constructor)
604                        -> &VariantDefData<'tcx, 'container> {
605         match ctor {
606             &Variant(vid) => self.variant_with_id(vid),
607             _ => self.struct_variant()
608         }
609     }
610 }
611
612 fn missing_constructors(cx: &MatchCheckCtxt, &Matrix(ref rows): &Matrix,
613                        left_ty: Ty, max_slice_length: usize) -> Vec<Constructor> {
614     let used_constructors: Vec<Constructor> = rows.iter()
615         .flat_map(|row| pat_constructors(cx, row[0], left_ty, max_slice_length))
616         .collect();
617     all_constructors(cx, left_ty, max_slice_length)
618         .into_iter()
619         .filter(|c| !used_constructors.contains(c)).collect()
620 }
621
622 /// This determines the set of all possible constructors of a pattern matching
623 /// values of type `left_ty`. For vectors, this would normally be an infinite set
624 /// but is instead bounded by the maximum fixed length of slice patterns in
625 /// the column of patterns being analyzed.
626 fn all_constructors(_cx: &MatchCheckCtxt, left_ty: Ty,
627                     max_slice_length: usize) -> Vec<Constructor> {
628     match left_ty.sty {
629         ty::TyBool =>
630             [true, false].iter().map(|b| ConstantValue(ConstVal::Bool(*b))).collect(),
631
632         ty::TyRef(_, ty::TypeAndMut { ty, .. }) => match ty.sty {
633             ty::TySlice(_) =>
634                 (0..max_slice_length+1).map(|length| Slice(length)).collect(),
635             _ => vec![Single]
636         },
637
638         ty::TyEnum(def, _) => def.variants.iter().map(|v| Variant(v.did)).collect(),
639         _ => vec![Single]
640     }
641 }
642
643 // Algorithm from http://moscova.inria.fr/~maranget/papers/warn/index.html
644 //
645 // Whether a vector `v` of patterns is 'useful' in relation to a set of such
646 // vectors `m` is defined as there being a set of inputs that will match `v`
647 // but not any of the sets in `m`.
648 //
649 // This is used both for reachability checking (if a pattern isn't useful in
650 // relation to preceding patterns, it is not reachable) and exhaustiveness
651 // checking (if a wildcard pattern is useful in relation to a matrix, the
652 // matrix isn't exhaustive).
653
654 // Note: is_useful doesn't work on empty types, as the paper notes.
655 // So it assumes that v is non-empty.
656 fn is_useful(cx: &MatchCheckCtxt,
657              matrix: &Matrix,
658              v: &[&Pat],
659              witness: WitnessPreference)
660              -> Usefulness {
661     let &Matrix(ref rows) = matrix;
662     debug!("{:?}", matrix);
663     if rows.is_empty() {
664         return match witness {
665             ConstructWitness => UsefulWithWitness(vec!()),
666             LeaveOutWitness => Useful
667         };
668     }
669     if rows[0].is_empty() {
670         return NotUseful;
671     }
672     assert!(rows.iter().all(|r| r.len() == v.len()));
673     let real_pat = match rows.iter().find(|r| (*r)[0].id != DUMMY_NODE_ID) {
674         Some(r) => raw_pat(r[0]),
675         None if v.is_empty() => return NotUseful,
676         None => v[0]
677     };
678     let left_ty = if real_pat.id == DUMMY_NODE_ID {
679         cx.tcx.mk_nil()
680     } else {
681         let left_ty = cx.tcx.pat_ty(&*real_pat);
682
683         match real_pat.node {
684             hir::PatIdent(hir::BindByRef(..), _, _) => {
685                 left_ty.builtin_deref(false, NoPreference).unwrap().ty
686             }
687             _ => left_ty,
688         }
689     };
690
691     let max_slice_length = rows.iter().filter_map(|row| match row[0].node {
692         hir::PatVec(ref before, _, ref after) => Some(before.len() + after.len()),
693         _ => None
694     }).max().map_or(0, |v| v + 1);
695
696     let constructors = pat_constructors(cx, v[0], left_ty, max_slice_length);
697     if constructors.is_empty() {
698         match &missing_constructors(cx, matrix, left_ty, max_slice_length)[..] {
699             [] => {
700                 all_constructors(cx, left_ty, max_slice_length).into_iter().map(|c| {
701                     match is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness) {
702                         UsefulWithWitness(pats) => UsefulWithWitness({
703                             let arity = constructor_arity(cx, &c, left_ty);
704                             let mut result = {
705                                 let pat_slice = &pats[..];
706                                 let subpats: Vec<_> = (0..arity).map(|i| {
707                                     pat_slice.get(i).map_or(DUMMY_WILD_PAT, |p| &**p)
708                                 }).collect();
709                                 vec![construct_witness(cx, &c, subpats, left_ty)]
710                             };
711                             result.extend(pats.into_iter().skip(arity));
712                             result
713                         }),
714                         result => result
715                     }
716                 }).find(|result| result != &NotUseful).unwrap_or(NotUseful)
717             },
718
719             [constructors..] => {
720                 let matrix = rows.iter().filter_map(|r| {
721                     if pat_is_binding_or_wild(&cx.tcx.def_map.borrow(), raw_pat(r[0])) {
722                         Some(r[1..].to_vec())
723                     } else {
724                         None
725                     }
726                 }).collect();
727                 match is_useful(cx, &matrix, &v[1..], witness) {
728                     UsefulWithWitness(pats) => {
729                         let mut new_pats: Vec<_> = constructors.into_iter().map(|constructor| {
730                             let arity = constructor_arity(cx, &constructor, left_ty);
731                             let wild_pats = vec![DUMMY_WILD_PAT; arity];
732                             construct_witness(cx, &constructor, wild_pats, left_ty)
733                         }).collect();
734                         new_pats.extend(pats);
735                         UsefulWithWitness(new_pats)
736                     },
737                     result => result
738                 }
739             }
740         }
741     } else {
742         constructors.into_iter().map(|c|
743             is_useful_specialized(cx, matrix, v, c.clone(), left_ty, witness)
744         ).find(|result| result != &NotUseful).unwrap_or(NotUseful)
745     }
746 }
747
748 fn is_useful_specialized(cx: &MatchCheckCtxt, &Matrix(ref m): &Matrix,
749                          v: &[&Pat], ctor: Constructor, lty: Ty,
750                          witness: WitnessPreference) -> Usefulness {
751     let arity = constructor_arity(cx, &ctor, lty);
752     let matrix = Matrix(m.iter().filter_map(|r| {
753         specialize(cx, &r[..], &ctor, 0, arity)
754     }).collect());
755     match specialize(cx, v, &ctor, 0, arity) {
756         Some(v) => is_useful(cx, &matrix, &v[..], witness),
757         None => NotUseful
758     }
759 }
760
761 /// Determines the constructors that the given pattern can be specialized to.
762 ///
763 /// In most cases, there's only one constructor that a specific pattern
764 /// represents, such as a specific enum variant or a specific literal value.
765 /// Slice patterns, however, can match slices of different lengths. For instance,
766 /// `[a, b, ..tail]` can match a slice of length 2, 3, 4 and so on.
767 ///
768 /// On the other hand, a wild pattern and an identifier pattern cannot be
769 /// specialized in any way.
770 fn pat_constructors(cx: &MatchCheckCtxt, p: &Pat,
771                     left_ty: Ty, max_slice_length: usize) -> Vec<Constructor> {
772     let pat = raw_pat(p);
773     match pat.node {
774         hir::PatIdent(..) =>
775             match cx.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
776                 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
777                     cx.tcx.sess.span_bug(pat.span, "const pattern should've \
778                                                     been rewritten"),
779                 Some(DefStruct(_)) => vec!(Single),
780                 Some(DefVariant(_, id, _)) => vec!(Variant(id)),
781                 _ => vec!()
782             },
783         hir::PatEnum(..) =>
784             match cx.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
785                 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
786                     cx.tcx.sess.span_bug(pat.span, "const pattern should've \
787                                                     been rewritten"),
788                 Some(DefVariant(_, id, _)) => vec!(Variant(id)),
789                 _ => vec!(Single)
790             },
791         hir::PatQPath(..) =>
792             cx.tcx.sess.span_bug(pat.span, "const pattern should've \
793                                             been rewritten"),
794         hir::PatStruct(..) =>
795             match cx.tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
796                 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
797                     cx.tcx.sess.span_bug(pat.span, "const pattern should've \
798                                                     been rewritten"),
799                 Some(DefVariant(_, id, _)) => vec!(Variant(id)),
800                 _ => vec!(Single)
801             },
802         hir::PatLit(ref expr) =>
803             vec!(ConstantValue(eval_const_expr(cx.tcx, &**expr))),
804         hir::PatRange(ref lo, ref hi) =>
805             vec!(ConstantRange(eval_const_expr(cx.tcx, &**lo), eval_const_expr(cx.tcx, &**hi))),
806         hir::PatVec(ref before, ref slice, ref after) =>
807             match left_ty.sty {
808                 ty::TyArray(_, _) => vec!(Single),
809                 _                      => if slice.is_some() {
810                     (before.len() + after.len()..max_slice_length+1)
811                         .map(|length| Slice(length))
812                         .collect()
813                 } else {
814                     vec!(Slice(before.len() + after.len()))
815                 }
816             },
817         hir::PatBox(_) | hir::PatTup(_) | hir::PatRegion(..) =>
818             vec!(Single),
819         hir::PatWild =>
820             vec!(),
821     }
822 }
823
824 /// This computes the arity of a constructor. The arity of a constructor
825 /// is how many subpattern patterns of that constructor should be expanded to.
826 ///
827 /// For instance, a tuple pattern (_, 42, Some([])) has the arity of 3.
828 /// A struct pattern's arity is the number of fields it contains, etc.
829 pub fn constructor_arity(_cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> usize {
830     match ty.sty {
831         ty::TyTuple(ref fs) => fs.len(),
832         ty::TyBox(_) => 1,
833         ty::TyRef(_, ty::TypeAndMut { ty, .. }) => match ty.sty {
834             ty::TySlice(_) => match *ctor {
835                 Slice(length) => length,
836                 ConstantValue(_) => 0,
837                 _ => unreachable!()
838             },
839             ty::TyStr => 0,
840             _ => 1
841         },
842         ty::TyEnum(adt, _) | ty::TyStruct(adt, _) => {
843             adt.variant_of_ctor(ctor).fields.len()
844         }
845         ty::TyArray(_, n) => n,
846         _ => 0
847     }
848 }
849
850 fn range_covered_by_constructor(ctor: &Constructor,
851                                 from: &ConstVal, to: &ConstVal) -> Option<bool> {
852     let (c_from, c_to) = match *ctor {
853         ConstantValue(ref value)        => (value, value),
854         ConstantRange(ref from, ref to) => (from, to),
855         Single                          => return Some(true),
856         _                               => unreachable!()
857     };
858     let cmp_from = compare_const_vals(c_from, from);
859     let cmp_to = compare_const_vals(c_to, to);
860     match (cmp_from, cmp_to) {
861         (Some(cmp_from), Some(cmp_to)) => {
862             Some(cmp_from != Ordering::Less && cmp_to != Ordering::Greater)
863         }
864         _ => None
865     }
866 }
867
868 /// This is the main specialization step. It expands the first pattern in the given row
869 /// into `arity` patterns based on the constructor. For most patterns, the step is trivial,
870 /// for instance tuple patterns are flattened and box patterns expand into their inner pattern.
871 ///
872 /// OTOH, slice patterns with a subslice pattern (..tail) can be expanded into multiple
873 /// different patterns.
874 /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing
875 /// fields filled with wild patterns.
876 pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat],
877                       constructor: &Constructor, col: usize, arity: usize) -> Option<Vec<&'a Pat>> {
878     let &Pat {
879         id: pat_id, ref node, span: pat_span
880     } = raw_pat(r[col]);
881     let head: Option<Vec<&Pat>> = match *node {
882         hir::PatWild =>
883             Some(vec![DUMMY_WILD_PAT; arity]),
884
885         hir::PatIdent(_, _, _) => {
886             let opt_def = cx.tcx.def_map.borrow().get(&pat_id).map(|d| d.full_def());
887             match opt_def {
888                 Some(DefConst(..)) | Some(DefAssociatedConst(..)) =>
889                     cx.tcx.sess.span_bug(pat_span, "const pattern should've \
890                                                     been rewritten"),
891                 Some(DefVariant(_, id, _)) => if *constructor == Variant(id) {
892                     Some(vec!())
893                 } else {
894                     None
895                 },
896                 _ => Some(vec![DUMMY_WILD_PAT; arity])
897             }
898         }
899
900         hir::PatEnum(_, ref args) => {
901             let def = cx.tcx.def_map.borrow().get(&pat_id).unwrap().full_def();
902             match def {
903                 DefConst(..) | DefAssociatedConst(..) =>
904                     cx.tcx.sess.span_bug(pat_span, "const pattern should've \
905                                                     been rewritten"),
906                 DefVariant(_, id, _) if *constructor != Variant(id) => None,
907                 DefVariant(..) | DefStruct(..) => {
908                     Some(match args {
909                         &Some(ref args) => args.iter().map(|p| &**p).collect(),
910                         &None => vec![DUMMY_WILD_PAT; arity],
911                     })
912                 }
913                 _ => None
914             }
915         }
916
917         hir::PatQPath(_, _) => {
918             cx.tcx.sess.span_bug(pat_span, "const pattern should've \
919                                             been rewritten")
920         }
921
922         hir::PatStruct(_, ref pattern_fields, _) => {
923             let def = cx.tcx.def_map.borrow().get(&pat_id).unwrap().full_def();
924             let adt = cx.tcx.node_id_to_type(pat_id).ty_adt_def().unwrap();
925             let variant = adt.variant_of_ctor(constructor);
926             let def_variant = adt.variant_of_def(def);
927             if variant.did == def_variant.did {
928                 Some(variant.fields.iter().map(|sf| {
929                     match pattern_fields.iter().find(|f| f.node.name == sf.name) {
930                         Some(ref f) => &*f.node.pat,
931                         _ => DUMMY_WILD_PAT
932                     }
933                 }).collect())
934             } else {
935                 None
936             }
937         }
938
939         hir::PatTup(ref args) =>
940             Some(args.iter().map(|p| &**p).collect()),
941
942         hir::PatBox(ref inner) | hir::PatRegion(ref inner, _) =>
943             Some(vec![&**inner]),
944
945         hir::PatLit(ref expr) => {
946             let expr_value = eval_const_expr(cx.tcx, &**expr);
947             match range_covered_by_constructor(constructor, &expr_value, &expr_value) {
948                 Some(true) => Some(vec![]),
949                 Some(false) => None,
950                 None => {
951                     span_err!(cx.tcx.sess, pat_span, E0298, "mismatched types between arms");
952                     None
953                 }
954             }
955         }
956
957         hir::PatRange(ref from, ref to) => {
958             let from_value = eval_const_expr(cx.tcx, &**from);
959             let to_value = eval_const_expr(cx.tcx, &**to);
960             match range_covered_by_constructor(constructor, &from_value, &to_value) {
961                 Some(true) => Some(vec![]),
962                 Some(false) => None,
963                 None => {
964                     span_err!(cx.tcx.sess, pat_span, E0299, "mismatched types between arms");
965                     None
966                 }
967             }
968         }
969
970         hir::PatVec(ref before, ref slice, ref after) => {
971             match *constructor {
972                 // Fixed-length vectors.
973                 Single => {
974                     let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
975                     pats.extend(repeat(DUMMY_WILD_PAT).take(arity - before.len() - after.len()));
976                     pats.extend(after.iter().map(|p| &**p));
977                     Some(pats)
978                 },
979                 Slice(length) if before.len() + after.len() <= length && slice.is_some() => {
980                     let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
981                     pats.extend(repeat(DUMMY_WILD_PAT).take(arity - before.len() - after.len()));
982                     pats.extend(after.iter().map(|p| &**p));
983                     Some(pats)
984                 },
985                 Slice(length) if before.len() + after.len() == length => {
986                     let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
987                     pats.extend(after.iter().map(|p| &**p));
988                     Some(pats)
989                 },
990                 SliceWithSubslice(prefix, suffix)
991                     if before.len() == prefix
992                         && after.len() == suffix
993                         && slice.is_some() => {
994                     let mut pats: Vec<&Pat> = before.iter().map(|p| &**p).collect();
995                     pats.extend(after.iter().map(|p| &**p));
996                     Some(pats)
997                 }
998                 _ => None
999             }
1000         }
1001     };
1002     head.map(|mut head| {
1003         head.extend_from_slice(&r[..col]);
1004         head.extend_from_slice(&r[col + 1..]);
1005         head
1006     })
1007 }
1008
1009 fn check_local(cx: &mut MatchCheckCtxt, loc: &hir::Local) {
1010     intravisit::walk_local(cx, loc);
1011
1012     let pat = StaticInliner::new(cx.tcx, None).fold_pat(loc.pat.clone());
1013     check_irrefutable(cx, &pat, false);
1014
1015     // Check legality of move bindings and `@` patterns.
1016     check_legality_of_move_bindings(cx, false, slice::ref_slice(&loc.pat));
1017     check_legality_of_bindings_in_at_patterns(cx, &*loc.pat);
1018 }
1019
1020 fn check_fn(cx: &mut MatchCheckCtxt,
1021             kind: FnKind,
1022             decl: &hir::FnDecl,
1023             body: &hir::Block,
1024             sp: Span,
1025             fn_id: NodeId) {
1026     match kind {
1027         FnKind::Closure => {}
1028         _ => cx.param_env = ParameterEnvironment::for_item(cx.tcx, fn_id),
1029     }
1030
1031     intravisit::walk_fn(cx, kind, decl, body, sp);
1032
1033     for input in &decl.inputs {
1034         check_irrefutable(cx, &input.pat, true);
1035         check_legality_of_move_bindings(cx, false, slice::ref_slice(&input.pat));
1036         check_legality_of_bindings_in_at_patterns(cx, &*input.pat);
1037     }
1038 }
1039
1040 fn check_irrefutable(cx: &MatchCheckCtxt, pat: &Pat, is_fn_arg: bool) {
1041     let origin = if is_fn_arg {
1042         "function argument"
1043     } else {
1044         "local binding"
1045     };
1046
1047     is_refutable(cx, pat, |uncovered_pat| {
1048         span_err!(cx.tcx.sess, pat.span, E0005,
1049             "refutable pattern in {}: `{}` not covered",
1050             origin,
1051             pat_to_string(uncovered_pat),
1052         );
1053     });
1054 }
1055
1056 fn is_refutable<A, F>(cx: &MatchCheckCtxt, pat: &Pat, refutable: F) -> Option<A> where
1057     F: FnOnce(&Pat) -> A,
1058 {
1059     let pats = Matrix(vec!(vec!(pat)));
1060     match is_useful(cx, &pats, &[DUMMY_WILD_PAT], ConstructWitness) {
1061         UsefulWithWitness(pats) => {
1062             assert_eq!(pats.len(), 1);
1063             Some(refutable(&*pats[0]))
1064         },
1065         NotUseful => None,
1066         Useful => unreachable!()
1067     }
1068 }
1069
1070 // Legality of move bindings checking
1071 fn check_legality_of_move_bindings(cx: &MatchCheckCtxt,
1072                                    has_guard: bool,
1073                                    pats: &[P<Pat>]) {
1074     let tcx = cx.tcx;
1075     let def_map = &tcx.def_map;
1076     let mut by_ref_span = None;
1077     for pat in pats {
1078         pat_bindings(def_map, &**pat, |bm, _, span, _path| {
1079             match bm {
1080                 hir::BindByRef(_) => {
1081                     by_ref_span = Some(span);
1082                 }
1083                 hir::BindByValue(_) => {
1084                 }
1085             }
1086         })
1087     }
1088
1089     let check_move = |p: &Pat, sub: Option<&Pat>| {
1090         // check legality of moving out of the enum
1091
1092         // x @ Foo(..) is legal, but x @ Foo(y) isn't.
1093         if sub.map_or(false, |p| pat_contains_bindings(&def_map.borrow(), &*p)) {
1094             span_err!(cx.tcx.sess, p.span, E0007, "cannot bind by-move with sub-bindings");
1095         } else if has_guard {
1096             span_err!(cx.tcx.sess, p.span, E0008, "cannot bind by-move into a pattern guard");
1097         } else if by_ref_span.is_some() {
1098             let mut err = struct_span_err!(cx.tcx.sess, p.span, E0009,
1099                                            "cannot bind by-move and by-ref in the same pattern");
1100             span_note!(&mut err, by_ref_span.unwrap(), "by-ref binding occurs here");
1101             err.emit();
1102         }
1103     };
1104
1105     for pat in pats {
1106         front_util::walk_pat(&**pat, |p| {
1107             if pat_is_binding(&def_map.borrow(), &*p) {
1108                 match p.node {
1109                     hir::PatIdent(hir::BindByValue(_), _, ref sub) => {
1110                         let pat_ty = tcx.node_id_to_type(p.id);
1111                         //FIXME: (@jroesch) this code should be floated up as well
1112                         let infcx = infer::new_infer_ctxt(cx.tcx,
1113                                                           &cx.tcx.tables,
1114                                                           Some(cx.param_env.clone()));
1115                         if infcx.type_moves_by_default(pat_ty, pat.span) {
1116                             check_move(p, sub.as_ref().map(|p| &**p));
1117                         }
1118                     }
1119                     hir::PatIdent(hir::BindByRef(_), _, _) => {
1120                     }
1121                     _ => {
1122                         cx.tcx.sess.span_bug(
1123                             p.span,
1124                             &format!("binding pattern {} is not an \
1125                                      identifier: {:?}",
1126                                     p.id,
1127                                     p.node));
1128                     }
1129                 }
1130             }
1131             true
1132         });
1133     }
1134 }
1135
1136 /// Ensures that a pattern guard doesn't borrow by mutable reference or
1137 /// assign.
1138 fn check_for_mutation_in_guard<'a, 'tcx>(cx: &'a MatchCheckCtxt<'a, 'tcx>,
1139                                          guard: &hir::Expr) {
1140     let mut checker = MutationChecker {
1141         cx: cx,
1142     };
1143
1144     let infcx = infer::new_infer_ctxt(cx.tcx,
1145                                       &cx.tcx.tables,
1146                                       Some(checker.cx.param_env.clone()));
1147
1148     let mut visitor = ExprUseVisitor::new(&mut checker, &infcx);
1149     visitor.walk_expr(guard);
1150 }
1151
1152 struct MutationChecker<'a, 'tcx: 'a> {
1153     cx: &'a MatchCheckCtxt<'a, 'tcx>,
1154 }
1155
1156 impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> {
1157     fn matched_pat(&mut self, _: &Pat, _: cmt, _: euv::MatchMode) {}
1158     fn consume(&mut self, _: NodeId, _: Span, _: cmt, _: ConsumeMode) {}
1159     fn consume_pat(&mut self, _: &Pat, _: cmt, _: ConsumeMode) {}
1160     fn borrow(&mut self,
1161               _: NodeId,
1162               span: Span,
1163               _: cmt,
1164               _: Region,
1165               kind: BorrowKind,
1166               _: LoanCause) {
1167         match kind {
1168             MutBorrow => {
1169                 span_err!(self.cx.tcx.sess, span, E0301,
1170                           "cannot mutably borrow in a pattern guard")
1171             }
1172             ImmBorrow | UniqueImmBorrow => {}
1173         }
1174     }
1175     fn decl_without_init(&mut self, _: NodeId, _: Span) {}
1176     fn mutate(&mut self, _: NodeId, span: Span, _: cmt, mode: MutateMode) {
1177         match mode {
1178             MutateMode::JustWrite | MutateMode::WriteAndRead => {
1179                 span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
1180             }
1181             MutateMode::Init => {}
1182         }
1183     }
1184 }
1185
1186 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
1187 /// because of the way rvalues are handled in the borrow check. (See issue
1188 /// #14587.)
1189 fn check_legality_of_bindings_in_at_patterns(cx: &MatchCheckCtxt, pat: &Pat) {
1190     AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
1191 }
1192
1193 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
1194     cx: &'a MatchCheckCtxt<'b, 'tcx>,
1195     bindings_allowed: bool
1196 }
1197
1198 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
1199     fn visit_pat(&mut self, pat: &Pat) {
1200         if !self.bindings_allowed && pat_is_binding(&self.cx.tcx.def_map.borrow(), pat) {
1201             span_err!(self.cx.tcx.sess, pat.span, E0303,
1202                                       "pattern bindings are not allowed \
1203                                        after an `@`");
1204         }
1205
1206         match pat.node {
1207             hir::PatIdent(_, _, Some(_)) => {
1208                 let bindings_were_allowed = self.bindings_allowed;
1209                 self.bindings_allowed = false;
1210                 intravisit::walk_pat(self, pat);
1211                 self.bindings_allowed = bindings_were_allowed;
1212             }
1213             _ => intravisit::walk_pat(self, pat),
1214         }
1215     }
1216 }