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