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