]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/thir/pattern/check_match.rs
Auto merge of #94402 - erikdesjardins:revert-coldland, r=nagisa
[rust.git] / compiler / rustc_mir_build / src / thir / pattern / check_match.rs
1 use super::deconstruct_pat::{Constructor, DeconstructedPat};
2 use super::usefulness::{
3     compute_match_usefulness, MatchArm, MatchCheckCtxt, Reachability, UsefulnessReport,
4 };
5 use super::{PatCtxt, PatternError};
6
7 use rustc_arena::TypedArena;
8 use rustc_ast::Mutability;
9 use rustc_errors::{
10     error_code, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorReported,
11 };
12 use rustc_hir as hir;
13 use rustc_hir::def::*;
14 use rustc_hir::def_id::DefId;
15 use rustc_hir::intravisit::{self, Visitor};
16 use rustc_hir::{HirId, Pat};
17 use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt};
18 use rustc_session::lint::builtin::{
19     BINDINGS_WITH_VARIANT_NAME, IRREFUTABLE_LET_PATTERNS, UNREACHABLE_PATTERNS,
20 };
21 use rustc_session::Session;
22 use rustc_span::source_map::Spanned;
23 use rustc_span::{DesugaringKind, ExpnKind, Span};
24
25 crate fn check_match(tcx: TyCtxt<'_>, def_id: DefId) {
26     let body_id = match def_id.as_local() {
27         None => return,
28         Some(id) => tcx.hir().body_owned_by(tcx.hir().local_def_id_to_hir_id(id)),
29     };
30
31     let pattern_arena = TypedArena::default();
32     let mut visitor = MatchVisitor {
33         tcx,
34         typeck_results: tcx.typeck_body(body_id),
35         param_env: tcx.param_env(def_id),
36         pattern_arena: &pattern_arena,
37     };
38     visitor.visit_body(tcx.hir().body(body_id));
39 }
40
41 fn create_e0004(
42     sess: &Session,
43     sp: Span,
44     error_message: String,
45 ) -> DiagnosticBuilder<'_, ErrorReported> {
46     struct_span_err!(sess, sp, E0004, "{}", &error_message)
47 }
48
49 #[derive(PartialEq)]
50 enum RefutableFlag {
51     Irrefutable,
52     Refutable,
53 }
54 use RefutableFlag::*;
55
56 struct MatchVisitor<'a, 'p, 'tcx> {
57     tcx: TyCtxt<'tcx>,
58     typeck_results: &'a ty::TypeckResults<'tcx>,
59     param_env: ty::ParamEnv<'tcx>,
60     pattern_arena: &'p TypedArena<DeconstructedPat<'p, 'tcx>>,
61 }
62
63 impl<'tcx> Visitor<'tcx> for MatchVisitor<'_, '_, 'tcx> {
64     fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
65         intravisit::walk_expr(self, ex);
66         match &ex.kind {
67             hir::ExprKind::Match(scrut, arms, source) => self.check_match(scrut, arms, *source),
68             hir::ExprKind::Let(hir::Let { pat, init, span, .. }) => {
69                 self.check_let(pat, init, *span)
70             }
71             _ => {}
72         }
73     }
74
75     fn visit_local(&mut self, loc: &'tcx hir::Local<'tcx>) {
76         intravisit::walk_local(self, loc);
77
78         let (msg, sp) = match loc.source {
79             hir::LocalSource::Normal => ("local binding", Some(loc.span)),
80             hir::LocalSource::AsyncFn => ("async fn binding", None),
81             hir::LocalSource::AwaitDesugar => ("`await` future binding", None),
82             hir::LocalSource::AssignDesugar(_) => ("destructuring assignment binding", None),
83         };
84         self.check_irrefutable(&loc.pat, msg, sp);
85     }
86
87     fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
88         intravisit::walk_param(self, param);
89         self.check_irrefutable(&param.pat, "function argument", None);
90     }
91 }
92
93 impl PatCtxt<'_, '_> {
94     fn report_inlining_errors(&self) {
95         for error in &self.errors {
96             match *error {
97                 PatternError::StaticInPattern(span) => {
98                     self.span_e0158(span, "statics cannot be referenced in patterns")
99                 }
100                 PatternError::AssocConstInPattern(span) => {
101                     self.span_e0158(span, "associated consts cannot be referenced in patterns")
102                 }
103                 PatternError::ConstParamInPattern(span) => {
104                     self.span_e0158(span, "const parameters cannot be referenced in patterns")
105                 }
106                 PatternError::NonConstPath(span) => {
107                     rustc_middle::mir::interpret::struct_error(
108                         self.tcx.at(span),
109                         "runtime values cannot be referenced in patterns",
110                     )
111                     .emit();
112                 }
113             }
114         }
115     }
116
117     fn span_e0158(&self, span: Span, text: &str) {
118         struct_span_err!(self.tcx.sess, span, E0158, "{}", text).emit();
119     }
120 }
121
122 impl<'p, 'tcx> MatchVisitor<'_, 'p, 'tcx> {
123     fn check_patterns(&self, pat: &Pat<'_>, rf: RefutableFlag) {
124         pat.walk_always(|pat| check_borrow_conflicts_in_at_patterns(self, pat));
125         check_for_bindings_named_same_as_variants(self, pat, rf);
126     }
127
128     fn lower_pattern(
129         &self,
130         cx: &mut MatchCheckCtxt<'p, 'tcx>,
131         pat: &'tcx hir::Pat<'tcx>,
132         have_errors: &mut bool,
133     ) -> &'p DeconstructedPat<'p, 'tcx> {
134         let mut patcx = PatCtxt::new(self.tcx, self.param_env, self.typeck_results);
135         patcx.include_lint_checks();
136         let pattern = patcx.lower_pattern(pat);
137         let pattern: &_ = cx.pattern_arena.alloc(DeconstructedPat::from_pat(cx, &pattern));
138         if !patcx.errors.is_empty() {
139             *have_errors = true;
140             patcx.report_inlining_errors();
141         }
142         pattern
143     }
144
145     fn new_cx(&self, hir_id: HirId) -> MatchCheckCtxt<'p, 'tcx> {
146         MatchCheckCtxt {
147             tcx: self.tcx,
148             param_env: self.param_env,
149             module: self.tcx.parent_module(hir_id).to_def_id(),
150             pattern_arena: &self.pattern_arena,
151         }
152     }
153
154     fn check_let(&mut self, pat: &'tcx hir::Pat<'tcx>, scrutinee: &hir::Expr<'_>, span: Span) {
155         self.check_patterns(pat, Refutable);
156         let mut cx = self.new_cx(scrutinee.hir_id);
157         let tpat = self.lower_pattern(&mut cx, pat, &mut false);
158         check_let_reachability(&mut cx, pat.hir_id, tpat, span);
159     }
160
161     fn check_match(
162         &mut self,
163         scrut: &hir::Expr<'_>,
164         hir_arms: &'tcx [hir::Arm<'tcx>],
165         source: hir::MatchSource,
166     ) {
167         let mut cx = self.new_cx(scrut.hir_id);
168
169         for arm in hir_arms {
170             // Check the arm for some things unrelated to exhaustiveness.
171             self.check_patterns(&arm.pat, Refutable);
172             if let Some(hir::Guard::IfLet(ref pat, _)) = arm.guard {
173                 self.check_patterns(pat, Refutable);
174                 let tpat = self.lower_pattern(&mut cx, pat, &mut false);
175                 check_let_reachability(&mut cx, pat.hir_id, tpat, tpat.span());
176             }
177         }
178
179         let mut have_errors = false;
180
181         let arms: Vec<_> = hir_arms
182             .iter()
183             .map(|hir::Arm { pat, guard, .. }| MatchArm {
184                 pat: self.lower_pattern(&mut cx, pat, &mut have_errors),
185                 hir_id: pat.hir_id,
186                 has_guard: guard.is_some(),
187             })
188             .collect();
189
190         // Bail out early if lowering failed.
191         if have_errors {
192             return;
193         }
194
195         let scrut_ty = self.typeck_results.expr_ty_adjusted(scrut);
196         let report = compute_match_usefulness(&cx, &arms, scrut.hir_id, scrut_ty);
197
198         match source {
199             // Don't report arm reachability of desugared `match $iter.into_iter() { iter => .. }`
200             // when the iterator is an uninhabited type. unreachable_code will trigger instead.
201             hir::MatchSource::ForLoopDesugar if arms.len() == 1 => {}
202             hir::MatchSource::ForLoopDesugar | hir::MatchSource::Normal => {
203                 report_arm_reachability(&cx, &report)
204             }
205             // Unreachable patterns in try and await expressions occur when one of
206             // the arms are an uninhabited type. Which is OK.
207             hir::MatchSource::AwaitDesugar | hir::MatchSource::TryDesugar => {}
208         }
209
210         // Check if the match is exhaustive.
211         let is_empty_match = arms.is_empty();
212         let witnesses = report.non_exhaustiveness_witnesses;
213         if !witnesses.is_empty() {
214             if source == hir::MatchSource::ForLoopDesugar && hir_arms.len() == 2 {
215                 // the for loop pattern is not irrefutable
216                 let pat = hir_arms[1].pat.for_loop_some().unwrap();
217                 self.check_irrefutable(pat, "`for` loop binding", None);
218             } else {
219                 non_exhaustive_match(&cx, scrut_ty, scrut.span, witnesses, is_empty_match);
220             }
221         }
222     }
223
224     fn check_irrefutable(&self, pat: &'tcx Pat<'tcx>, origin: &str, sp: Option<Span>) {
225         let mut cx = self.new_cx(pat.hir_id);
226
227         let pattern = self.lower_pattern(&mut cx, pat, &mut false);
228         let pattern_ty = pattern.ty();
229         let arms = vec![MatchArm { pat: pattern, hir_id: pat.hir_id, has_guard: false }];
230         let report = compute_match_usefulness(&cx, &arms, pat.hir_id, pattern_ty);
231
232         // Note: we ignore whether the pattern is unreachable (i.e. whether the type is empty). We
233         // only care about exhaustiveness here.
234         let witnesses = report.non_exhaustiveness_witnesses;
235         if witnesses.is_empty() {
236             // The pattern is irrefutable.
237             self.check_patterns(pat, Irrefutable);
238             return;
239         }
240
241         let joined_patterns = joined_uncovered_patterns(&cx, &witnesses);
242         let mut err = struct_span_err!(
243             self.tcx.sess,
244             pat.span,
245             E0005,
246             "refutable pattern in {}: {} not covered",
247             origin,
248             joined_patterns
249         );
250         let suggest_if_let = match &pat.kind {
251             hir::PatKind::Path(hir::QPath::Resolved(None, path))
252                 if path.segments.len() == 1 && path.segments[0].args.is_none() =>
253             {
254                 const_not_var(&mut err, cx.tcx, pat, path);
255                 false
256             }
257             _ => {
258                 err.span_label(pat.span, pattern_not_covered_label(&witnesses, &joined_patterns));
259                 true
260             }
261         };
262
263         if let (Some(span), true) = (sp, suggest_if_let) {
264             err.note(
265                 "`let` bindings require an \"irrefutable pattern\", like a `struct` or \
266                  an `enum` with only one variant",
267             );
268             if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
269                 err.span_suggestion(
270                     span,
271                     "you might want to use `if let` to ignore the variant that isn't matched",
272                     format!("if {} {{ /* */ }}", &snippet[..snippet.len() - 1]),
273                     Applicability::HasPlaceholders,
274                 );
275             }
276             err.note(
277                 "for more information, visit \
278                  https://doc.rust-lang.org/book/ch18-02-refutability.html",
279             );
280         }
281
282         adt_defined_here(&cx, &mut err, pattern_ty, &witnesses);
283         err.note(&format!("the matched value is of type `{}`", pattern_ty));
284         err.emit();
285     }
286 }
287
288 /// A path pattern was interpreted as a constant, not a new variable.
289 /// This caused an irrefutable match failure in e.g. `let`.
290 fn const_not_var(err: &mut Diagnostic, tcx: TyCtxt<'_>, pat: &Pat<'_>, path: &hir::Path<'_>) {
291     let descr = path.res.descr();
292     err.span_label(
293         pat.span,
294         format!("interpreted as {} {} pattern, not a new variable", path.res.article(), descr,),
295     );
296
297     err.span_suggestion(
298         pat.span,
299         "introduce a variable instead",
300         format!("{}_var", path.segments[0].ident).to_lowercase(),
301         // Cannot use `MachineApplicable` as it's not really *always* correct
302         // because there may be such an identifier in scope or the user maybe
303         // really wanted to match against the constant. This is quite unlikely however.
304         Applicability::MaybeIncorrect,
305     );
306
307     if let Some(span) = tcx.hir().res_span(path.res) {
308         err.span_label(span, format!("{} defined here", descr));
309     }
310 }
311
312 fn check_for_bindings_named_same_as_variants(
313     cx: &MatchVisitor<'_, '_, '_>,
314     pat: &Pat<'_>,
315     rf: RefutableFlag,
316 ) {
317     pat.walk_always(|p| {
318         if let hir::PatKind::Binding(_, _, ident, None) = p.kind {
319             if let Some(ty::BindByValue(hir::Mutability::Not)) =
320                 cx.typeck_results.extract_binding_mode(cx.tcx.sess, p.hir_id, p.span)
321             {
322                 let pat_ty = cx.typeck_results.pat_ty(p).peel_refs();
323                 if let ty::Adt(edef, _) = pat_ty.kind() {
324                     if edef.is_enum()
325                         && edef.variants.iter().any(|variant| {
326                             variant.ident(cx.tcx) == ident && variant.ctor_kind == CtorKind::Const
327                         })
328                     {
329                         let variant_count = edef.variants.len();
330                         cx.tcx.struct_span_lint_hir(
331                             BINDINGS_WITH_VARIANT_NAME,
332                             p.hir_id,
333                             p.span,
334                             |lint| {
335                                 let ty_path = cx.tcx.def_path_str(edef.did);
336                                 let mut err = lint.build(&format!(
337                                     "pattern binding `{}` is named the same as one \
338                                                     of the variants of the type `{}`",
339                                     ident, ty_path
340                                 ));
341                                 err.code(error_code!(E0170));
342                                 // If this is an irrefutable pattern, and there's > 1 variant,
343                                 // then we can't actually match on this. Applying the below
344                                 // suggestion would produce code that breaks on `check_irrefutable`.
345                                 if rf == Refutable || variant_count == 1 {
346                                     err.span_suggestion(
347                                         p.span,
348                                         "to match on the variant, qualify the path",
349                                         format!("{}::{}", ty_path, ident),
350                                         Applicability::MachineApplicable,
351                                     );
352                                 }
353                                 err.emit();
354                             },
355                         )
356                     }
357                 }
358             }
359         }
360     });
361 }
362
363 /// Checks for common cases of "catchall" patterns that may not be intended as such.
364 fn pat_is_catchall(pat: &DeconstructedPat<'_, '_>) -> bool {
365     use Constructor::*;
366     match pat.ctor() {
367         Wildcard => true,
368         Single => pat.iter_fields().all(|pat| pat_is_catchall(pat)),
369         _ => false,
370     }
371 }
372
373 fn unreachable_pattern(tcx: TyCtxt<'_>, span: Span, id: HirId, catchall: Option<Span>) {
374     tcx.struct_span_lint_hir(UNREACHABLE_PATTERNS, id, span, |lint| {
375         let mut err = lint.build("unreachable pattern");
376         if let Some(catchall) = catchall {
377             // We had a catchall pattern, hint at that.
378             err.span_label(span, "unreachable pattern");
379             err.span_label(catchall, "matches any value");
380         }
381         err.emit();
382     });
383 }
384
385 fn irrefutable_let_pattern(tcx: TyCtxt<'_>, id: HirId, span: Span) {
386     macro_rules! emit_diag {
387         (
388             $lint:expr,
389             $source_name:expr,
390             $note_sufix:expr,
391             $help_sufix:expr
392         ) => {{
393             let mut diag = $lint.build(concat!("irrefutable ", $source_name, " pattern"));
394             diag.note(concat!("this pattern will always match, so the ", $note_sufix));
395             diag.help(concat!("consider ", $help_sufix));
396             diag.emit()
397         }};
398     }
399
400     let source = let_source(tcx, id);
401     let span = match source {
402         LetSource::LetElse(span) => span,
403         _ => span,
404     };
405     tcx.struct_span_lint_hir(IRREFUTABLE_LET_PATTERNS, id, span, |lint| match source {
406         LetSource::GenericLet => {
407             emit_diag!(lint, "`let`", "`let` is useless", "removing `let`");
408         }
409         LetSource::IfLet => {
410             emit_diag!(
411                 lint,
412                 "`if let`",
413                 "`if let` is useless",
414                 "replacing the `if let` with a `let`"
415             );
416         }
417         LetSource::IfLetGuard => {
418             emit_diag!(
419                 lint,
420                 "`if let` guard",
421                 "guard is useless",
422                 "removing the guard and adding a `let` inside the match arm"
423             );
424         }
425         LetSource::LetElse(..) => {
426             emit_diag!(
427                 lint,
428                 "`let...else`",
429                 "`else` clause is useless",
430                 "removing the `else` clause"
431             );
432         }
433         LetSource::WhileLet => {
434             emit_diag!(
435                 lint,
436                 "`while let`",
437                 "loop will never exit",
438                 "instead using a `loop { ... }` with a `let` inside it"
439             );
440         }
441     });
442 }
443
444 fn check_let_reachability<'p, 'tcx>(
445     cx: &mut MatchCheckCtxt<'p, 'tcx>,
446     pat_id: HirId,
447     pat: &'p DeconstructedPat<'p, 'tcx>,
448     span: Span,
449 ) {
450     if is_let_chain(cx.tcx, pat_id) {
451         return;
452     }
453
454     let arms = [MatchArm { pat, hir_id: pat_id, has_guard: false }];
455     let report = compute_match_usefulness(&cx, &arms, pat_id, pat.ty());
456
457     // Report if the pattern is unreachable, which can only occur when the type is uninhabited.
458     // This also reports unreachable sub-patterns though, so we can't just replace it with an
459     // `is_uninhabited` check.
460     report_arm_reachability(&cx, &report);
461
462     if report.non_exhaustiveness_witnesses.is_empty() {
463         // The match is exhaustive, i.e. the `if let` pattern is irrefutable.
464         irrefutable_let_pattern(cx.tcx, pat_id, span);
465     }
466 }
467
468 /// Report unreachable arms, if any.
469 fn report_arm_reachability<'p, 'tcx>(
470     cx: &MatchCheckCtxt<'p, 'tcx>,
471     report: &UsefulnessReport<'p, 'tcx>,
472 ) {
473     use Reachability::*;
474     let mut catchall = None;
475     for (arm, is_useful) in report.arm_usefulness.iter() {
476         match is_useful {
477             Unreachable => unreachable_pattern(cx.tcx, arm.pat.span(), arm.hir_id, catchall),
478             Reachable(unreachables) if unreachables.is_empty() => {}
479             // The arm is reachable, but contains unreachable subpatterns (from or-patterns).
480             Reachable(unreachables) => {
481                 let mut unreachables = unreachables.clone();
482                 // Emit lints in the order in which they occur in the file.
483                 unreachables.sort_unstable();
484                 for span in unreachables {
485                     unreachable_pattern(cx.tcx, span, arm.hir_id, None);
486                 }
487             }
488         }
489         if !arm.has_guard && catchall.is_none() && pat_is_catchall(arm.pat) {
490             catchall = Some(arm.pat.span());
491         }
492     }
493 }
494
495 /// Report that a match is not exhaustive.
496 fn non_exhaustive_match<'p, 'tcx>(
497     cx: &MatchCheckCtxt<'p, 'tcx>,
498     scrut_ty: Ty<'tcx>,
499     sp: Span,
500     witnesses: Vec<DeconstructedPat<'p, 'tcx>>,
501     is_empty_match: bool,
502 ) {
503     let non_empty_enum = match scrut_ty.kind() {
504         ty::Adt(def, _) => def.is_enum() && !def.variants.is_empty(),
505         _ => false,
506     };
507     // In the case of an empty match, replace the '`_` not covered' diagnostic with something more
508     // informative.
509     let mut err;
510     if is_empty_match && !non_empty_enum {
511         err = create_e0004(
512             cx.tcx.sess,
513             sp,
514             format!("non-exhaustive patterns: type `{}` is non-empty", scrut_ty),
515         );
516     } else {
517         let joined_patterns = joined_uncovered_patterns(cx, &witnesses);
518         err = create_e0004(
519             cx.tcx.sess,
520             sp,
521             format!("non-exhaustive patterns: {} not covered", joined_patterns),
522         );
523         err.span_label(sp, pattern_not_covered_label(&witnesses, &joined_patterns));
524     };
525
526     let is_variant_list_non_exhaustive = match scrut_ty.kind() {
527         ty::Adt(def, _) if def.is_variant_list_non_exhaustive() && !def.did.is_local() => true,
528         _ => false,
529     };
530
531     adt_defined_here(cx, &mut err, scrut_ty, &witnesses);
532     err.help(
533         "ensure that all possible cases are being handled, \
534               possibly by adding wildcards or more match arms",
535     );
536     err.note(&format!(
537         "the matched value is of type `{}`{}",
538         scrut_ty,
539         if is_variant_list_non_exhaustive { ", which is marked as non-exhaustive" } else { "" }
540     ));
541     if (scrut_ty == cx.tcx.types.usize || scrut_ty == cx.tcx.types.isize)
542         && !is_empty_match
543         && witnesses.len() == 1
544         && matches!(witnesses[0].ctor(), Constructor::NonExhaustive)
545     {
546         err.note(&format!(
547             "`{}` does not have a fixed maximum value, \
548                 so a wildcard `_` is necessary to match exhaustively",
549             scrut_ty,
550         ));
551         if cx.tcx.sess.is_nightly_build() {
552             err.help(&format!(
553                 "add `#![feature(precise_pointer_size_matching)]` \
554                     to the crate attributes to enable precise `{}` matching",
555                 scrut_ty,
556             ));
557         }
558     }
559     if let ty::Ref(_, sub_ty, _) = scrut_ty.kind() {
560         if cx.tcx.is_ty_uninhabited_from(cx.module, *sub_ty, cx.param_env) {
561             err.note("references are always considered inhabited");
562         }
563     }
564     err.emit();
565 }
566
567 crate fn joined_uncovered_patterns<'p, 'tcx>(
568     cx: &MatchCheckCtxt<'p, 'tcx>,
569     witnesses: &[DeconstructedPat<'p, 'tcx>],
570 ) -> String {
571     const LIMIT: usize = 3;
572     let pat_to_str = |pat: &DeconstructedPat<'p, 'tcx>| pat.to_pat(cx).to_string();
573     match witnesses {
574         [] => bug!(),
575         [witness] => format!("`{}`", witness.to_pat(cx)),
576         [head @ .., tail] if head.len() < LIMIT => {
577             let head: Vec<_> = head.iter().map(pat_to_str).collect();
578             format!("`{}` and `{}`", head.join("`, `"), tail.to_pat(cx))
579         }
580         _ => {
581             let (head, tail) = witnesses.split_at(LIMIT);
582             let head: Vec<_> = head.iter().map(pat_to_str).collect();
583             format!("`{}` and {} more", head.join("`, `"), tail.len())
584         }
585     }
586 }
587
588 crate fn pattern_not_covered_label(
589     witnesses: &[DeconstructedPat<'_, '_>],
590     joined_patterns: &str,
591 ) -> String {
592     format!("pattern{} {} not covered", rustc_errors::pluralize!(witnesses.len()), joined_patterns)
593 }
594
595 /// Point at the definition of non-covered `enum` variants.
596 fn adt_defined_here<'p, 'tcx>(
597     cx: &MatchCheckCtxt<'p, 'tcx>,
598     err: &mut Diagnostic,
599     ty: Ty<'tcx>,
600     witnesses: &[DeconstructedPat<'p, 'tcx>],
601 ) {
602     let ty = ty.peel_refs();
603     if let ty::Adt(def, _) = ty.kind() {
604         if let Some(sp) = cx.tcx.hir().span_if_local(def.did) {
605             err.span_label(sp, format!("`{}` defined here", ty));
606         }
607
608         if witnesses.len() < 4 {
609             for sp in maybe_point_at_variant(cx, def, witnesses.iter()) {
610                 err.span_label(sp, "not covered");
611             }
612         }
613     }
614 }
615
616 fn maybe_point_at_variant<'a, 'p: 'a, 'tcx: 'a>(
617     cx: &MatchCheckCtxt<'p, 'tcx>,
618     def: &AdtDef,
619     patterns: impl Iterator<Item = &'a DeconstructedPat<'p, 'tcx>>,
620 ) -> Vec<Span> {
621     use Constructor::*;
622     let mut covered = vec![];
623     for pattern in patterns {
624         if let Variant(variant_index) = pattern.ctor() {
625             if let ty::Adt(this_def, _) = pattern.ty().kind() {
626                 if this_def.did != def.did {
627                     continue;
628                 }
629             }
630             let sp = def.variants[*variant_index].ident(cx.tcx).span;
631             if covered.contains(&sp) {
632                 // Don't point at variants that have already been covered due to other patterns to avoid
633                 // visual clutter.
634                 continue;
635             }
636             covered.push(sp);
637         }
638         covered.extend(maybe_point_at_variant(cx, def, pattern.iter_fields()));
639     }
640     covered
641 }
642
643 /// Check if a by-value binding is by-value. That is, check if the binding's type is not `Copy`.
644 fn is_binding_by_move(cx: &MatchVisitor<'_, '_, '_>, hir_id: HirId, span: Span) -> bool {
645     !cx.typeck_results.node_type(hir_id).is_copy_modulo_regions(cx.tcx.at(span), cx.param_env)
646 }
647
648 /// Check that there are no borrow or move conflicts in `binding @ subpat` patterns.
649 ///
650 /// For example, this would reject:
651 /// - `ref x @ Some(ref mut y)`,
652 /// - `ref mut x @ Some(ref y)`,
653 /// - `ref mut x @ Some(ref mut y)`,
654 /// - `ref mut? x @ Some(y)`, and
655 /// - `x @ Some(ref mut? y)`.
656 ///
657 /// This analysis is *not* subsumed by NLL.
658 fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_, '_>, pat: &Pat<'_>) {
659     // Extract `sub` in `binding @ sub`.
660     let (name, sub) = match &pat.kind {
661         hir::PatKind::Binding(.., name, Some(sub)) => (*name, sub),
662         _ => return,
663     };
664     let binding_span = pat.span.with_hi(name.span.hi());
665
666     let typeck_results = cx.typeck_results;
667     let sess = cx.tcx.sess;
668
669     // Get the binding move, extract the mutability if by-ref.
670     let mut_outer = match typeck_results.extract_binding_mode(sess, pat.hir_id, pat.span) {
671         Some(ty::BindByValue(_)) if is_binding_by_move(cx, pat.hir_id, pat.span) => {
672             // We have `x @ pat` where `x` is by-move. Reject all borrows in `pat`.
673             let mut conflicts_ref = Vec::new();
674             sub.each_binding(|_, hir_id, span, _| {
675                 match typeck_results.extract_binding_mode(sess, hir_id, span) {
676                     Some(ty::BindByValue(_)) | None => {}
677                     Some(ty::BindByReference(_)) => conflicts_ref.push(span),
678                 }
679             });
680             if !conflicts_ref.is_empty() {
681                 let occurs_because = format!(
682                     "move occurs because `{}` has type `{}` which does not implement the `Copy` trait",
683                     name,
684                     typeck_results.node_type(pat.hir_id),
685                 );
686                 sess.struct_span_err(pat.span, "borrow of moved value")
687                     .span_label(binding_span, format!("value moved into `{}` here", name))
688                     .span_label(binding_span, occurs_because)
689                     .span_labels(conflicts_ref, "value borrowed here after move")
690                     .emit();
691             }
692             return;
693         }
694         Some(ty::BindByValue(_)) | None => return,
695         Some(ty::BindByReference(m)) => m,
696     };
697
698     // We now have `ref $mut_outer binding @ sub` (semantically).
699     // Recurse into each binding in `sub` and find mutability or move conflicts.
700     let mut conflicts_move = Vec::new();
701     let mut conflicts_mut_mut = Vec::new();
702     let mut conflicts_mut_ref = Vec::new();
703     sub.each_binding(|_, hir_id, span, name| {
704         match typeck_results.extract_binding_mode(sess, hir_id, span) {
705             Some(ty::BindByReference(mut_inner)) => match (mut_outer, mut_inner) {
706                 (Mutability::Not, Mutability::Not) => {} // Both sides are `ref`.
707                 (Mutability::Mut, Mutability::Mut) => conflicts_mut_mut.push((span, name)), // 2x `ref mut`.
708                 _ => conflicts_mut_ref.push((span, name)), // `ref` + `ref mut` in either direction.
709             },
710             Some(ty::BindByValue(_)) if is_binding_by_move(cx, hir_id, span) => {
711                 conflicts_move.push((span, name)) // `ref mut?` + by-move conflict.
712             }
713             Some(ty::BindByValue(_)) | None => {} // `ref mut?` + by-copy is fine.
714         }
715     });
716
717     // Report errors if any.
718     if !conflicts_mut_mut.is_empty() {
719         // Report mutability conflicts for e.g. `ref mut x @ Some(ref mut y)`.
720         let mut err = sess
721             .struct_span_err(pat.span, "cannot borrow value as mutable more than once at a time");
722         err.span_label(binding_span, format!("first mutable borrow, by `{}`, occurs here", name));
723         for (span, name) in conflicts_mut_mut {
724             err.span_label(span, format!("another mutable borrow, by `{}`, occurs here", name));
725         }
726         for (span, name) in conflicts_mut_ref {
727             err.span_label(span, format!("also borrowed as immutable, by `{}`, here", name));
728         }
729         for (span, name) in conflicts_move {
730             err.span_label(span, format!("also moved into `{}` here", name));
731         }
732         err.emit();
733     } else if !conflicts_mut_ref.is_empty() {
734         // Report mutability conflicts for e.g. `ref x @ Some(ref mut y)` or the converse.
735         let (primary, also) = match mut_outer {
736             Mutability::Mut => ("mutable", "immutable"),
737             Mutability::Not => ("immutable", "mutable"),
738         };
739         let msg =
740             format!("cannot borrow value as {} because it is also borrowed as {}", also, primary);
741         let mut err = sess.struct_span_err(pat.span, &msg);
742         err.span_label(binding_span, format!("{} borrow, by `{}`, occurs here", primary, name));
743         for (span, name) in conflicts_mut_ref {
744             err.span_label(span, format!("{} borrow, by `{}`, occurs here", also, name));
745         }
746         for (span, name) in conflicts_move {
747             err.span_label(span, format!("also moved into `{}` here", name));
748         }
749         err.emit();
750     } else if !conflicts_move.is_empty() {
751         // Report by-ref and by-move conflicts, e.g. `ref x @ y`.
752         let mut err =
753             sess.struct_span_err(pat.span, "cannot move out of value because it is borrowed");
754         err.span_label(binding_span, format!("value borrowed, by `{}`, here", name));
755         for (span, name) in conflicts_move {
756             err.span_label(span, format!("value moved into `{}` here", name));
757         }
758         err.emit();
759     }
760 }
761
762 #[derive(Clone, Copy, Debug)]
763 pub enum LetSource {
764     GenericLet,
765     IfLet,
766     IfLetGuard,
767     LetElse(Span),
768     WhileLet,
769 }
770
771 fn let_source(tcx: TyCtxt<'_>, pat_id: HirId) -> LetSource {
772     let hir = tcx.hir();
773
774     let parent = hir.get_parent_node(pat_id);
775     let parent_node = hir.get(parent);
776
777     match parent_node {
778         hir::Node::Arm(hir::Arm {
779             guard: Some(hir::Guard::IfLet(&hir::Pat { hir_id, .. }, _)),
780             ..
781         }) if hir_id == pat_id => {
782             return LetSource::IfLetGuard;
783         }
784         hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Let(..), span, .. }) => {
785             let expn_data = span.ctxt().outer_expn_data();
786             if let ExpnKind::Desugaring(DesugaringKind::LetElse) = expn_data.kind {
787                 return LetSource::LetElse(expn_data.call_site);
788             }
789         }
790         _ => {}
791     }
792
793     let parent_parent = hir.get_parent_node(parent);
794     let parent_parent_node = hir.get(parent_parent);
795
796     let parent_parent_parent = hir.get_parent_node(parent_parent);
797     let parent_parent_parent_parent = hir.get_parent_node(parent_parent_parent);
798     let parent_parent_parent_parent_node = hir.get(parent_parent_parent_parent);
799
800     if let hir::Node::Expr(hir::Expr {
801         kind: hir::ExprKind::Loop(_, _, hir::LoopSource::While, _),
802         ..
803     }) = parent_parent_parent_parent_node
804     {
805         return LetSource::WhileLet;
806     }
807
808     if let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::If(..), .. }) = parent_parent_node {
809         return LetSource::IfLet;
810     }
811
812     LetSource::GenericLet
813 }
814
815 // Since this function is called within a let context, it is reasonable to assume that any parent
816 // `&&` infers a let chain
817 fn is_let_chain(tcx: TyCtxt<'_>, pat_id: HirId) -> bool {
818     let hir = tcx.hir();
819     let parent = hir.get_parent_node(pat_id);
820     let parent_parent = hir.get_parent_node(parent);
821     matches!(
822         hir.get(parent_parent),
823         hir::Node::Expr(
824             hir::Expr {
825                 kind: hir::ExprKind::Binary(Spanned { node: hir::BinOpKind::And, .. }, ..),
826                 ..
827             },
828             ..
829         )
830     )
831 }