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