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