]> git.lizzy.rs Git - rust.git/blob - src/librustc_const_eval/check_match.rs
Refactor away `inferred_obligations` from the trait selector
[rust.git] / src / librustc_const_eval / check_match.rs
1 // Copyright 2012-2016 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 use _match::{MatchCheckCtxt, Matrix, expand_pattern, is_useful};
12 use _match::Usefulness::*;
13 use _match::WitnessPreference::*;
14
15 use pattern::{Pattern, PatternContext, PatternError, PatternKind};
16
17 use rustc::middle::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor};
18 use rustc::middle::expr_use_visitor::{LoanCause, MutateMode};
19 use rustc::middle::expr_use_visitor as euv;
20 use rustc::middle::mem_categorization::{cmt};
21 use rustc::middle::region;
22 use rustc::session::Session;
23 use rustc::ty::{self, Ty, TyCtxt};
24 use rustc::ty::subst::Substs;
25 use rustc::lint;
26 use rustc_errors::DiagnosticBuilder;
27 use rustc::util::common::ErrorReported;
28
29 use rustc::hir::def::*;
30 use rustc::hir::def_id::DefId;
31 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
32 use rustc::hir::{self, Pat, PatKind};
33
34 use std::slice;
35
36 use syntax::ast;
37 use syntax::ptr::P;
38 use syntax_pos::{Span, DUMMY_SP};
39
40 struct OuterVisitor<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx> }
41
42 impl<'a, 'tcx> Visitor<'tcx> for OuterVisitor<'a, 'tcx> {
43     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
44         NestedVisitorMap::OnlyBodies(&self.tcx.hir)
45     }
46
47     fn visit_body(&mut self, body: &'tcx hir::Body) {
48         intravisit::walk_body(self, body);
49         let def_id = self.tcx.hir.body_owner_def_id(body.id());
50         let _ = self.tcx.check_match(def_id);
51     }
52 }
53
54 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
55     tcx.hir.krate().visit_all_item_likes(&mut OuterVisitor { tcx: tcx }.as_deep_visitor());
56     tcx.sess.abort_if_errors();
57 }
58
59 pub(crate) fn check_match<'a, 'tcx>(
60     tcx: TyCtxt<'a, 'tcx, 'tcx>,
61     def_id: DefId,
62 ) -> Result<(), ErrorReported> {
63     let body_id = if let Some(id) = tcx.hir.as_local_node_id(def_id) {
64         tcx.hir.body_owned_by(id)
65     } else {
66         return Ok(());
67     };
68
69     tcx.sess.track_errors(|| {
70         MatchVisitor {
71             tcx,
72             tables: tcx.body_tables(body_id),
73             region_scope_tree: &tcx.region_scope_tree(def_id),
74             param_env: tcx.param_env(def_id),
75             identity_substs: Substs::identity_for_item(tcx, def_id),
76         }.visit_body(tcx.hir.body(body_id));
77     })
78 }
79
80 fn create_e0004<'a>(sess: &'a Session, sp: Span, error_message: String) -> DiagnosticBuilder<'a> {
81     struct_span_err!(sess, sp, E0004, "{}", &error_message)
82 }
83
84 struct MatchVisitor<'a, 'tcx: 'a> {
85     tcx: TyCtxt<'a, 'tcx, 'tcx>,
86     tables: &'a ty::TypeckTables<'tcx>,
87     param_env: ty::ParamEnv<'tcx>,
88     identity_substs: &'tcx Substs<'tcx>,
89     region_scope_tree: &'a region::ScopeTree,
90 }
91
92 impl<'a, 'tcx> Visitor<'tcx> for MatchVisitor<'a, 'tcx> {
93     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
94         NestedVisitorMap::None
95     }
96
97     fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
98         intravisit::walk_expr(self, ex);
99
100         match ex.node {
101             hir::ExprMatch(ref scrut, ref arms, source) => {
102                 self.check_match(scrut, arms, source);
103             }
104             _ => {}
105         }
106     }
107
108     fn visit_local(&mut self, loc: &'tcx hir::Local) {
109         intravisit::walk_local(self, loc);
110
111         self.check_irrefutable(&loc.pat, match loc.source {
112             hir::LocalSource::Normal => "local binding",
113             hir::LocalSource::ForLoopDesugar => "`for` loop binding",
114         });
115
116         // Check legality of move bindings and `@` patterns.
117         self.check_patterns(false, slice::from_ref(&loc.pat));
118     }
119
120     fn visit_body(&mut self, body: &'tcx hir::Body) {
121         intravisit::walk_body(self, body);
122
123         for arg in &body.arguments {
124             self.check_irrefutable(&arg.pat, "function argument");
125             self.check_patterns(false, slice::from_ref(&arg.pat));
126         }
127     }
128 }
129
130
131 impl<'a, 'tcx> PatternContext<'a, 'tcx> {
132     fn report_inlining_errors(&self, pat_span: Span) {
133         for error in &self.errors {
134             match *error {
135                 PatternError::StaticInPattern(span) => {
136                     self.span_e0158(span, "statics cannot be referenced in patterns")
137                 }
138                 PatternError::AssociatedConstInPattern(span) => {
139                     self.span_e0158(span, "associated consts cannot be referenced in patterns")
140                 }
141                 PatternError::ConstEval(ref err) => {
142                     err.report(self.tcx, pat_span, "pattern");
143                 }
144             }
145         }
146     }
147
148     fn span_e0158(&self, span: Span, text: &str) {
149         span_err!(self.tcx.sess, span, E0158, "{}", text)
150     }
151 }
152
153 impl<'a, 'tcx> MatchVisitor<'a, 'tcx> {
154     fn check_patterns(&self, has_guard: bool, pats: &[P<Pat>]) {
155         check_legality_of_move_bindings(self, has_guard, pats);
156         for pat in pats {
157             check_legality_of_bindings_in_at_patterns(self, pat);
158         }
159     }
160
161     fn check_match(
162         &self,
163         scrut: &hir::Expr,
164         arms: &'tcx [hir::Arm],
165         source: hir::MatchSource)
166     {
167         for arm in arms {
168             // First, check legality of move bindings.
169             self.check_patterns(arm.guard.is_some(), &arm.pats);
170
171             // Second, if there is a guard on each arm, make sure it isn't
172             // assigning or borrowing anything mutably.
173             if let Some(ref guard) = arm.guard {
174                 check_for_mutation_in_guard(self, &guard);
175             }
176
177             // Third, perform some lints.
178             for pat in &arm.pats {
179                 check_for_bindings_named_the_same_as_variants(self, pat);
180             }
181         }
182
183         let module = self.tcx.hir.get_module_parent(scrut.id);
184         MatchCheckCtxt::create_and_enter(self.tcx, module, |ref mut cx| {
185             let mut have_errors = false;
186
187             let inlined_arms : Vec<(Vec<_>, _)> = arms.iter().map(|arm| (
188                 arm.pats.iter().map(|pat| {
189                     let mut patcx = PatternContext::new(self.tcx,
190                                                         self.param_env.and(self.identity_substs),
191                                                         self.tables);
192                     let pattern = expand_pattern(cx, patcx.lower_pattern(&pat));
193                     if !patcx.errors.is_empty() {
194                         patcx.report_inlining_errors(pat.span);
195                         have_errors = true;
196                     }
197                     (pattern, &**pat)
198                 }).collect(),
199                 arm.guard.as_ref().map(|e| &**e)
200             )).collect();
201
202             // Bail out early if inlining failed.
203             if have_errors {
204                 return;
205             }
206
207             // Fourth, check for unreachable arms.
208             check_arms(cx, &inlined_arms, source);
209
210             // Then, if the match has no arms, check whether the scrutinee
211             // is uninhabited.
212             let pat_ty = self.tables.node_id_to_type(scrut.hir_id);
213             let module = self.tcx.hir.get_module_parent(scrut.id);
214             if inlined_arms.is_empty() {
215                 let scrutinee_is_uninhabited = if self.tcx.sess.features.borrow().never_type {
216                     self.tcx.is_ty_uninhabited_from(module, pat_ty)
217                 } else {
218                     self.conservative_is_uninhabited(pat_ty)
219                 };
220                 if !scrutinee_is_uninhabited {
221                     // We know the type is inhabited, so this must be wrong
222                     let mut err = create_e0004(self.tcx.sess, scrut.span,
223                                                format!("non-exhaustive patterns: type {} \
224                                                         is non-empty",
225                                                        pat_ty));
226                     span_help!(&mut err, scrut.span,
227                                "Please ensure that all possible cases are being handled; \
228                                 possibly adding wildcards or more match arms.");
229                     err.emit();
230                 }
231                 // If the type *is* uninhabited, it's vacuously exhaustive
232                 return;
233             }
234
235             let matrix: Matrix = inlined_arms
236                 .iter()
237                 .filter(|&&(_, guard)| guard.is_none())
238                 .flat_map(|arm| &arm.0)
239                 .map(|pat| vec![pat.0])
240                 .collect();
241             let scrut_ty = self.tables.node_id_to_type(scrut.hir_id);
242             check_exhaustive(cx, scrut_ty, scrut.span, &matrix);
243         })
244     }
245
246     fn conservative_is_uninhabited(&self, scrutinee_ty: Ty<'tcx>) -> bool {
247         // "rustc-1.0-style" uncontentious uninhabitableness check
248         match scrutinee_ty.sty {
249             ty::TyNever => true,
250             ty::TyAdt(def, _) => def.variants.is_empty(),
251             _ => false
252         }
253     }
254
255     fn check_irrefutable(&self, pat: &'tcx Pat, origin: &str) {
256         let module = self.tcx.hir.get_module_parent(pat.id);
257         MatchCheckCtxt::create_and_enter(self.tcx, module, |ref mut cx| {
258             let mut patcx = PatternContext::new(self.tcx,
259                                                 self.param_env.and(self.identity_substs),
260                                                 self.tables);
261             let pattern = patcx.lower_pattern(pat);
262             let pattern_ty = pattern.ty;
263             let pats : Matrix = vec![vec![
264                 expand_pattern(cx, pattern)
265             ]].into_iter().collect();
266
267             let wild_pattern = Pattern {
268                 ty: pattern_ty,
269                 span: DUMMY_SP,
270                 kind: box PatternKind::Wild,
271             };
272             let witness = match is_useful(cx, &pats, &[&wild_pattern], ConstructWitness) {
273                 UsefulWithWitness(witness) => witness,
274                 NotUseful => return,
275                 Useful => bug!()
276             };
277
278             let pattern_string = witness[0].single_pattern().to_string();
279             let mut diag = struct_span_err!(
280                 self.tcx.sess, pat.span, E0005,
281                 "refutable pattern in {}: `{}` not covered",
282                 origin, pattern_string
283             );
284             let label_msg = match pat.node {
285                 PatKind::Path(hir::QPath::Resolved(None, ref path))
286                         if path.segments.len() == 1 && path.segments[0].parameters.is_none() => {
287                     format!("interpreted as a {} pattern, not new variable", path.def.kind_name())
288                 }
289                 _ => format!("pattern `{}` not covered", pattern_string),
290             };
291             diag.span_label(pat.span, label_msg);
292             diag.emit();
293         });
294     }
295 }
296
297 fn check_for_bindings_named_the_same_as_variants(cx: &MatchVisitor, pat: &Pat) {
298     pat.walk(|p| {
299         if let PatKind::Binding(_, _, name, None) = p.node {
300             let bm = *cx.tables
301                         .pat_binding_modes()
302                         .get(p.hir_id)
303                         .expect("missing binding mode");
304
305             if bm != ty::BindByValue(hir::MutImmutable) {
306                 // Nothing to check.
307                 return true;
308             }
309             let pat_ty = cx.tables.pat_ty(p);
310             if let ty::TyAdt(edef, _) = pat_ty.sty {
311                 if edef.is_enum() && edef.variants.iter().any(|variant| {
312                     variant.name == name.node && variant.ctor_kind == CtorKind::Const
313                 }) {
314                     let ty_path = cx.tcx.item_path_str(edef.did);
315                     let mut err = struct_span_warn!(cx.tcx.sess, p.span, E0170,
316                         "pattern binding `{}` is named the same as one \
317                          of the variants of the type `{}`",
318                         name.node, ty_path);
319                     help!(err,
320                         "if you meant to match on a variant, \
321                         consider making the path in the pattern qualified: `{}::{}`",
322                         ty_path, name.node);
323                     err.emit();
324                 }
325             }
326         }
327         true
328     });
329 }
330
331 /// Checks for common cases of "catchall" patterns that may not be intended as such.
332 fn pat_is_catchall(pat: &Pat) -> bool {
333     match pat.node {
334         PatKind::Binding(.., None) => true,
335         PatKind::Binding(.., Some(ref s)) => pat_is_catchall(s),
336         PatKind::Ref(ref s, _) => pat_is_catchall(s),
337         PatKind::Tuple(ref v, _) => v.iter().all(|p| {
338             pat_is_catchall(&p)
339         }),
340         _ => false
341     }
342 }
343
344 // Check for unreachable patterns
345 fn check_arms<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
346                         arms: &[(Vec<(&'a Pattern<'tcx>, &hir::Pat)>, Option<&hir::Expr>)],
347                         source: hir::MatchSource)
348 {
349     let mut seen = Matrix::empty();
350     let mut catchall = None;
351     let mut printed_if_let_err = false;
352     for (arm_index, &(ref pats, guard)) in arms.iter().enumerate() {
353         for &(pat, hir_pat) in pats {
354             let v = vec![pat];
355
356             match is_useful(cx, &seen, &v, LeaveOutWitness) {
357                 NotUseful => {
358                     match source {
359                         hir::MatchSource::IfLetDesugar { .. } => {
360                             if printed_if_let_err {
361                                 // we already printed an irrefutable if-let pattern error.
362                                 // We don't want two, that's just confusing.
363                             } else {
364                                 // find the first arm pattern so we can use its span
365                                 let &(ref first_arm_pats, _) = &arms[0];
366                                 let first_pat = &first_arm_pats[0];
367                                 let span = first_pat.0.span;
368                                 struct_span_err!(cx.tcx.sess, span, E0162,
369                                                 "irrefutable if-let pattern")
370                                     .span_label(span, "irrefutable pattern")
371                                     .emit();
372                                 printed_if_let_err = true;
373                             }
374                         },
375
376                         hir::MatchSource::WhileLetDesugar => {
377                             // find the first arm pattern so we can use its span
378                             let &(ref first_arm_pats, _) = &arms[0];
379                             let first_pat = &first_arm_pats[0];
380                             let span = first_pat.0.span;
381
382                             // check which arm we're on.
383                             match arm_index {
384                                 // The arm with the user-specified pattern.
385                                 0 => {
386                                     cx.tcx.lint_node(
387                                             lint::builtin::UNREACHABLE_PATTERNS,
388                                         hir_pat.id, pat.span,
389                                         "unreachable pattern");
390                                 },
391                                 // The arm with the wildcard pattern.
392                                 1 => {
393                                     struct_span_err!(cx.tcx.sess, span, E0165,
394                                                      "irrefutable while-let pattern")
395                                         .span_label(span, "irrefutable pattern")
396                                         .emit();
397                                 },
398                                 _ => bug!(),
399                             }
400                         },
401
402                         hir::MatchSource::ForLoopDesugar |
403                         hir::MatchSource::Normal => {
404                             let mut err = cx.tcx.struct_span_lint_node(
405                                 lint::builtin::UNREACHABLE_PATTERNS,
406                                 hir_pat.id,
407                                 pat.span,
408                                 "unreachable pattern",
409                             );
410                             // if we had a catchall pattern, hint at that
411                             if let Some(catchall) = catchall {
412                                 err.span_label(pat.span, "unreachable pattern");
413                                 err.span_label(catchall, "matches any value");
414                             }
415                             err.emit();
416                         },
417
418                         // Unreachable patterns in try expressions occur when one of the arms
419                         // are an uninhabited type. Which is OK.
420                         hir::MatchSource::TryDesugar => {}
421                     }
422                 }
423                 Useful => (),
424                 UsefulWithWitness(_) => bug!()
425             }
426             if guard.is_none() {
427                 seen.push(v);
428                 if catchall.is_none() && pat_is_catchall(hir_pat) {
429                     catchall = Some(pat.span);
430                 }
431             }
432         }
433     }
434 }
435
436 fn check_exhaustive<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>,
437                               scrut_ty: Ty<'tcx>,
438                               sp: Span,
439                               matrix: &Matrix<'a, 'tcx>) {
440     let wild_pattern = Pattern {
441         ty: scrut_ty,
442         span: DUMMY_SP,
443         kind: box PatternKind::Wild,
444     };
445     match is_useful(cx, matrix, &[&wild_pattern], ConstructWitness) {
446         UsefulWithWitness(pats) => {
447             let witnesses = if pats.is_empty() {
448                 vec![&wild_pattern]
449             } else {
450                 pats.iter().map(|w| w.single_pattern()).collect()
451             };
452
453             const LIMIT: usize = 3;
454             let joined_patterns = match witnesses.len() {
455                 0 => bug!(),
456                 1 => format!("`{}`", witnesses[0]),
457                 2...LIMIT => {
458                     let (tail, head) = witnesses.split_last().unwrap();
459                     let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
460                     format!("`{}` and `{}`", head.join("`, `"), tail)
461                 },
462                 _ => {
463                     let (head, tail) = witnesses.split_at(LIMIT);
464                     let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
465                     format!("`{}` and {} more", head.join("`, `"), tail.len())
466                 }
467             };
468
469             let label_text = match witnesses.len() {
470                 1 => format!("pattern {} not covered", joined_patterns),
471                 _ => format!("patterns {} not covered", joined_patterns)
472             };
473             create_e0004(cx.tcx.sess, sp,
474                             format!("non-exhaustive patterns: {} not covered",
475                                     joined_patterns))
476                 .span_label(sp, label_text)
477                 .emit();
478         }
479         NotUseful => {
480             // This is good, wildcard pattern isn't reachable
481         },
482         _ => bug!()
483     }
484 }
485
486 // Legality of move bindings checking
487 fn check_legality_of_move_bindings(cx: &MatchVisitor,
488                                    has_guard: bool,
489                                    pats: &[P<Pat>]) {
490     let mut by_ref_span = None;
491     for pat in pats {
492         pat.each_binding(|_, id, span, _path| {
493             let hir_id = cx.tcx.hir.node_to_hir_id(id);
494             let bm = *cx.tables
495                         .pat_binding_modes()
496                         .get(hir_id)
497                         .expect("missing binding mode");
498             if let ty::BindByReference(..) = bm {
499                 by_ref_span = Some(span);
500             }
501         })
502     }
503
504     let check_move = |p: &Pat, sub: Option<&Pat>| {
505         // check legality of moving out of the enum
506
507         // x @ Foo(..) is legal, but x @ Foo(y) isn't.
508         if sub.map_or(false, |p| p.contains_bindings()) {
509             struct_span_err!(cx.tcx.sess, p.span, E0007,
510                              "cannot bind by-move with sub-bindings")
511                 .span_label(p.span, "binds an already bound by-move value by moving it")
512                 .emit();
513         } else if has_guard {
514             struct_span_err!(cx.tcx.sess, p.span, E0008,
515                       "cannot bind by-move into a pattern guard")
516                 .span_label(p.span, "moves value into pattern guard")
517                 .emit();
518         } else if by_ref_span.is_some() {
519             struct_span_err!(cx.tcx.sess, p.span, E0009,
520                             "cannot bind by-move and by-ref in the same pattern")
521                     .span_label(p.span, "by-move pattern here")
522                     .span_label(by_ref_span.unwrap(), "both by-ref and by-move used")
523                     .emit();
524         }
525     };
526
527     for pat in pats {
528         pat.walk(|p| {
529             if let PatKind::Binding(_, _, _, ref sub) = p.node {
530                 let bm = *cx.tables
531                             .pat_binding_modes()
532                             .get(p.hir_id)
533                             .expect("missing binding mode");
534                 match bm {
535                     ty::BindByValue(..) => {
536                         let pat_ty = cx.tables.node_id_to_type(p.hir_id);
537                         if pat_ty.moves_by_default(cx.tcx, cx.param_env, pat.span) {
538                             check_move(p, sub.as_ref().map(|p| &**p));
539                         }
540                     }
541                     _ => {}
542                 }
543             }
544             true
545         });
546     }
547 }
548
549 /// Ensures that a pattern guard doesn't borrow by mutable reference or
550 /// assign.
551 ///
552 /// FIXME: this should be done by borrowck.
553 fn check_for_mutation_in_guard(cx: &MatchVisitor, guard: &hir::Expr) {
554     let mut checker = MutationChecker {
555         cx,
556     };
557     ExprUseVisitor::new(&mut checker, cx.tcx, cx.param_env, cx.region_scope_tree, cx.tables, None)
558         .walk_expr(guard);
559 }
560
561 struct MutationChecker<'a, 'tcx: 'a> {
562     cx: &'a MatchVisitor<'a, 'tcx>,
563 }
564
565 impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> {
566     fn matched_pat(&mut self, _: &Pat, _: cmt, _: euv::MatchMode) {}
567     fn consume(&mut self, _: ast::NodeId, _: Span, _: cmt, _: ConsumeMode) {}
568     fn consume_pat(&mut self, _: &Pat, _: cmt, _: ConsumeMode) {}
569     fn borrow(&mut self,
570               _: ast::NodeId,
571               span: Span,
572               _: cmt,
573               _: ty::Region<'tcx>,
574               kind:ty:: BorrowKind,
575               _: LoanCause) {
576         match kind {
577             ty::MutBorrow => {
578                 struct_span_err!(self.cx.tcx.sess, span, E0301,
579                           "cannot mutably borrow in a pattern guard")
580                     .span_label(span, "borrowed mutably in pattern guard")
581                     .emit();
582             }
583             ty::ImmBorrow | ty::UniqueImmBorrow => {}
584         }
585     }
586     fn decl_without_init(&mut self, _: ast::NodeId, _: Span) {}
587     fn mutate(&mut self, _: ast::NodeId, span: Span, _: cmt, mode: MutateMode) {
588         match mode {
589             MutateMode::JustWrite | MutateMode::WriteAndRead => {
590                 struct_span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
591                     .span_label(span, "assignment in pattern guard")
592                     .emit();
593             }
594             MutateMode::Init => {}
595         }
596     }
597 }
598
599 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
600 /// because of the way rvalues are handled in the borrow check. (See issue
601 /// #14587.)
602 fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor, pat: &Pat) {
603     AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
604 }
605
606 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
607     cx: &'a MatchVisitor<'b, 'tcx>,
608     bindings_allowed: bool
609 }
610
611 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
612     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
613         NestedVisitorMap::None
614     }
615
616     fn visit_pat(&mut self, pat: &Pat) {
617         match pat.node {
618             PatKind::Binding(.., ref subpat) => {
619                 if !self.bindings_allowed {
620                     struct_span_err!(self.cx.tcx.sess, pat.span, E0303,
621                                      "pattern bindings are not allowed after an `@`")
622                         .span_label(pat.span,  "not allowed after `@`")
623                         .emit();
624                 }
625
626                 if subpat.is_some() {
627                     let bindings_were_allowed = self.bindings_allowed;
628                     self.bindings_allowed = false;
629                     intravisit::walk_pat(self, pat);
630                     self.bindings_allowed = bindings_were_allowed;
631                 }
632             }
633             _ => intravisit::walk_pat(self, pat),
634         }
635     }
636 }