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