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