]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir_build/hair/pattern/check_match.rs
4d97a19f4086bdff11222171efcc635fe3874f4d
[rust.git] / src / librustc_mir_build / hair / pattern / check_match.rs
1 use super::_match::Usefulness::*;
2 use super::_match::WitnessPreference::*;
3 use super::_match::{expand_pattern, is_useful, MatchCheckCtxt, Matrix, PatStack};
4 use super::{PatCtxt, PatKind, PatternError};
5
6 use rustc_arena::TypedArena;
7 use rustc_ast::ast::Mutability;
8 use rustc_errors::{error_code, struct_span_err, Applicability, DiagnosticBuilder};
9 use rustc_hir as hir;
10 use rustc_hir::def::*;
11 use rustc_hir::def_id::DefId;
12 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
13 use rustc_hir::{HirId, Pat};
14 use rustc_middle::ty::{self, Ty, TyCtxt};
15 use rustc_session::lint::builtin::BINDINGS_WITH_VARIANT_NAME;
16 use rustc_session::lint::builtin::{IRREFUTABLE_LET_PATTERNS, UNREACHABLE_PATTERNS};
17 use rustc_session::parse::feature_err;
18 use rustc_session::Session;
19 use rustc_span::{sym, Span};
20 use std::slice;
21
22 crate fn check_match(tcx: TyCtxt<'_>, def_id: DefId) {
23     let body_id = match def_id.as_local() {
24         None => return,
25         Some(id) => tcx.hir().body_owned_by(tcx.hir().as_local_hir_id(id)),
26     };
27
28     let mut visitor = MatchVisitor {
29         tcx,
30         tables: tcx.body_tables(body_id),
31         param_env: tcx.param_env(def_id),
32         pattern_arena: TypedArena::default(),
33     };
34     visitor.visit_body(tcx.hir().body(body_id));
35 }
36
37 fn create_e0004(sess: &Session, sp: Span, error_message: String) -> DiagnosticBuilder<'_> {
38     struct_span_err!(sess, sp, E0004, "{}", &error_message)
39 }
40
41 struct MatchVisitor<'a, 'tcx> {
42     tcx: TyCtxt<'tcx>,
43     tables: &'a ty::TypeckTables<'tcx>,
44     param_env: ty::ParamEnv<'tcx>,
45     pattern_arena: TypedArena<super::Pat<'tcx>>,
46 }
47
48 impl<'tcx> Visitor<'tcx> for MatchVisitor<'_, 'tcx> {
49     type Map = intravisit::ErasedMap<'tcx>;
50
51     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
52         NestedVisitorMap::None
53     }
54
55     fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
56         intravisit::walk_expr(self, ex);
57
58         if let hir::ExprKind::Match(ref scrut, ref arms, source) = ex.kind {
59             self.check_match(scrut, arms, source);
60         }
61     }
62
63     fn visit_local(&mut self, loc: &'tcx hir::Local<'tcx>) {
64         intravisit::walk_local(self, loc);
65
66         let (msg, sp) = match loc.source {
67             hir::LocalSource::Normal => ("local binding", Some(loc.span)),
68             hir::LocalSource::ForLoopDesugar => ("`for` loop binding", None),
69             hir::LocalSource::AsyncFn => ("async fn binding", None),
70             hir::LocalSource::AwaitDesugar => ("`await` future binding", None),
71         };
72         self.check_irrefutable(&loc.pat, msg, sp);
73         self.check_patterns(false, &loc.pat);
74     }
75
76     fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
77         intravisit::walk_param(self, param);
78         self.check_irrefutable(&param.pat, "function argument", None);
79         self.check_patterns(false, &param.pat);
80     }
81 }
82
83 impl PatCtxt<'_, '_> {
84     fn report_inlining_errors(&self, pat_span: Span) {
85         for error in &self.errors {
86             match *error {
87                 PatternError::StaticInPattern(span) => {
88                     self.span_e0158(span, "statics cannot be referenced in patterns")
89                 }
90                 PatternError::AssocConstInPattern(span) => {
91                     self.span_e0158(span, "associated consts cannot be referenced in patterns")
92                 }
93                 PatternError::ConstParamInPattern(span) => {
94                     self.span_e0158(span, "const parameters cannot be referenced in patterns")
95                 }
96                 PatternError::FloatBug => {
97                     // FIXME(#31407) this is only necessary because float parsing is buggy
98                     ::rustc_middle::mir::interpret::struct_error(
99                         self.tcx.at(pat_span),
100                         "could not evaluate float literal (see issue #31407)",
101                     )
102                     .emit();
103                 }
104                 PatternError::NonConstPath(span) => {
105                     ::rustc_middle::mir::interpret::struct_error(
106                         self.tcx.at(span),
107                         "runtime values cannot be referenced in patterns",
108                     )
109                     .emit();
110                 }
111             }
112         }
113     }
114
115     fn span_e0158(&self, span: Span, text: &str) {
116         struct_span_err!(self.tcx.sess, span, E0158, "{}", text).emit();
117     }
118 }
119
120 impl<'tcx> MatchVisitor<'_, 'tcx> {
121     fn check_patterns(&mut self, has_guard: bool, pat: &Pat<'_>) {
122         if !self.tcx.features().move_ref_pattern {
123             check_legality_of_move_bindings(self, has_guard, pat);
124         }
125         pat.walk_always(|pat| check_borrow_conflicts_in_at_patterns(self, pat));
126         if !self.tcx.features().bindings_after_at {
127             check_legality_of_bindings_in_at_patterns(self, pat);
128         }
129         check_for_bindings_named_same_as_variants(self, pat);
130     }
131
132     fn lower_pattern<'p>(
133         &self,
134         cx: &mut MatchCheckCtxt<'p, 'tcx>,
135         pat: &'tcx hir::Pat<'tcx>,
136         have_errors: &mut bool,
137     ) -> (&'p super::Pat<'tcx>, Ty<'tcx>) {
138         let mut patcx = PatCtxt::new(self.tcx, self.param_env, self.tables);
139         patcx.include_lint_checks();
140         let pattern = patcx.lower_pattern(pat);
141         let pattern_ty = pattern.ty;
142         let pattern: &_ = cx.pattern_arena.alloc(expand_pattern(cx, pattern));
143         if !patcx.errors.is_empty() {
144             *have_errors = true;
145             patcx.report_inlining_errors(pat.span);
146         }
147         (pattern, pattern_ty)
148     }
149
150     fn new_cx(&self, hir_id: HirId) -> MatchCheckCtxt<'_, 'tcx> {
151         MatchCheckCtxt {
152             tcx: self.tcx,
153             param_env: self.param_env,
154             module: self.tcx.parent_module(hir_id).to_def_id(),
155             pattern_arena: &self.pattern_arena,
156         }
157     }
158
159     fn check_match(
160         &mut self,
161         scrut: &hir::Expr<'_>,
162         arms: &'tcx [hir::Arm<'tcx>],
163         source: hir::MatchSource,
164     ) {
165         for arm in arms {
166             // Check the arm for some things unrelated to exhaustiveness.
167             self.check_patterns(arm.guard.is_some(), &arm.pat);
168         }
169
170         let mut cx = self.new_cx(scrut.hir_id);
171
172         let mut have_errors = false;
173
174         let inlined_arms: Vec<_> = arms
175             .iter()
176             .map(|hir::Arm { pat, guard, .. }| {
177                 (self.lower_pattern(&mut cx, pat, &mut have_errors).0, pat.hir_id, guard.is_some())
178             })
179             .collect();
180
181         // Bail out early if inlining failed.
182         if have_errors {
183             return;
184         }
185
186         // Fourth, check for unreachable arms.
187         let matrix = check_arms(&mut cx, &inlined_arms, source);
188
189         // Fifth, check if the match is exhaustive.
190         // Note: An empty match isn't the same as an empty matrix for diagnostics purposes,
191         // since an empty matrix can occur when there are arms, if those arms all have guards.
192         let scrut_ty = self.tables.expr_ty_adjusted(scrut);
193         let is_empty_match = inlined_arms.is_empty();
194         check_exhaustive(&mut cx, scrut_ty, scrut.span, &matrix, scrut.hir_id, is_empty_match);
195     }
196
197     fn check_irrefutable(&self, pat: &'tcx Pat<'tcx>, origin: &str, sp: Option<Span>) {
198         let mut cx = self.new_cx(pat.hir_id);
199
200         let (pattern, pattern_ty) = self.lower_pattern(&mut cx, pat, &mut false);
201         let pats: Matrix<'_, '_> = vec![PatStack::from_pattern(pattern)].into_iter().collect();
202
203         let witnesses = match check_not_useful(&mut cx, pattern_ty, &pats, pat.hir_id) {
204             Ok(_) => return,
205             Err(err) => err,
206         };
207
208         let joined_patterns = joined_uncovered_patterns(&witnesses);
209         let mut err = struct_span_err!(
210             self.tcx.sess,
211             pat.span,
212             E0005,
213             "refutable pattern in {}: {} not covered",
214             origin,
215             joined_patterns
216         );
217         let suggest_if_let = match &pat.kind {
218             hir::PatKind::Path(hir::QPath::Resolved(None, path))
219                 if path.segments.len() == 1 && path.segments[0].args.is_none() =>
220             {
221                 const_not_var(&mut err, cx.tcx, pat, path);
222                 false
223             }
224             _ => {
225                 err.span_label(pat.span, pattern_not_covered_label(&witnesses, &joined_patterns));
226                 true
227             }
228         };
229
230         if let (Some(span), true) = (sp, suggest_if_let) {
231             err.note(
232                 "`let` bindings require an \"irrefutable pattern\", like a `struct` or \
233                  an `enum` with only one variant",
234             );
235             if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
236                 err.span_suggestion(
237                     span,
238                     "you might want to use `if let` to ignore the variant that isn't matched",
239                     format!("if {} {{ /* */ }}", &snippet[..snippet.len() - 1]),
240                     Applicability::HasPlaceholders,
241                 );
242             }
243             err.note(
244                 "for more information, visit \
245                  https://doc.rust-lang.org/book/ch18-02-refutability.html",
246             );
247         }
248
249         adt_defined_here(&cx, &mut err, pattern_ty, &witnesses);
250         err.note(&format!("the matched value is of type `{}`", pattern_ty));
251         err.emit();
252     }
253 }
254
255 /// A path pattern was interpreted as a constant, not a new variable.
256 /// This caused an irrefutable match failure in e.g. `let`.
257 fn const_not_var(
258     err: &mut DiagnosticBuilder<'_>,
259     tcx: TyCtxt<'_>,
260     pat: &Pat<'_>,
261     path: &hir::Path<'_>,
262 ) {
263     let descr = path.res.descr();
264     err.span_label(
265         pat.span,
266         format!("interpreted as {} {} pattern, not a new variable", path.res.article(), descr,),
267     );
268
269     err.span_suggestion(
270         pat.span,
271         "introduce a variable instead",
272         format!("{}_var", path.segments[0].ident).to_lowercase(),
273         // Cannot use `MachineApplicable` as it's not really *always* correct
274         // because there may be such an identifier in scope or the user maybe
275         // really wanted to match against the constant. This is quite unlikely however.
276         Applicability::MaybeIncorrect,
277     );
278
279     if let Some(span) = tcx.hir().res_span(path.res) {
280         err.span_label(span, format!("{} defined here", descr));
281     }
282 }
283
284 fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_>) {
285     pat.walk_always(|p| {
286         if let hir::PatKind::Binding(_, _, ident, None) = p.kind {
287             if let Some(ty::BindByValue(hir::Mutability::Not)) =
288                 cx.tables.extract_binding_mode(cx.tcx.sess, p.hir_id, p.span)
289             {
290                 let pat_ty = cx.tables.pat_ty(p).peel_refs();
291                 if let ty::Adt(edef, _) = pat_ty.kind {
292                     if edef.is_enum()
293                         && edef.variants.iter().any(|variant| {
294                             variant.ident == ident && variant.ctor_kind == CtorKind::Const
295                         })
296                     {
297                         cx.tcx.struct_span_lint_hir(
298                             BINDINGS_WITH_VARIANT_NAME,
299                             p.hir_id,
300                             p.span,
301                             |lint| {
302                                 let ty_path = cx.tcx.def_path_str(edef.did);
303                                 lint.build(&format!(
304                                     "pattern binding `{}` is named the same as one \
305                                                 of the variants of the type `{}`",
306                                     ident, ty_path
307                                 ))
308                                 .code(error_code!(E0170))
309                                 .span_suggestion(
310                                     p.span,
311                                     "to match on the variant, qualify the path",
312                                     format!("{}::{}", ty_path, ident),
313                                     Applicability::MachineApplicable,
314                                 )
315                                 .emit();
316                             },
317                         )
318                     }
319                 }
320             }
321         }
322     });
323 }
324
325 /// Checks for common cases of "catchall" patterns that may not be intended as such.
326 fn pat_is_catchall(pat: &super::Pat<'_>) -> bool {
327     use super::PatKind::*;
328     match &*pat.kind {
329         Binding { subpattern: None, .. } => true,
330         Binding { subpattern: Some(s), .. } | Deref { subpattern: s } => pat_is_catchall(s),
331         Leaf { subpatterns: s } => s.iter().all(|p| pat_is_catchall(&p.pattern)),
332         _ => false,
333     }
334 }
335
336 fn unreachable_pattern(tcx: TyCtxt<'_>, span: Span, id: HirId, catchall: Option<Span>) {
337     tcx.struct_span_lint_hir(UNREACHABLE_PATTERNS, id, span, |lint| {
338         let mut err = lint.build("unreachable pattern");
339         if let Some(catchall) = catchall {
340             // We had a catchall pattern, hint at that.
341             err.span_label(span, "unreachable pattern");
342             err.span_label(catchall, "matches any value");
343         }
344         err.emit();
345     });
346 }
347
348 fn irrefutable_let_pattern(tcx: TyCtxt<'_>, span: Span, id: HirId, source: hir::MatchSource) {
349     tcx.struct_span_lint_hir(IRREFUTABLE_LET_PATTERNS, id, span, |lint| {
350         let msg = match source {
351             hir::MatchSource::IfLetDesugar { .. } => "irrefutable if-let pattern",
352             hir::MatchSource::WhileLetDesugar => "irrefutable while-let pattern",
353             _ => bug!(),
354         };
355         lint.build(msg).emit()
356     });
357 }
358
359 /// Check for unreachable patterns.
360 fn check_arms<'p, 'tcx>(
361     cx: &mut MatchCheckCtxt<'p, 'tcx>,
362     arms: &[(&'p super::Pat<'tcx>, HirId, bool)],
363     source: hir::MatchSource,
364 ) -> Matrix<'p, 'tcx> {
365     let mut seen = Matrix::empty();
366     let mut catchall = None;
367     for (arm_index, (pat, id, has_guard)) in arms.iter().copied().enumerate() {
368         let v = PatStack::from_pattern(pat);
369         match is_useful(cx, &seen, &v, LeaveOutWitness, id, has_guard, true) {
370             NotUseful => {
371                 match source {
372                     hir::MatchSource::IfDesugar { .. } | hir::MatchSource::WhileDesugar => bug!(),
373
374                     hir::MatchSource::IfLetDesugar { .. } | hir::MatchSource::WhileLetDesugar => {
375                         // Check which arm we're on.
376                         match arm_index {
377                             // The arm with the user-specified pattern.
378                             0 => unreachable_pattern(cx.tcx, pat.span, id, None),
379                             // The arm with the wildcard pattern.
380                             1 => irrefutable_let_pattern(cx.tcx, pat.span, id, source),
381                             _ => bug!(),
382                         }
383                     }
384
385                     hir::MatchSource::ForLoopDesugar | hir::MatchSource::Normal => {
386                         unreachable_pattern(cx.tcx, pat.span, id, catchall);
387                     }
388
389                     // Unreachable patterns in try and await expressions occur when one of
390                     // the arms are an uninhabited type. Which is OK.
391                     hir::MatchSource::AwaitDesugar | hir::MatchSource::TryDesugar => {}
392                 }
393             }
394             Useful(unreachable_subpatterns) => {
395                 for pat in unreachable_subpatterns {
396                     unreachable_pattern(cx.tcx, pat.span, id, None);
397                 }
398             }
399             UsefulWithWitness(_) => bug!(),
400         }
401         if !has_guard {
402             seen.push(v);
403             if catchall.is_none() && pat_is_catchall(pat) {
404                 catchall = Some(pat.span);
405             }
406         }
407     }
408     seen
409 }
410
411 fn check_not_useful<'p, 'tcx>(
412     cx: &mut MatchCheckCtxt<'p, 'tcx>,
413     ty: Ty<'tcx>,
414     matrix: &Matrix<'p, 'tcx>,
415     hir_id: HirId,
416 ) -> Result<(), Vec<super::Pat<'tcx>>> {
417     let wild_pattern = cx.pattern_arena.alloc(super::Pat::wildcard_from_ty(ty));
418     let v = PatStack::from_pattern(wild_pattern);
419
420     // false is given for `is_under_guard` argument due to the wildcard
421     // pattern not having a guard
422     match is_useful(cx, matrix, &v, ConstructWitness, hir_id, false, true) {
423         NotUseful => Ok(()), // This is good, wildcard pattern isn't reachable.
424         UsefulWithWitness(pats) => Err(if pats.is_empty() {
425             bug!("Exhaustiveness check returned no witnesses")
426         } else {
427             pats.into_iter().map(|w| w.single_pattern()).collect()
428         }),
429         Useful(_) => bug!(),
430     }
431 }
432
433 fn check_exhaustive<'p, 'tcx>(
434     cx: &mut MatchCheckCtxt<'p, 'tcx>,
435     scrut_ty: Ty<'tcx>,
436     sp: Span,
437     matrix: &Matrix<'p, 'tcx>,
438     hir_id: HirId,
439     is_empty_match: bool,
440 ) {
441     // In the absence of the `exhaustive_patterns` feature, empty matches are not detected by
442     // `is_useful` to exhaustively match uninhabited types, so we manually check here.
443     if is_empty_match && !cx.tcx.features().exhaustive_patterns {
444         let scrutinee_is_visibly_uninhabited = match scrut_ty.kind {
445             ty::Never => true,
446             ty::Adt(def, _) => {
447                 def.is_enum()
448                     && def.variants.is_empty()
449                     && !cx.is_foreign_non_exhaustive_enum(scrut_ty)
450             }
451             _ => false,
452         };
453         if scrutinee_is_visibly_uninhabited {
454             // If the type *is* uninhabited, an empty match is vacuously exhaustive.
455             return;
456         }
457     }
458
459     let witnesses = match check_not_useful(cx, scrut_ty, matrix, hir_id) {
460         Ok(_) => return,
461         Err(err) => err,
462     };
463
464     let non_empty_enum = match scrut_ty.kind {
465         ty::Adt(def, _) => def.is_enum() && !def.variants.is_empty(),
466         _ => false,
467     };
468     // In the case of an empty match, replace the '`_` not covered' diagnostic with something more
469     // informative.
470     let mut err;
471     if is_empty_match && !non_empty_enum {
472         err = create_e0004(
473             cx.tcx.sess,
474             sp,
475             format!("non-exhaustive patterns: type `{}` is non-empty", scrut_ty),
476         );
477     } else {
478         let joined_patterns = joined_uncovered_patterns(&witnesses);
479         err = create_e0004(
480             cx.tcx.sess,
481             sp,
482             format!("non-exhaustive patterns: {} not covered", joined_patterns),
483         );
484         err.span_label(sp, pattern_not_covered_label(&witnesses, &joined_patterns));
485     };
486
487     adt_defined_here(cx, &mut err, scrut_ty, &witnesses);
488     err.help(
489         "ensure that all possible cases are being handled, \
490          possibly by adding wildcards or more match arms",
491     );
492     err.note(&format!("the matched value is of type `{}`", scrut_ty));
493     err.emit();
494 }
495
496 fn joined_uncovered_patterns(witnesses: &[super::Pat<'_>]) -> String {
497     const LIMIT: usize = 3;
498     match witnesses {
499         [] => bug!(),
500         [witness] => format!("`{}`", witness),
501         [head @ .., tail] if head.len() < LIMIT => {
502             let head: Vec<_> = head.iter().map(<_>::to_string).collect();
503             format!("`{}` and `{}`", head.join("`, `"), tail)
504         }
505         _ => {
506             let (head, tail) = witnesses.split_at(LIMIT);
507             let head: Vec<_> = head.iter().map(<_>::to_string).collect();
508             format!("`{}` and {} more", head.join("`, `"), tail.len())
509         }
510     }
511 }
512
513 fn pattern_not_covered_label(witnesses: &[super::Pat<'_>], joined_patterns: &str) -> String {
514     format!("pattern{} {} not covered", rustc_errors::pluralize!(witnesses.len()), joined_patterns)
515 }
516
517 /// Point at the definition of non-covered `enum` variants.
518 fn adt_defined_here(
519     cx: &MatchCheckCtxt<'_, '_>,
520     err: &mut DiagnosticBuilder<'_>,
521     ty: Ty<'_>,
522     witnesses: &[super::Pat<'_>],
523 ) {
524     let ty = ty.peel_refs();
525     if let ty::Adt(def, _) = ty.kind {
526         if let Some(sp) = cx.tcx.hir().span_if_local(def.did) {
527             err.span_label(sp, format!("`{}` defined here", ty));
528         }
529
530         if witnesses.len() < 4 {
531             for sp in maybe_point_at_variant(ty, &witnesses) {
532                 err.span_label(sp, "not covered");
533             }
534         }
535     }
536 }
537
538 fn maybe_point_at_variant(ty: Ty<'_>, patterns: &[super::Pat<'_>]) -> Vec<Span> {
539     let mut covered = vec![];
540     if let ty::Adt(def, _) = ty.kind {
541         // Don't point at variants that have already been covered due to other patterns to avoid
542         // visual clutter.
543         for pattern in patterns {
544             use PatKind::{AscribeUserType, Deref, Leaf, Or, Variant};
545             match &*pattern.kind {
546                 AscribeUserType { subpattern, .. } | Deref { subpattern } => {
547                     covered.extend(maybe_point_at_variant(ty, slice::from_ref(&subpattern)));
548                 }
549                 Variant { adt_def, variant_index, subpatterns, .. } if adt_def.did == def.did => {
550                     let sp = def.variants[*variant_index].ident.span;
551                     if covered.contains(&sp) {
552                         continue;
553                     }
554                     covered.push(sp);
555
556                     let pats = subpatterns
557                         .iter()
558                         .map(|field_pattern| field_pattern.pattern.clone())
559                         .collect::<Box<[_]>>();
560                     covered.extend(maybe_point_at_variant(ty, &pats));
561                 }
562                 Leaf { subpatterns } => {
563                     let pats = subpatterns
564                         .iter()
565                         .map(|field_pattern| field_pattern.pattern.clone())
566                         .collect::<Box<[_]>>();
567                     covered.extend(maybe_point_at_variant(ty, &pats));
568                 }
569                 Or { pats } => {
570                     let pats = pats.iter().cloned().collect::<Box<[_]>>();
571                     covered.extend(maybe_point_at_variant(ty, &pats));
572                 }
573                 _ => {}
574             }
575         }
576     }
577     covered
578 }
579
580 /// Check if a by-value binding is by-value. That is, check if the binding's type is not `Copy`.
581 fn is_binding_by_move(cx: &MatchVisitor<'_, '_>, hir_id: HirId, span: Span) -> bool {
582     !cx.tables.node_type(hir_id).is_copy_modulo_regions(cx.tcx, cx.param_env, span)
583 }
584
585 /// Check the legality of legality of by-move bindings.
586 fn check_legality_of_move_bindings(cx: &mut MatchVisitor<'_, '_>, has_guard: bool, pat: &Pat<'_>) {
587     let sess = cx.tcx.sess;
588     let tables = cx.tables;
589
590     // Find all by-ref spans.
591     let mut by_ref_spans = Vec::new();
592     pat.each_binding(|_, hir_id, span, _| {
593         if let Some(ty::BindByReference(_)) = tables.extract_binding_mode(sess, hir_id, span) {
594             by_ref_spans.push(span);
595         }
596     });
597
598     // Find bad by-move spans:
599     let by_move_spans = &mut Vec::new();
600     let mut check_move = |p: &Pat<'_>, sub: Option<&Pat<'_>>| {
601         // Check legality of moving out of the enum.
602         //
603         // `x @ Foo(..)` is legal, but `x @ Foo(y)` isn't.
604         if sub.map_or(false, |p| p.contains_bindings()) {
605             struct_span_err!(sess, p.span, E0007, "cannot bind by-move with sub-bindings")
606                 .span_label(p.span, "binds an already bound by-move value by moving it")
607                 .emit();
608         } else if !has_guard && !by_ref_spans.is_empty() {
609             by_move_spans.push(p.span);
610         }
611     };
612     pat.walk_always(|p| {
613         if let hir::PatKind::Binding(.., sub) = &p.kind {
614             if let Some(ty::BindByValue(_)) = tables.extract_binding_mode(sess, p.hir_id, p.span) {
615                 if is_binding_by_move(cx, p.hir_id, p.span) {
616                     check_move(p, sub.as_deref());
617                 }
618             }
619         }
620     });
621
622     // Found some bad by-move spans, error!
623     if !by_move_spans.is_empty() {
624         let mut err = feature_err(
625             &sess.parse_sess,
626             sym::move_ref_pattern,
627             by_move_spans.clone(),
628             "binding by-move and by-ref in the same pattern is unstable",
629         );
630         for span in by_ref_spans.iter() {
631             err.span_label(*span, "by-ref pattern here");
632         }
633         for span in by_move_spans.iter() {
634             err.span_label(*span, "by-move pattern here");
635         }
636         err.emit();
637     }
638 }
639
640 /// Check that there are no borrow or move conflicts in `binding @ subpat` patterns.
641 ///
642 /// For example, this would reject:
643 /// - `ref x @ Some(ref mut y)`,
644 /// - `ref mut x @ Some(ref y)`,
645 /// - `ref mut x @ Some(ref mut y)`,
646 /// - `ref mut? x @ Some(y)`, and
647 /// - `x @ Some(ref mut? y)`.
648 ///
649 /// This analysis is *not* subsumed by NLL.
650 fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_>) {
651     // Extract `sub` in `binding @ sub`.
652     let (name, sub) = match &pat.kind {
653         hir::PatKind::Binding(.., name, Some(sub)) => (*name, sub),
654         _ => return,
655     };
656     let binding_span = pat.span.with_hi(name.span.hi());
657
658     let tables = cx.tables;
659     let sess = cx.tcx.sess;
660
661     // Get the binding move, extract the mutability if by-ref.
662     let mut_outer = match tables.extract_binding_mode(sess, pat.hir_id, pat.span) {
663         Some(ty::BindByValue(_)) if is_binding_by_move(cx, pat.hir_id, pat.span) => {
664             // We have `x @ pat` where `x` is by-move. Reject all borrows in `pat`.
665             let mut conflicts_ref = Vec::new();
666             sub.each_binding(|_, hir_id, span, _| {
667                 match tables.extract_binding_mode(sess, hir_id, span) {
668                     Some(ty::BindByValue(_)) | None => {}
669                     Some(ty::BindByReference(_)) => conflicts_ref.push(span),
670                 }
671             });
672             if !conflicts_ref.is_empty() {
673                 let occurs_because = format!(
674                     "move occurs because `{}` has type `{}` which does not implement the `Copy` trait",
675                     name,
676                     tables.node_type(pat.hir_id),
677                 );
678                 sess.struct_span_err(pat.span, "borrow of moved value")
679                     .span_label(binding_span, format!("value moved into `{}` here", name))
680                     .span_label(binding_span, occurs_because)
681                     .span_labels(conflicts_ref, "value borrowed here after move")
682                     .emit();
683             }
684             return;
685         }
686         Some(ty::BindByValue(_)) | None => return,
687         Some(ty::BindByReference(m)) => m,
688     };
689
690     // We now have `ref $mut_outer binding @ sub` (semantically).
691     // Recurse into each binding in `sub` and find mutability or move conflicts.
692     let mut conflicts_move = Vec::new();
693     let mut conflicts_mut_mut = Vec::new();
694     let mut conflicts_mut_ref = Vec::new();
695     sub.each_binding(|_, hir_id, span, name| {
696         match tables.extract_binding_mode(sess, hir_id, span) {
697             Some(ty::BindByReference(mut_inner)) => match (mut_outer, mut_inner) {
698                 (Mutability::Not, Mutability::Not) => {} // Both sides are `ref`.
699                 (Mutability::Mut, Mutability::Mut) => conflicts_mut_mut.push((span, name)), // 2x `ref mut`.
700                 _ => conflicts_mut_ref.push((span, name)), // `ref` + `ref mut` in either direction.
701             },
702             Some(ty::BindByValue(_)) if is_binding_by_move(cx, hir_id, span) => {
703                 conflicts_move.push((span, name)) // `ref mut?` + by-move conflict.
704             }
705             Some(ty::BindByValue(_)) | None => {} // `ref mut?` + by-copy is fine.
706         }
707     });
708
709     // Report errors if any.
710     if !conflicts_mut_mut.is_empty() {
711         // Report mutability conflicts for e.g. `ref mut x @ Some(ref mut y)`.
712         let mut err = sess
713             .struct_span_err(pat.span, "cannot borrow value as mutable more than once at a time");
714         err.span_label(binding_span, format!("first mutable borrow, by `{}`, occurs here", name));
715         for (span, name) in conflicts_mut_mut {
716             err.span_label(span, format!("another mutable borrow, by `{}`, occurs here", name));
717         }
718         for (span, name) in conflicts_mut_ref {
719             err.span_label(span, format!("also borrowed as immutable, by `{}`, here", name));
720         }
721         for (span, name) in conflicts_move {
722             err.span_label(span, format!("also moved into `{}` here", name));
723         }
724         err.emit();
725     } else if !conflicts_mut_ref.is_empty() {
726         // Report mutability conflicts for e.g. `ref x @ Some(ref mut y)` or the converse.
727         let (primary, also) = match mut_outer {
728             Mutability::Mut => ("mutable", "immutable"),
729             Mutability::Not => ("immutable", "mutable"),
730         };
731         let msg =
732             format!("cannot borrow value as {} because it is also borrowed as {}", also, primary);
733         let mut err = sess.struct_span_err(pat.span, &msg);
734         err.span_label(binding_span, format!("{} borrow, by `{}`, occurs here", primary, name));
735         for (span, name) in conflicts_mut_ref {
736             err.span_label(span, format!("{} borrow, by `{}`, occurs here", also, name));
737         }
738         for (span, name) in conflicts_move {
739             err.span_label(span, format!("also moved into `{}` here", name));
740         }
741         err.emit();
742     } else if !conflicts_move.is_empty() {
743         // Report by-ref and by-move conflicts, e.g. `ref x @ y`.
744         let mut err =
745             sess.struct_span_err(pat.span, "cannot move out of value because it is borrowed");
746         err.span_label(binding_span, format!("value borrowed, by `{}`, here", name));
747         for (span, name) in conflicts_move {
748             err.span_label(span, format!("value moved into `{}` here", name));
749         }
750         err.emit();
751     }
752 }
753
754 /// Forbids bindings in `@` patterns. This used to be is necessary for memory safety,
755 /// because of the way rvalues were handled in the borrow check. (See issue #14587.)
756 fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_>) {
757     AtBindingPatternVisitor { cx, bindings_allowed: true }.visit_pat(pat);
758
759     struct AtBindingPatternVisitor<'a, 'b, 'tcx> {
760         cx: &'a MatchVisitor<'b, 'tcx>,
761         bindings_allowed: bool,
762     }
763
764     impl<'v> Visitor<'v> for AtBindingPatternVisitor<'_, '_, '_> {
765         type Map = intravisit::ErasedMap<'v>;
766
767         fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
768             NestedVisitorMap::None
769         }
770
771         fn visit_pat(&mut self, pat: &Pat<'_>) {
772             match pat.kind {
773                 hir::PatKind::Binding(.., ref subpat) => {
774                     if !self.bindings_allowed {
775                         feature_err(
776                             &self.cx.tcx.sess.parse_sess,
777                             sym::bindings_after_at,
778                             pat.span,
779                             "pattern bindings after an `@` are unstable",
780                         )
781                         .emit();
782                     }
783
784                     if subpat.is_some() {
785                         let bindings_were_allowed = self.bindings_allowed;
786                         self.bindings_allowed = false;
787                         intravisit::walk_pat(self, pat);
788                         self.bindings_allowed = bindings_were_allowed;
789                     }
790                 }
791                 _ => intravisit::walk_pat(self, pat),
792             }
793         }
794     }
795 }