]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/hair/pattern/check_match.rs
ed183acc93b74f75e9f5adafb28c90c8fef37406
[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         });
81
82         // Check legality of move bindings and `@` patterns.
83         self.check_patterns(false, slice::from_ref(&loc.pat));
84     }
85
86     fn visit_body(&mut self, body: &'tcx hir::Body) {
87         intravisit::walk_body(self, body);
88
89         for arg in &body.arguments {
90             self.check_irrefutable(&arg.pat, "function argument");
91             self.check_patterns(false, slice::from_ref(&arg.pat));
92         }
93     }
94 }
95
96
97 impl<'a, 'tcx> PatternContext<'a, 'tcx> {
98     fn report_inlining_errors(&self, pat_span: Span) {
99         for error in &self.errors {
100             match *error {
101                 PatternError::StaticInPattern(span) => {
102                     self.span_e0158(span, "statics cannot be referenced in patterns")
103                 }
104                 PatternError::AssociatedConstInPattern(span) => {
105                     self.span_e0158(span, "associated consts cannot be referenced in patterns")
106                 }
107                 PatternError::FloatBug => {
108                     // FIXME(#31407) this is only necessary because float parsing is buggy
109                     ::rustc::mir::interpret::struct_error(
110                         self.tcx.at(pat_span),
111                         "could not evaluate float literal (see issue #31407)",
112                     ).emit();
113                 }
114                 PatternError::NonConstPath(span) => {
115                     ::rustc::mir::interpret::struct_error(
116                         self.tcx.at(span),
117                         "runtime values cannot be referenced in patterns",
118                     ).emit();
119                 }
120             }
121         }
122     }
123
124     fn span_e0158(&self, span: Span, text: &str) {
125         span_err!(self.tcx.sess, span, E0158, "{}", text)
126     }
127 }
128
129 impl<'a, 'tcx> MatchVisitor<'a, 'tcx> {
130     fn check_patterns(&self, has_guard: bool, pats: &[P<Pat>]) {
131         check_legality_of_move_bindings(self, has_guard, pats);
132         for pat in pats {
133             check_legality_of_bindings_in_at_patterns(self, pat);
134         }
135     }
136
137     fn check_match(
138         &self,
139         scrut: &hir::Expr,
140         arms: &'tcx [hir::Arm],
141         source: hir::MatchSource)
142     {
143         for arm in arms {
144             // First, check legality of move bindings.
145             self.check_patterns(arm.guard.is_some(), &arm.pats);
146
147             // Second, if there is a guard on each arm, make sure it isn't
148             // assigning or borrowing anything mutably.
149             if let Some(ref guard) = arm.guard {
150                 if !self.tcx.features().bind_by_move_pattern_guards {
151                     check_for_mutation_in_guard(self, &guard);
152                 }
153             }
154
155             // Third, perform some lints.
156             for pat in &arm.pats {
157                 check_for_bindings_named_same_as_variants(self, pat);
158             }
159         }
160
161         let module = self.tcx.hir().get_module_parent_by_hir_id(scrut.hir_id);
162         MatchCheckCtxt::create_and_enter(self.tcx, self.param_env, module, |ref mut cx| {
163             let mut have_errors = false;
164
165             let inlined_arms : Vec<(Vec<_>, _)> = arms.iter().map(|arm| (
166                 arm.pats.iter().map(|pat| {
167                     let mut patcx = PatternContext::new(self.tcx,
168                                                         self.param_env.and(self.identity_substs),
169                                                         self.tables);
170                     let pattern = expand_pattern(cx, patcx.lower_pattern(&pat));
171                     if !patcx.errors.is_empty() {
172                         patcx.report_inlining_errors(pat.span);
173                         have_errors = true;
174                     }
175                     (pattern, &**pat)
176                 }).collect(),
177                 arm.guard.as_ref().map(|g| match g {
178                     hir::Guard::If(ref e) => &**e,
179                 })
180             )).collect();
181
182             // Bail out early if inlining failed.
183             if have_errors {
184                 return;
185             }
186
187             // Fourth, check for unreachable arms.
188             check_arms(cx, &inlined_arms, source);
189
190             // Then, if the match has no arms, check whether the scrutinee
191             // is uninhabited.
192             let pat_ty = self.tables.node_type(scrut.hir_id);
193             let module = self.tcx.hir().get_module_parent_by_hir_id(scrut.hir_id);
194             let mut def_span = None;
195             let mut missing_variants = vec![];
196             if inlined_arms.is_empty() {
197                 let scrutinee_is_uninhabited = if self.tcx.features().exhaustive_patterns {
198                     self.tcx.is_ty_uninhabited_from(module, pat_ty)
199                 } else {
200                     match pat_ty.sty {
201                         ty::Never => true,
202                         ty::Adt(def, _) => {
203                             def_span = self.tcx.hir().span_if_local(def.did);
204                             if def.variants.len() < 4 && !def.variants.is_empty() {
205                                 // keep around to point at the definition of non-covered variants
206                                 missing_variants = def.variants.iter()
207                                     .map(|variant| variant.ident)
208                                     .collect();
209                             }
210                             def.variants.is_empty()
211                         },
212                         _ => false
213                     }
214                 };
215                 if !scrutinee_is_uninhabited {
216                     // We know the type is inhabited, so this must be wrong
217                     let mut err = create_e0004(
218                         self.tcx.sess,
219                         scrut.span,
220                         format!("non-exhaustive patterns: {}", match missing_variants.len() {
221                             0 => format!("type `{}` is non-empty", pat_ty),
222                             1 => format!(
223                                 "pattern `{}` of type `{}` is not handled",
224                                 missing_variants[0].name,
225                                 pat_ty,
226                             ),
227                             _ => format!("multiple patterns of type `{}` are not handled", pat_ty),
228                         }),
229                     );
230                     err.help("ensure that all possible cases are being handled, \
231                               possibly by adding wildcards or more match arms");
232                     if let Some(sp) = def_span {
233                         err.span_label(sp, format!("`{}` defined here", pat_ty));
234                     }
235                     // point at the definition of non-covered enum variants
236                     for variant in &missing_variants {
237                         err.span_label(variant.span, "variant not covered");
238                     }
239                     err.emit();
240                 }
241                 // If the type *is* uninhabited, it's vacuously exhaustive
242                 return;
243             }
244
245             let matrix: Matrix<'_, '_> = inlined_arms
246                 .iter()
247                 .filter(|&&(_, guard)| guard.is_none())
248                 .flat_map(|arm| &arm.0)
249                 .map(|pat| smallvec![pat.0])
250                 .collect();
251             let scrut_ty = self.tables.node_type(scrut.hir_id);
252             check_exhaustive(cx, scrut_ty, scrut.span, &matrix);
253         })
254     }
255
256     fn check_irrefutable(&self, pat: &'tcx Pat, origin: &str) {
257         let module = self.tcx.hir().get_module_parent_by_hir_id(pat.hir_id);
258         MatchCheckCtxt::create_and_enter(self.tcx, self.param_env, module, |ref mut cx| {
259             let mut patcx = PatternContext::new(self.tcx,
260                                                 self.param_env.and(self.identity_substs),
261                                                 self.tables);
262             let pattern = patcx.lower_pattern(pat);
263             let pattern_ty = pattern.ty;
264             let pats: Matrix<'_, '_> = vec![smallvec![
265                 expand_pattern(cx, pattern)
266             ]].into_iter().collect();
267
268             let wild_pattern = Pattern {
269                 ty: pattern_ty,
270                 span: DUMMY_SP,
271                 kind: box PatternKind::Wild,
272             };
273             let witness = match is_useful(cx, &pats, &[&wild_pattern], ConstructWitness) {
274                 UsefulWithWitness(witness) => witness,
275                 NotUseful => return,
276                 Useful => bug!()
277             };
278
279             let pattern_string = witness[0].single_pattern().to_string();
280             let mut err = struct_span_err!(
281                 self.tcx.sess, pat.span, E0005,
282                 "refutable pattern in {}: `{}` not covered",
283                 origin, pattern_string
284             );
285             let label_msg = match pat.node {
286                 PatKind::Path(hir::QPath::Resolved(None, ref path))
287                         if path.segments.len() == 1 && path.segments[0].args.is_none() => {
288                     format!("interpreted as {} {} pattern, not new variable",
289                             path.res.article(), path.res.descr())
290                 }
291                 _ => format!("pattern `{}` not covered", pattern_string),
292             };
293             err.span_label(pat.span, label_msg);
294             if let ty::Adt(def, _) = pattern_ty.sty {
295                 if let Some(sp) = self.tcx.hir().span_if_local(def.did){
296                     err.span_label(sp, format!("`{}` defined here", pattern_ty));
297                 }
298             }
299             err.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.ident == ident && variant.ctor_kind == CtorKind::Const
316                     }) {
317                         let ty_path = cx.tcx.def_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(
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>(
354     cx: &mut MatchCheckCtxt<'a, 'tcx>,
355     arms: &[(Vec<(&'a Pattern<'tcx>, &hir::Pat)>, Option<&hir::Expr>)],
356     source: hir::MatchSource,
357 ) {
358     let mut seen = Matrix::empty();
359     let mut catchall = None;
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                             cx.tcx.lint_hir(
369                                 lint::builtin::IRREFUTABLE_LET_PATTERNS,
370                                 hir_pat.hir_id,
371                                 pat.span,
372                                 "irrefutable if-let pattern",
373                             );
374                         }
375
376                         hir::MatchSource::WhileLetDesugar => {
377                             // check which arm we're on.
378                             match arm_index {
379                                 // The arm with the user-specified pattern.
380                                 0 => {
381                                     cx.tcx.lint_hir(
382                                         lint::builtin::UNREACHABLE_PATTERNS,
383                                         hir_pat.hir_id, pat.span,
384                                         "unreachable pattern");
385                                 },
386                                 // The arm with the wildcard pattern.
387                                 1 => {
388                                     cx.tcx.lint_hir(
389                                         lint::builtin::IRREFUTABLE_LET_PATTERNS,
390                                         hir_pat.hir_id,
391                                         pat.span,
392                                         "irrefutable while-let pattern",
393                                     );
394                                 },
395                                 _ => bug!(),
396                             }
397                         }
398
399                         hir::MatchSource::ForLoopDesugar |
400                         hir::MatchSource::Normal => {
401                             let mut err = cx.tcx.struct_span_lint_hir(
402                                 lint::builtin::UNREACHABLE_PATTERNS,
403                                 hir_pat.hir_id,
404                                 pat.span,
405                                 "unreachable pattern",
406                             );
407                             // if we had a catchall pattern, hint at that
408                             if let Some(catchall) = catchall {
409                                 err.span_label(pat.span, "unreachable pattern");
410                                 err.span_label(catchall, "matches any value");
411                             }
412                             err.emit();
413                         }
414
415                         // Unreachable patterns in try expressions occur when one of the arms
416                         // are an uninhabited type. Which is OK.
417                         hir::MatchSource::TryDesugar => {}
418                     }
419                 }
420                 Useful => (),
421                 UsefulWithWitness(_) => bug!()
422             }
423             if guard.is_none() {
424                 seen.push(v);
425                 if catchall.is_none() && pat_is_catchall(hir_pat) {
426                     catchall = Some(pat.span);
427                 }
428             }
429         }
430     }
431 }
432
433 fn check_exhaustive<'p, 'a: 'p, 'tcx: 'a>(
434     cx: &mut MatchCheckCtxt<'a, 'tcx>,
435     scrut_ty: Ty<'tcx>,
436     sp: Span,
437     matrix: &Matrix<'p, 'tcx>,
438 ) {
439     let wild_pattern = Pattern {
440         ty: scrut_ty,
441         span: DUMMY_SP,
442         kind: box PatternKind::Wild,
443     };
444     match is_useful(cx, matrix, &[&wild_pattern], ConstructWitness) {
445         UsefulWithWitness(pats) => {
446             let witnesses = if pats.is_empty() {
447                 vec![&wild_pattern]
448             } else {
449                 pats.iter().map(|w| w.single_pattern()).collect()
450             };
451
452             const LIMIT: usize = 3;
453             let joined_patterns = match witnesses.len() {
454                 0 => bug!(),
455                 1 => format!("`{}`", witnesses[0]),
456                 2..=LIMIT => {
457                     let (tail, head) = witnesses.split_last().unwrap();
458                     let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
459                     format!("`{}` and `{}`", head.join("`, `"), tail)
460                 }
461                 _ => {
462                     let (head, tail) = witnesses.split_at(LIMIT);
463                     let head: Vec<_> = head.iter().map(|w| w.to_string()).collect();
464                     format!("`{}` and {} more", head.join("`, `"), tail.len())
465                 }
466             };
467
468             let label_text = match witnesses.len() {
469                 1 => format!("pattern {} not covered", joined_patterns),
470                 _ => format!("patterns {} not covered", joined_patterns),
471             };
472             let mut err = create_e0004(cx.tcx.sess, sp, format!(
473                 "non-exhaustive patterns: {} not covered",
474                 joined_patterns,
475             ));
476             err.span_label(sp, label_text);
477             // point at the definition of non-covered enum variants
478             if let ty::Adt(def, _) = scrut_ty.sty {
479                 if let Some(sp) = cx.tcx.hir().span_if_local(def.did){
480                     err.span_label(sp, format!("`{}` defined here", scrut_ty));
481                 }
482             }
483             let patterns = witnesses.iter().map(|p| (**p).clone()).collect::<Vec<Pattern<'_>>>();
484             if patterns.len() < 4 {
485                 for sp in maybe_point_at_variant(cx, scrut_ty, patterns.as_slice()) {
486                     err.span_label(sp, "not covered");
487                 }
488             }
489             err.help("ensure that all possible cases are being handled, \
490                       possibly by adding wildcards or more match arms");
491             err.emit();
492         }
493         NotUseful => {
494             // This is good, wildcard pattern isn't reachable
495         }
496         _ => bug!()
497     }
498 }
499
500 fn maybe_point_at_variant(
501     cx: &mut MatchCheckCtxt<'a, 'tcx>,
502     ty: Ty<'tcx>,
503     patterns: &[Pattern<'_>],
504 ) -> Vec<Span> {
505     let mut covered = vec![];
506     if let ty::Adt(def, _) = ty.sty {
507         // Don't point at variants that have already been covered due to other patterns to avoid
508         // visual clutter
509         for pattern in patterns {
510             let pk: &PatternKind<'_> = &pattern.kind;
511             if let PatternKind::Variant { adt_def, variant_index, subpatterns, .. } = pk {
512                 if adt_def.did == def.did {
513                     let sp = def.variants[*variant_index].ident.span;
514                     if covered.contains(&sp) {
515                         continue;
516                     }
517                     covered.push(sp);
518                     let subpatterns = subpatterns.iter()
519                         .map(|field_pattern| field_pattern.pattern.clone())
520                         .collect::<Vec<_>>();
521                     covered.extend(
522                         maybe_point_at_variant(cx, ty, subpatterns.as_slice()),
523                     );
524                 }
525             }
526             if let PatternKind::Leaf { subpatterns } = pk {
527                 let subpatterns = subpatterns.iter()
528                     .map(|field_pattern| field_pattern.pattern.clone())
529                     .collect::<Vec<_>>();
530                 covered.extend(maybe_point_at_variant(cx, ty, subpatterns.as_slice()));
531             }
532         }
533     }
534     covered
535 }
536
537 // Legality of move bindings checking
538 fn check_legality_of_move_bindings(
539     cx: &MatchVisitor<'_, '_>,
540     has_guard: bool,
541     pats: &[P<Pat>],
542 ) {
543     let mut by_ref_span = None;
544     for pat in pats {
545         pat.each_binding(|_, hir_id, span, _path| {
546             if let Some(&bm) = cx.tables.pat_binding_modes().get(hir_id) {
547                 if let ty::BindByReference(..) = bm {
548                     by_ref_span = Some(span);
549                 }
550             } else {
551                 cx.tcx.sess.delay_span_bug(pat.span, "missing binding mode");
552             }
553         })
554     }
555     let span_vec = &mut Vec::new();
556     let check_move = |p: &Pat, sub: Option<&Pat>, span_vec: &mut Vec<Span>| {
557         // check legality of moving out of the enum
558
559         // x @ Foo(..) is legal, but x @ Foo(y) isn't.
560         if sub.map_or(false, |p| p.contains_bindings()) {
561             struct_span_err!(cx.tcx.sess, p.span, E0007,
562                              "cannot bind by-move with sub-bindings")
563                 .span_label(p.span, "binds an already bound by-move value by moving it")
564                 .emit();
565         } else if has_guard && !cx.tcx.features().bind_by_move_pattern_guards {
566             let mut err = struct_span_err!(cx.tcx.sess, p.span, E0008,
567                                            "cannot bind by-move into a pattern guard");
568             err.span_label(p.span, "moves value into pattern guard");
569             if cx.tcx.sess.opts.unstable_features.is_nightly_build() {
570                 err.help("add #![feature(bind_by_move_pattern_guards)] to the \
571                           crate attributes to enable");
572             }
573             err.emit();
574         } else if let Some(_by_ref_span) = by_ref_span {
575             span_vec.push(p.span);
576         }
577     };
578
579     for pat in pats {
580         pat.walk(|p| {
581             if let PatKind::Binding(_, _, _, ref sub) = p.node {
582                 if let Some(&bm) = cx.tables.pat_binding_modes().get(p.hir_id) {
583                     match bm {
584                         ty::BindByValue(..) => {
585                             let pat_ty = cx.tables.node_type(p.hir_id);
586                             if !pat_ty.is_copy_modulo_regions(cx.tcx, cx.param_env, pat.span) {
587                                 check_move(p, sub.as_ref().map(|p| &**p), span_vec);
588                             }
589                         }
590                         _ => {}
591                     }
592                 } else {
593                     cx.tcx.sess.delay_span_bug(pat.span, "missing binding mode");
594                 }
595             }
596             true
597         });
598     }
599     if !span_vec.is_empty(){
600         let span = MultiSpan::from_spans(span_vec.clone());
601         let mut err = struct_span_err!(
602             cx.tcx.sess,
603             span,
604             E0009,
605             "cannot bind by-move and by-ref in the same pattern",
606         );
607         if let Some(by_ref_span) = by_ref_span {
608             err.span_label(by_ref_span, "both by-ref and by-move used");
609         }
610         for span in span_vec.iter(){
611             err.span_label(*span, "by-move pattern here");
612         }
613         err.emit();
614     }
615 }
616
617 /// Ensures that a pattern guard doesn't borrow by mutable reference or assign.
618 //
619 // FIXME: this should be done by borrowck.
620 fn check_for_mutation_in_guard(cx: &MatchVisitor<'_, '_>, guard: &hir::Guard) {
621     let mut checker = MutationChecker {
622         cx,
623     };
624     match guard {
625         hir::Guard::If(expr) =>
626             ExprUseVisitor::new(&mut checker,
627                                 cx.tcx,
628                                 cx.param_env,
629                                 cx.region_scope_tree,
630                                 cx.tables,
631                                 None).walk_expr(expr),
632     };
633 }
634
635 struct MutationChecker<'a, 'tcx: 'a> {
636     cx: &'a MatchVisitor<'a, 'tcx>,
637 }
638
639 impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> {
640     fn matched_pat(&mut self, _: &Pat, _: &cmt_<'_>, _: euv::MatchMode) {}
641     fn consume(&mut self, _: hir::HirId, _: Span, _: &cmt_<'_>, _: ConsumeMode) {}
642     fn consume_pat(&mut self, _: &Pat, _: &cmt_<'_>, _: ConsumeMode) {}
643     fn borrow(&mut self,
644               _: hir::HirId,
645               span: Span,
646               _: &cmt_<'_>,
647               _: ty::Region<'tcx>,
648               kind:ty:: BorrowKind,
649               _: LoanCause) {
650         match kind {
651             ty::MutBorrow => {
652                 let mut err = struct_span_err!(self.cx.tcx.sess, span, E0301,
653                           "cannot mutably borrow in a pattern guard");
654                 err.span_label(span, "borrowed mutably in pattern guard");
655                 if self.cx.tcx.sess.opts.unstable_features.is_nightly_build() {
656                     err.help("add #![feature(bind_by_move_pattern_guards)] to the \
657                               crate attributes to enable");
658                 }
659                 err.emit();
660             }
661             ty::ImmBorrow | ty::UniqueImmBorrow => {}
662         }
663     }
664     fn decl_without_init(&mut self, _: hir::HirId, _: Span) {}
665     fn mutate(&mut self, _: hir::HirId, span: Span, _: &cmt_<'_>, mode: MutateMode) {
666         match mode {
667             MutateMode::JustWrite | MutateMode::WriteAndRead => {
668                 struct_span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
669                     .span_label(span, "assignment in pattern guard")
670                     .emit();
671             }
672             MutateMode::Init => {}
673         }
674     }
675 }
676
677 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
678 /// because of the way rvalues are handled in the borrow check. (See issue
679 /// #14587.)
680 fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat) {
681     AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
682 }
683
684 struct AtBindingPatternVisitor<'a, 'b:'a, 'tcx:'b> {
685     cx: &'a MatchVisitor<'b, 'tcx>,
686     bindings_allowed: bool
687 }
688
689 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> {
690     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
691         NestedVisitorMap::None
692     }
693
694     fn visit_pat(&mut self, pat: &Pat) {
695         match pat.node {
696             PatKind::Binding(.., ref subpat) => {
697                 if !self.bindings_allowed {
698                     struct_span_err!(self.cx.tcx.sess, pat.span, E0303,
699                                      "pattern bindings are not allowed after an `@`")
700                         .span_label(pat.span,  "not allowed after `@`")
701                         .emit();
702                 }
703
704                 if subpat.is_some() {
705                     let bindings_were_allowed = self.bindings_allowed;
706                     self.bindings_allowed = false;
707                     intravisit::walk_pat(self, pat);
708                     self.bindings_allowed = bindings_were_allowed;
709                 }
710             }
711             _ => intravisit::walk_pat(self, pat),
712         }
713     }
714 }