]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/thir/pattern/check_match.rs
Rollup merge of #99651 - compiler-errors:fn-and-raw-ptr-in-const-generics, r=oli-obk
[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, pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder,
11     ErrorGuaranteed, MultiSpan,
12 };
13 use rustc_hir as hir;
14 use rustc_hir::def::*;
15 use rustc_hir::def_id::DefId;
16 use rustc_hir::intravisit::{self, Visitor};
17 use rustc_hir::{HirId, Pat};
18 use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt};
19 use rustc_session::lint::builtin::{
20     BINDINGS_WITH_VARIANT_NAME, IRREFUTABLE_LET_PATTERNS, UNREACHABLE_PATTERNS,
21 };
22 use rustc_session::Session;
23 use rustc_span::source_map::Spanned;
24 use rustc_span::{BytePos, Span};
25
26 pub(crate) fn check_match(tcx: TyCtxt<'_>, def_id: DefId) {
27     let body_id = match def_id.as_local() {
28         None => return,
29         Some(id) => tcx.hir().body_owned_by(tcx.hir().local_def_id_to_hir_id(id)),
30     };
31
32     let pattern_arena = TypedArena::default();
33     let mut visitor = MatchVisitor {
34         tcx,
35         typeck_results: tcx.typeck_body(body_id),
36         param_env: tcx.param_env(def_id),
37         pattern_arena: &pattern_arena,
38     };
39     visitor.visit_body(tcx.hir().body(body_id));
40 }
41
42 fn create_e0004(
43     sess: &Session,
44     sp: Span,
45     error_message: String,
46 ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
47     struct_span_err!(sess, sp, E0004, "{}", &error_message)
48 }
49
50 #[derive(PartialEq)]
51 enum RefutableFlag {
52     Irrefutable,
53     Refutable,
54 }
55 use RefutableFlag::*;
56
57 struct MatchVisitor<'a, 'p, 'tcx> {
58     tcx: TyCtxt<'tcx>,
59     typeck_results: &'a ty::TypeckResults<'tcx>,
60     param_env: ty::ParamEnv<'tcx>,
61     pattern_arena: &'p TypedArena<DeconstructedPat<'p, 'tcx>>,
62 }
63
64 impl<'tcx> Visitor<'tcx> for MatchVisitor<'_, '_, 'tcx> {
65     fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
66         intravisit::walk_expr(self, ex);
67         match &ex.kind {
68             hir::ExprKind::Match(scrut, arms, source) => {
69                 self.check_match(scrut, arms, *source, ex.span)
70             }
71             hir::ExprKind::Let(hir::Let { pat, init, span, .. }) => {
72                 self.check_let(pat, init, *span)
73             }
74             _ => {}
75         }
76     }
77
78     fn visit_local(&mut self, loc: &'tcx hir::Local<'tcx>) {
79         intravisit::walk_local(self, loc);
80         let els = loc.els;
81         if let Some(init) = loc.init && els.is_some() {
82             self.check_let(&loc.pat, init, loc.span);
83         }
84
85         let (msg, sp) = match loc.source {
86             hir::LocalSource::Normal => ("local binding", Some(loc.span)),
87             hir::LocalSource::AsyncFn => ("async fn binding", None),
88             hir::LocalSource::AwaitDesugar => ("`await` future binding", None),
89             hir::LocalSource::AssignDesugar(_) => ("destructuring assignment binding", None),
90         };
91         if els.is_none() {
92             self.check_irrefutable(&loc.pat, msg, sp);
93         }
94     }
95
96     fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
97         intravisit::walk_param(self, param);
98         self.check_irrefutable(&param.pat, "function argument", None);
99     }
100 }
101
102 impl PatCtxt<'_, '_> {
103     fn report_inlining_errors(&self) {
104         for error in &self.errors {
105             match *error {
106                 PatternError::StaticInPattern(span) => {
107                     self.span_e0158(span, "statics cannot be referenced in patterns")
108                 }
109                 PatternError::AssocConstInPattern(span) => {
110                     self.span_e0158(span, "associated consts cannot be referenced in patterns")
111                 }
112                 PatternError::ConstParamInPattern(span) => {
113                     self.span_e0158(span, "const parameters cannot be referenced in patterns")
114                 }
115                 PatternError::NonConstPath(span) => {
116                     rustc_middle::mir::interpret::struct_error(
117                         self.tcx.at(span),
118                         "runtime values cannot be referenced in patterns",
119                     )
120                     .emit();
121                 }
122             }
123         }
124     }
125
126     fn span_e0158(&self, span: Span, text: &str) {
127         struct_span_err!(self.tcx.sess, span, E0158, "{}", text).emit();
128     }
129 }
130
131 impl<'p, 'tcx> MatchVisitor<'_, 'p, 'tcx> {
132     fn check_patterns(&self, pat: &Pat<'_>, rf: RefutableFlag) {
133         pat.walk_always(|pat| check_borrow_conflicts_in_at_patterns(self, pat));
134         check_for_bindings_named_same_as_variants(self, pat, rf);
135     }
136
137     fn lower_pattern(
138         &self,
139         cx: &mut MatchCheckCtxt<'p, 'tcx>,
140         pat: &'tcx hir::Pat<'tcx>,
141         have_errors: &mut bool,
142     ) -> &'p DeconstructedPat<'p, 'tcx> {
143         let mut patcx = PatCtxt::new(self.tcx, self.param_env, self.typeck_results);
144         patcx.include_lint_checks();
145         let pattern = patcx.lower_pattern(pat);
146         let pattern: &_ = cx.pattern_arena.alloc(DeconstructedPat::from_pat(cx, &pattern));
147         if !patcx.errors.is_empty() {
148             *have_errors = true;
149             patcx.report_inlining_errors();
150         }
151         pattern
152     }
153
154     fn new_cx(&self, hir_id: HirId) -> MatchCheckCtxt<'p, 'tcx> {
155         MatchCheckCtxt {
156             tcx: self.tcx,
157             param_env: self.param_env,
158             module: self.tcx.parent_module(hir_id).to_def_id(),
159             pattern_arena: &self.pattern_arena,
160         }
161     }
162
163     fn check_let(&mut self, pat: &'tcx hir::Pat<'tcx>, scrutinee: &hir::Expr<'_>, span: Span) {
164         self.check_patterns(pat, Refutable);
165         let mut cx = self.new_cx(scrutinee.hir_id);
166         let tpat = self.lower_pattern(&mut cx, pat, &mut false);
167         self.check_let_reachability(&mut cx, pat.hir_id, tpat, span);
168     }
169
170     fn check_match(
171         &mut self,
172         scrut: &hir::Expr<'_>,
173         hir_arms: &'tcx [hir::Arm<'tcx>],
174         source: hir::MatchSource,
175         expr_span: Span,
176     ) {
177         let mut cx = self.new_cx(scrut.hir_id);
178
179         for arm in hir_arms {
180             // Check the arm for some things unrelated to exhaustiveness.
181             self.check_patterns(&arm.pat, Refutable);
182             if let Some(hir::Guard::IfLet(ref let_expr)) = arm.guard {
183                 self.check_patterns(let_expr.pat, Refutable);
184                 let tpat = self.lower_pattern(&mut cx, let_expr.pat, &mut false);
185                 self.check_let_reachability(&mut cx, let_expr.pat.hir_id, tpat, tpat.span());
186             }
187         }
188
189         let mut have_errors = false;
190
191         let arms: Vec<_> = hir_arms
192             .iter()
193             .map(|hir::Arm { pat, guard, .. }| MatchArm {
194                 pat: self.lower_pattern(&mut cx, pat, &mut have_errors),
195                 hir_id: pat.hir_id,
196                 has_guard: guard.is_some(),
197             })
198             .collect();
199
200         // Bail out early if lowering failed.
201         if have_errors {
202             return;
203         }
204
205         let scrut_ty = self.typeck_results.expr_ty_adjusted(scrut);
206         let report = compute_match_usefulness(&cx, &arms, scrut.hir_id, scrut_ty);
207
208         match source {
209             // Don't report arm reachability of desugared `match $iter.into_iter() { iter => .. }`
210             // when the iterator is an uninhabited type. unreachable_code will trigger instead.
211             hir::MatchSource::ForLoopDesugar if arms.len() == 1 => {}
212             hir::MatchSource::ForLoopDesugar | hir::MatchSource::Normal => {
213                 report_arm_reachability(&cx, &report)
214             }
215             // Unreachable patterns in try and await expressions occur when one of
216             // the arms are an uninhabited type. Which is OK.
217             hir::MatchSource::AwaitDesugar | hir::MatchSource::TryDesugar => {}
218         }
219
220         // Check if the match is exhaustive.
221         let witnesses = report.non_exhaustiveness_witnesses;
222         if !witnesses.is_empty() {
223             if source == hir::MatchSource::ForLoopDesugar && hir_arms.len() == 2 {
224                 // the for loop pattern is not irrefutable
225                 let pat = hir_arms[1].pat.for_loop_some().unwrap();
226                 self.check_irrefutable(pat, "`for` loop binding", None);
227             } else {
228                 non_exhaustive_match(&cx, scrut_ty, scrut.span, witnesses, hir_arms, expr_span);
229             }
230         }
231     }
232
233     fn check_let_reachability(
234         &mut self,
235         cx: &mut MatchCheckCtxt<'p, 'tcx>,
236         pat_id: HirId,
237         pat: &'p DeconstructedPat<'p, 'tcx>,
238         span: Span,
239     ) {
240         if self.check_let_chain(cx, pat_id) {
241             return;
242         }
243
244         if is_let_irrefutable(cx, pat_id, pat) {
245             irrefutable_let_pattern(cx.tcx, pat_id, span);
246         }
247     }
248
249     fn check_let_chain(&mut self, cx: &mut MatchCheckCtxt<'p, 'tcx>, pat_id: HirId) -> bool {
250         let hir = self.tcx.hir();
251         let parent = hir.get_parent_node(pat_id);
252
253         // First, figure out if the given pattern is part of a let chain,
254         // and if so, obtain the top node of the chain.
255         let mut top = parent;
256         let mut part_of_chain = false;
257         loop {
258             let new_top = hir.get_parent_node(top);
259             if let hir::Node::Expr(
260                 hir::Expr {
261                     kind: hir::ExprKind::Binary(Spanned { node: hir::BinOpKind::And, .. }, lhs, rhs),
262                     ..
263                 },
264                 ..,
265             ) = hir.get(new_top)
266             {
267                 // If this isn't the first iteration, we need to check
268                 // if there is a let expr before us in the chain, so
269                 // that we avoid doubly checking the let chain.
270
271                 // The way a chain of &&s is encoded is ((let ... && let ...) && let ...) && let ...
272                 // as && is left-to-right associative. Thus, we need to check rhs.
273                 if part_of_chain && matches!(rhs.kind, hir::ExprKind::Let(..)) {
274                     return true;
275                 }
276                 // If there is a let at the lhs, and we provide the rhs, we don't do any checking either.
277                 if !part_of_chain && matches!(lhs.kind, hir::ExprKind::Let(..)) && rhs.hir_id == top
278                 {
279                     return true;
280                 }
281             } else {
282                 // We've reached the top.
283                 break;
284             }
285
286             // Since this function is called within a let context, it is reasonable to assume that any parent
287             // `&&` infers a let chain
288             part_of_chain = true;
289             top = new_top;
290         }
291         if !part_of_chain {
292             return false;
293         }
294
295         // Second, obtain the refutabilities of all exprs in the chain,
296         // and record chain members that aren't let exprs.
297         let mut chain_refutabilities = Vec::new();
298         let hir::Node::Expr(top_expr) = hir.get(top) else {
299             // We ensure right above that it's an Expr
300             unreachable!()
301         };
302         let mut cur_expr = top_expr;
303         loop {
304             let mut add = |expr: &hir::Expr<'tcx>| {
305                 let refutability = match expr.kind {
306                     hir::ExprKind::Let(hir::Let { pat, init, span, .. }) => {
307                         let mut ncx = self.new_cx(init.hir_id);
308                         let tpat = self.lower_pattern(&mut ncx, pat, &mut false);
309
310                         let refutable = !is_let_irrefutable(&mut ncx, pat.hir_id, tpat);
311                         Some((*span, refutable))
312                     }
313                     _ => None,
314                 };
315                 chain_refutabilities.push(refutability);
316             };
317             if let hir::Expr {
318                 kind: hir::ExprKind::Binary(Spanned { node: hir::BinOpKind::And, .. }, lhs, rhs),
319                 ..
320             } = cur_expr
321             {
322                 add(rhs);
323                 cur_expr = lhs;
324             } else {
325                 add(cur_expr);
326                 break;
327             }
328         }
329         chain_refutabilities.reverse();
330
331         // Third, emit the actual warnings.
332
333         if chain_refutabilities.iter().all(|r| matches!(*r, Some((_, false)))) {
334             // The entire chain is made up of irrefutable `let` statements
335             let let_source = let_source_parent(self.tcx, top, None);
336             irrefutable_let_patterns(
337                 cx.tcx,
338                 top,
339                 let_source,
340                 chain_refutabilities.len(),
341                 top_expr.span,
342             );
343             return true;
344         }
345         let lint_affix = |affix: &[Option<(Span, bool)>], kind, suggestion| {
346             let span_start = affix[0].unwrap().0;
347             let span_end = affix.last().unwrap().unwrap().0;
348             let span = span_start.to(span_end);
349             let cnt = affix.len();
350             cx.tcx.struct_span_lint_hir(IRREFUTABLE_LET_PATTERNS, top, span, |lint| {
351                 let s = pluralize!(cnt);
352                 let mut diag = lint.build(&format!("{kind} irrefutable pattern{s} in let chain"));
353                 diag.note(&format!(
354                     "{these} pattern{s} will always match",
355                     these = pluralize!("this", cnt),
356                 ));
357                 diag.help(&format!(
358                     "consider moving {} {suggestion}",
359                     if cnt > 1 { "them" } else { "it" }
360                 ));
361                 diag.emit()
362             });
363         };
364         if let Some(until) = chain_refutabilities.iter().position(|r| !matches!(*r, Some((_, false)))) && until > 0 {
365             // The chain has a non-zero prefix of irrefutable `let` statements.
366
367             // Check if the let source is while, for there is no alternative place to put a prefix,
368             // and we shouldn't lint.
369             let let_source = let_source_parent(self.tcx, top, None);
370             if !matches!(let_source, LetSource::WhileLet) {
371                 // Emit the lint
372                 let prefix = &chain_refutabilities[..until];
373                 lint_affix(prefix, "leading", "outside of the construct");
374             }
375         }
376         if let Some(from) = chain_refutabilities.iter().rposition(|r| !matches!(*r, Some((_, false)))) && from != (chain_refutabilities.len() - 1) {
377             // The chain has a non-empty suffix of irrefutable `let` statements
378             let suffix = &chain_refutabilities[from + 1..];
379             lint_affix(suffix, "trailing", "into the body");
380         }
381         true
382     }
383
384     fn check_irrefutable(&self, pat: &'tcx Pat<'tcx>, origin: &str, sp: Option<Span>) {
385         let mut cx = self.new_cx(pat.hir_id);
386
387         let pattern = self.lower_pattern(&mut cx, pat, &mut false);
388         let pattern_ty = pattern.ty();
389         let arms = vec![MatchArm { pat: pattern, hir_id: pat.hir_id, has_guard: false }];
390         let report = compute_match_usefulness(&cx, &arms, pat.hir_id, pattern_ty);
391
392         // Note: we ignore whether the pattern is unreachable (i.e. whether the type is empty). We
393         // only care about exhaustiveness here.
394         let witnesses = report.non_exhaustiveness_witnesses;
395         if witnesses.is_empty() {
396             // The pattern is irrefutable.
397             self.check_patterns(pat, Irrefutable);
398             return;
399         }
400
401         let joined_patterns = joined_uncovered_patterns(&cx, &witnesses);
402
403         let mut bindings = vec![];
404
405         let mut err = struct_span_err!(
406             self.tcx.sess,
407             pat.span,
408             E0005,
409             "refutable pattern in {}: {} not covered",
410             origin,
411             joined_patterns
412         );
413         let suggest_if_let = match &pat.kind {
414             hir::PatKind::Path(hir::QPath::Resolved(None, path))
415                 if path.segments.len() == 1 && path.segments[0].args.is_none() =>
416             {
417                 const_not_var(&mut err, cx.tcx, pat, path);
418                 false
419             }
420             _ => {
421                 pat.walk(&mut |pat: &hir::Pat<'_>| {
422                     match pat.kind {
423                         hir::PatKind::Binding(_, _, ident, _) => {
424                             bindings.push(ident);
425                         }
426                         _ => {}
427                     }
428                     true
429                 });
430
431                 err.span_label(pat.span, pattern_not_covered_label(&witnesses, &joined_patterns));
432                 true
433             }
434         };
435
436         if let (Some(span), true) = (sp, suggest_if_let) {
437             err.note(
438                 "`let` bindings require an \"irrefutable pattern\", like a `struct` or \
439                  an `enum` with only one variant",
440             );
441             if self.tcx.sess.source_map().is_span_accessible(span) {
442                 let semi_span = span.shrink_to_hi().with_lo(span.hi() - BytePos(1));
443                 let start_span = span.shrink_to_lo();
444                 let end_span = semi_span.shrink_to_lo();
445                 err.multipart_suggestion(
446                     &format!(
447                         "you might want to use `if let` to ignore the variant{} that {} matched",
448                         pluralize!(witnesses.len()),
449                         match witnesses.len() {
450                             1 => "isn't",
451                             _ => "aren't",
452                         },
453                     ),
454                     vec![
455                         match &bindings[..] {
456                             [] => (start_span, "if ".to_string()),
457                             [binding] => (start_span, format!("let {} = if ", binding)),
458                             bindings => (
459                                 start_span,
460                                 format!(
461                                     "let ({}) = if ",
462                                     bindings
463                                         .iter()
464                                         .map(|ident| ident.to_string())
465                                         .collect::<Vec<_>>()
466                                         .join(", ")
467                                 ),
468                             ),
469                         },
470                         match &bindings[..] {
471                             [] => (semi_span, " { todo!() }".to_string()),
472                             [binding] => {
473                                 (end_span, format!(" {{ {} }} else {{ todo!() }}", binding))
474                             }
475                             bindings => (
476                                 end_span,
477                                 format!(
478                                     " {{ ({}) }} else {{ todo!() }}",
479                                     bindings
480                                         .iter()
481                                         .map(|ident| ident.to_string())
482                                         .collect::<Vec<_>>()
483                                         .join(", ")
484                                 ),
485                             ),
486                         },
487                     ],
488                     Applicability::HasPlaceholders,
489                 );
490                 if !bindings.is_empty() && cx.tcx.sess.is_nightly_build() {
491                     err.span_suggestion_verbose(
492                         semi_span.shrink_to_lo(),
493                         &format!(
494                             "alternatively, on nightly, you might want to use \
495                              `#![feature(let_else)]` to handle the variant{} that {} matched",
496                             pluralize!(witnesses.len()),
497                             match witnesses.len() {
498                                 1 => "isn't",
499                                 _ => "aren't",
500                             },
501                         ),
502                         " else { todo!() }".to_string(),
503                         Applicability::HasPlaceholders,
504                     );
505                 }
506             }
507             err.note(
508                 "for more information, visit \
509                  https://doc.rust-lang.org/book/ch18-02-refutability.html",
510             );
511         }
512
513         adt_defined_here(&cx, &mut err, pattern_ty, &witnesses);
514         err.note(&format!("the matched value is of type `{}`", pattern_ty));
515         err.emit();
516     }
517 }
518
519 /// A path pattern was interpreted as a constant, not a new variable.
520 /// This caused an irrefutable match failure in e.g. `let`.
521 fn const_not_var(err: &mut Diagnostic, tcx: TyCtxt<'_>, pat: &Pat<'_>, path: &hir::Path<'_>) {
522     let descr = path.res.descr();
523     err.span_label(
524         pat.span,
525         format!("interpreted as {} {} pattern, not a new variable", path.res.article(), descr,),
526     );
527
528     err.span_suggestion(
529         pat.span,
530         "introduce a variable instead",
531         format!("{}_var", path.segments[0].ident).to_lowercase(),
532         // Cannot use `MachineApplicable` as it's not really *always* correct
533         // because there may be such an identifier in scope or the user maybe
534         // really wanted to match against the constant. This is quite unlikely however.
535         Applicability::MaybeIncorrect,
536     );
537
538     if let Some(span) = tcx.hir().res_span(path.res) {
539         err.span_label(span, format!("{} defined here", descr));
540     }
541 }
542
543 fn check_for_bindings_named_same_as_variants(
544     cx: &MatchVisitor<'_, '_, '_>,
545     pat: &Pat<'_>,
546     rf: RefutableFlag,
547 ) {
548     pat.walk_always(|p| {
549         if let hir::PatKind::Binding(_, _, ident, None) = p.kind
550             && let Some(ty::BindByValue(hir::Mutability::Not)) =
551                 cx.typeck_results.extract_binding_mode(cx.tcx.sess, p.hir_id, p.span)
552             && let pat_ty = cx.typeck_results.pat_ty(p).peel_refs()
553             && let ty::Adt(edef, _) = pat_ty.kind()
554             && edef.is_enum()
555             && edef.variants().iter().any(|variant| {
556                 variant.ident(cx.tcx) == ident && variant.ctor_kind == CtorKind::Const
557             })
558         {
559             let variant_count = edef.variants().len();
560             cx.tcx.struct_span_lint_hir(
561                 BINDINGS_WITH_VARIANT_NAME,
562                 p.hir_id,
563                 p.span,
564                 |lint| {
565                     let ty_path = cx.tcx.def_path_str(edef.did());
566                     let mut err = lint.build(&format!(
567                         "pattern binding `{}` is named the same as one \
568                          of the variants of the type `{}`",
569                         ident, ty_path
570                     ));
571                     err.code(error_code!(E0170));
572                     // If this is an irrefutable pattern, and there's > 1 variant,
573                     // then we can't actually match on this. Applying the below
574                     // suggestion would produce code that breaks on `check_irrefutable`.
575                     if rf == Refutable || variant_count == 1 {
576                         err.span_suggestion(
577                             p.span,
578                             "to match on the variant, qualify the path",
579                             format!("{}::{}", ty_path, ident),
580                             Applicability::MachineApplicable,
581                         );
582                     }
583                     err.emit();
584                 },
585             )
586         }
587     });
588 }
589
590 /// Checks for common cases of "catchall" patterns that may not be intended as such.
591 fn pat_is_catchall(pat: &DeconstructedPat<'_, '_>) -> bool {
592     use Constructor::*;
593     match pat.ctor() {
594         Wildcard => true,
595         Single => pat.iter_fields().all(|pat| pat_is_catchall(pat)),
596         _ => false,
597     }
598 }
599
600 fn unreachable_pattern(tcx: TyCtxt<'_>, span: Span, id: HirId, catchall: Option<Span>) {
601     tcx.struct_span_lint_hir(UNREACHABLE_PATTERNS, id, span, |lint| {
602         let mut err = lint.build("unreachable pattern");
603         if let Some(catchall) = catchall {
604             // We had a catchall pattern, hint at that.
605             err.span_label(span, "unreachable pattern");
606             err.span_label(catchall, "matches any value");
607         }
608         err.emit();
609     });
610 }
611
612 fn irrefutable_let_pattern(tcx: TyCtxt<'_>, id: HirId, span: Span) {
613     let source = let_source(tcx, id);
614     irrefutable_let_patterns(tcx, id, source, 1, span);
615 }
616
617 fn irrefutable_let_patterns(
618     tcx: TyCtxt<'_>,
619     id: HirId,
620     source: LetSource,
621     count: usize,
622     span: Span,
623 ) {
624     macro_rules! emit_diag {
625         (
626             $lint:expr,
627             $source_name:expr,
628             $note_sufix:expr,
629             $help_sufix:expr
630         ) => {{
631             let s = pluralize!(count);
632             let these = pluralize!("this", count);
633             let mut diag = $lint.build(&format!("irrefutable {} pattern{s}", $source_name));
634             diag.note(&format!("{these} pattern{s} will always match, so the {}", $note_sufix));
635             diag.help(concat!("consider ", $help_sufix));
636             diag.emit()
637         }};
638     }
639
640     let span = match source {
641         LetSource::LetElse(span) => span,
642         _ => span,
643     };
644     tcx.struct_span_lint_hir(IRREFUTABLE_LET_PATTERNS, id, span, |lint| match source {
645         LetSource::GenericLet => {
646             emit_diag!(lint, "`let`", "`let` is useless", "removing `let`");
647         }
648         LetSource::IfLet => {
649             emit_diag!(
650                 lint,
651                 "`if let`",
652                 "`if let` is useless",
653                 "replacing the `if let` with a `let`"
654             );
655         }
656         LetSource::IfLetGuard => {
657             emit_diag!(
658                 lint,
659                 "`if let` guard",
660                 "guard is useless",
661                 "removing the guard and adding a `let` inside the match arm"
662             );
663         }
664         LetSource::LetElse(..) => {
665             emit_diag!(
666                 lint,
667                 "`let...else`",
668                 "`else` clause is useless",
669                 "removing the `else` clause"
670             );
671         }
672         LetSource::WhileLet => {
673             emit_diag!(
674                 lint,
675                 "`while let`",
676                 "loop will never exit",
677                 "instead using a `loop { ... }` with a `let` inside it"
678             );
679         }
680     });
681 }
682
683 fn is_let_irrefutable<'p, 'tcx>(
684     cx: &mut MatchCheckCtxt<'p, 'tcx>,
685     pat_id: HirId,
686     pat: &'p DeconstructedPat<'p, 'tcx>,
687 ) -> bool {
688     let arms = [MatchArm { pat, hir_id: pat_id, has_guard: false }];
689     let report = compute_match_usefulness(&cx, &arms, pat_id, pat.ty());
690
691     // Report if the pattern is unreachable, which can only occur when the type is uninhabited.
692     // This also reports unreachable sub-patterns though, so we can't just replace it with an
693     // `is_uninhabited` check.
694     report_arm_reachability(&cx, &report);
695
696     // If the list of witnesses is empty, the match is exhaustive,
697     // i.e. the `if let` pattern is irrefutable.
698     report.non_exhaustiveness_witnesses.is_empty()
699 }
700
701 /// Report unreachable arms, if any.
702 fn report_arm_reachability<'p, 'tcx>(
703     cx: &MatchCheckCtxt<'p, 'tcx>,
704     report: &UsefulnessReport<'p, 'tcx>,
705 ) {
706     use Reachability::*;
707     let mut catchall = None;
708     for (arm, is_useful) in report.arm_usefulness.iter() {
709         match is_useful {
710             Unreachable => unreachable_pattern(cx.tcx, arm.pat.span(), arm.hir_id, catchall),
711             Reachable(unreachables) if unreachables.is_empty() => {}
712             // The arm is reachable, but contains unreachable subpatterns (from or-patterns).
713             Reachable(unreachables) => {
714                 let mut unreachables = unreachables.clone();
715                 // Emit lints in the order in which they occur in the file.
716                 unreachables.sort_unstable();
717                 for span in unreachables {
718                     unreachable_pattern(cx.tcx, span, arm.hir_id, None);
719                 }
720             }
721         }
722         if !arm.has_guard && catchall.is_none() && pat_is_catchall(arm.pat) {
723             catchall = Some(arm.pat.span());
724         }
725     }
726 }
727
728 /// Report that a match is not exhaustive.
729 fn non_exhaustive_match<'p, 'tcx>(
730     cx: &MatchCheckCtxt<'p, 'tcx>,
731     scrut_ty: Ty<'tcx>,
732     sp: Span,
733     witnesses: Vec<DeconstructedPat<'p, 'tcx>>,
734     arms: &[hir::Arm<'tcx>],
735     expr_span: Span,
736 ) {
737     let is_empty_match = arms.is_empty();
738     let non_empty_enum = match scrut_ty.kind() {
739         ty::Adt(def, _) => def.is_enum() && !def.variants().is_empty(),
740         _ => false,
741     };
742     // In the case of an empty match, replace the '`_` not covered' diagnostic with something more
743     // informative.
744     let mut err;
745     let pattern;
746     let mut patterns_len = 0;
747     if is_empty_match && !non_empty_enum {
748         err = create_e0004(
749             cx.tcx.sess,
750             sp,
751             format!("non-exhaustive patterns: type `{}` is non-empty", scrut_ty),
752         );
753         pattern = "_".to_string();
754     } else {
755         let joined_patterns = joined_uncovered_patterns(cx, &witnesses);
756         err = create_e0004(
757             cx.tcx.sess,
758             sp,
759             format!("non-exhaustive patterns: {} not covered", joined_patterns),
760         );
761         err.span_label(sp, pattern_not_covered_label(&witnesses, &joined_patterns));
762         patterns_len = witnesses.len();
763         pattern = if witnesses.len() < 4 {
764             witnesses
765                 .iter()
766                 .map(|witness| witness.to_pat(cx).to_string())
767                 .collect::<Vec<String>>()
768                 .join(" | ")
769         } else {
770             "_".to_string()
771         };
772     };
773
774     let is_variant_list_non_exhaustive = match scrut_ty.kind() {
775         ty::Adt(def, _) if def.is_variant_list_non_exhaustive() && !def.did().is_local() => true,
776         _ => false,
777     };
778
779     adt_defined_here(cx, &mut err, scrut_ty, &witnesses);
780     err.note(&format!(
781         "the matched value is of type `{}`{}",
782         scrut_ty,
783         if is_variant_list_non_exhaustive { ", which is marked as non-exhaustive" } else { "" }
784     ));
785     if (scrut_ty == cx.tcx.types.usize || scrut_ty == cx.tcx.types.isize)
786         && !is_empty_match
787         && witnesses.len() == 1
788         && matches!(witnesses[0].ctor(), Constructor::NonExhaustive)
789     {
790         err.note(&format!(
791             "`{}` does not have a fixed maximum value, so a wildcard `_` is necessary to match \
792              exhaustively",
793             scrut_ty,
794         ));
795         if cx.tcx.sess.is_nightly_build() {
796             err.help(&format!(
797                 "add `#![feature(precise_pointer_size_matching)]` to the crate attributes to \
798                  enable precise `{}` matching",
799                 scrut_ty,
800             ));
801         }
802     }
803     if let ty::Ref(_, sub_ty, _) = scrut_ty.kind() {
804         if cx.tcx.is_ty_uninhabited_from(cx.module, *sub_ty, cx.param_env) {
805             err.note("references are always considered inhabited");
806         }
807     }
808
809     let mut suggestion = None;
810     let sm = cx.tcx.sess.source_map();
811     match arms {
812         [] if sp.eq_ctxt(expr_span) => {
813             // Get the span for the empty match body `{}`.
814             let (indentation, more) = if let Some(snippet) = sm.indentation_before(sp) {
815                 (format!("\n{}", snippet), "    ")
816             } else {
817                 (" ".to_string(), "")
818             };
819             suggestion = Some((
820                 sp.shrink_to_hi().with_hi(expr_span.hi()),
821                 format!(
822                     " {{{indentation}{more}{pattern} => todo!(),{indentation}}}",
823                     indentation = indentation,
824                     more = more,
825                     pattern = pattern,
826                 ),
827             ));
828         }
829         [only] => {
830             let (pre_indentation, is_multiline) = if let Some(snippet) = sm.indentation_before(only.span)
831                 && let Ok(with_trailing) = sm.span_extend_while(only.span, |c| c.is_whitespace() || c == ',')
832                 && sm.is_multiline(with_trailing)
833             {
834                 (format!("\n{}", snippet), true)
835             } else {
836                 (" ".to_string(), false)
837             };
838             let comma = if matches!(only.body.kind, hir::ExprKind::Block(..))
839                 && only.span.eq_ctxt(only.body.span)
840                 && is_multiline
841             {
842                 ""
843             } else {
844                 ","
845             };
846             suggestion = Some((
847                 only.span.shrink_to_hi(),
848                 format!("{}{}{} => todo!()", comma, pre_indentation, pattern),
849             ));
850         }
851         [.., prev, last] if prev.span.eq_ctxt(last.span) => {
852             if let Ok(snippet) = sm.span_to_snippet(prev.span.between(last.span)) {
853                 let comma = if matches!(last.body.kind, hir::ExprKind::Block(..))
854                     && last.span.eq_ctxt(last.body.span)
855                 {
856                     ""
857                 } else {
858                     ","
859                 };
860                 suggestion = Some((
861                     last.span.shrink_to_hi(),
862                     format!(
863                         "{}{}{} => todo!()",
864                         comma,
865                         snippet.strip_prefix(',').unwrap_or(&snippet),
866                         pattern
867                     ),
868                 ));
869             }
870         }
871         _ => {}
872     }
873
874     let msg = format!(
875         "ensure that all possible cases are being handled by adding a match arm with a wildcard \
876          pattern{}{}",
877         if patterns_len > 1 && patterns_len < 4 && suggestion.is_some() {
878             ", a match arm with multiple or-patterns"
879         } else {
880             // we are either not suggesting anything, or suggesting `_`
881             ""
882         },
883         match patterns_len {
884             // non-exhaustive enum case
885             0 if suggestion.is_some() => " as shown",
886             0 => "",
887             1 if suggestion.is_some() => " or an explicit pattern as shown",
888             1 => " or an explicit pattern",
889             _ if suggestion.is_some() => " as shown, or multiple match arms",
890             _ => " or multiple match arms",
891         },
892     );
893     if let Some((span, sugg)) = suggestion {
894         err.span_suggestion_verbose(span, &msg, sugg, Applicability::HasPlaceholders);
895     } else {
896         err.help(&msg);
897     }
898     err.emit();
899 }
900
901 pub(crate) fn joined_uncovered_patterns<'p, 'tcx>(
902     cx: &MatchCheckCtxt<'p, 'tcx>,
903     witnesses: &[DeconstructedPat<'p, 'tcx>],
904 ) -> String {
905     const LIMIT: usize = 3;
906     let pat_to_str = |pat: &DeconstructedPat<'p, 'tcx>| pat.to_pat(cx).to_string();
907     match witnesses {
908         [] => bug!(),
909         [witness] => format!("`{}`", witness.to_pat(cx)),
910         [head @ .., tail] if head.len() < LIMIT => {
911             let head: Vec<_> = head.iter().map(pat_to_str).collect();
912             format!("`{}` and `{}`", head.join("`, `"), tail.to_pat(cx))
913         }
914         _ => {
915             let (head, tail) = witnesses.split_at(LIMIT);
916             let head: Vec<_> = head.iter().map(pat_to_str).collect();
917             format!("`{}` and {} more", head.join("`, `"), tail.len())
918         }
919     }
920 }
921
922 pub(crate) fn pattern_not_covered_label(
923     witnesses: &[DeconstructedPat<'_, '_>],
924     joined_patterns: &str,
925 ) -> String {
926     format!("pattern{} {} not covered", rustc_errors::pluralize!(witnesses.len()), joined_patterns)
927 }
928
929 /// Point at the definition of non-covered `enum` variants.
930 fn adt_defined_here<'p, 'tcx>(
931     cx: &MatchCheckCtxt<'p, 'tcx>,
932     err: &mut Diagnostic,
933     ty: Ty<'tcx>,
934     witnesses: &[DeconstructedPat<'p, 'tcx>],
935 ) {
936     let ty = ty.peel_refs();
937     if let ty::Adt(def, _) = ty.kind() {
938         let mut spans = vec![];
939         if witnesses.len() < 5 {
940             for sp in maybe_point_at_variant(cx, *def, witnesses.iter()) {
941                 spans.push(sp);
942             }
943         }
944         let def_span = cx
945             .tcx
946             .hir()
947             .get_if_local(def.did())
948             .and_then(|node| node.ident())
949             .map(|ident| ident.span)
950             .unwrap_or_else(|| cx.tcx.def_span(def.did()));
951         let mut span: MultiSpan =
952             if spans.is_empty() { def_span.into() } else { spans.clone().into() };
953
954         span.push_span_label(def_span, "");
955         for pat in spans {
956             span.push_span_label(pat, "not covered");
957         }
958         err.span_note(span, &format!("`{}` defined here", ty));
959     }
960 }
961
962 fn maybe_point_at_variant<'a, 'p: 'a, 'tcx: 'a>(
963     cx: &MatchCheckCtxt<'p, 'tcx>,
964     def: AdtDef<'tcx>,
965     patterns: impl Iterator<Item = &'a DeconstructedPat<'p, 'tcx>>,
966 ) -> Vec<Span> {
967     use Constructor::*;
968     let mut covered = vec![];
969     for pattern in patterns {
970         if let Variant(variant_index) = pattern.ctor() {
971             if let ty::Adt(this_def, _) = pattern.ty().kind() && this_def.did() != def.did() {
972                 continue;
973             }
974             let sp = def.variant(*variant_index).ident(cx.tcx).span;
975             if covered.contains(&sp) {
976                 // Don't point at variants that have already been covered due to other patterns to avoid
977                 // visual clutter.
978                 continue;
979             }
980             covered.push(sp);
981         }
982         covered.extend(maybe_point_at_variant(cx, def, pattern.iter_fields()));
983     }
984     covered
985 }
986
987 /// Check if a by-value binding is by-value. That is, check if the binding's type is not `Copy`.
988 fn is_binding_by_move(cx: &MatchVisitor<'_, '_, '_>, hir_id: HirId, span: Span) -> bool {
989     !cx.typeck_results.node_type(hir_id).is_copy_modulo_regions(cx.tcx.at(span), cx.param_env)
990 }
991
992 /// Check that there are no borrow or move conflicts in `binding @ subpat` patterns.
993 ///
994 /// For example, this would reject:
995 /// - `ref x @ Some(ref mut y)`,
996 /// - `ref mut x @ Some(ref y)`,
997 /// - `ref mut x @ Some(ref mut y)`,
998 /// - `ref mut? x @ Some(y)`, and
999 /// - `x @ Some(ref mut? y)`.
1000 ///
1001 /// This analysis is *not* subsumed by NLL.
1002 fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_, '_>, pat: &Pat<'_>) {
1003     // Extract `sub` in `binding @ sub`.
1004     let (name, sub) = match &pat.kind {
1005         hir::PatKind::Binding(.., name, Some(sub)) => (*name, sub),
1006         _ => return,
1007     };
1008     let binding_span = pat.span.with_hi(name.span.hi());
1009
1010     let typeck_results = cx.typeck_results;
1011     let sess = cx.tcx.sess;
1012
1013     // Get the binding move, extract the mutability if by-ref.
1014     let mut_outer = match typeck_results.extract_binding_mode(sess, pat.hir_id, pat.span) {
1015         Some(ty::BindByValue(_)) if is_binding_by_move(cx, pat.hir_id, pat.span) => {
1016             // We have `x @ pat` where `x` is by-move. Reject all borrows in `pat`.
1017             let mut conflicts_ref = Vec::new();
1018             sub.each_binding(|_, hir_id, span, _| {
1019                 match typeck_results.extract_binding_mode(sess, hir_id, span) {
1020                     Some(ty::BindByValue(_)) | None => {}
1021                     Some(ty::BindByReference(_)) => conflicts_ref.push(span),
1022                 }
1023             });
1024             if !conflicts_ref.is_empty() {
1025                 let occurs_because = format!(
1026                     "move occurs because `{}` has type `{}` which does not implement the `Copy` trait",
1027                     name,
1028                     typeck_results.node_type(pat.hir_id),
1029                 );
1030                 sess.struct_span_err(pat.span, "borrow of moved value")
1031                     .span_label(binding_span, format!("value moved into `{}` here", name))
1032                     .span_label(binding_span, occurs_because)
1033                     .span_labels(conflicts_ref, "value borrowed here after move")
1034                     .emit();
1035             }
1036             return;
1037         }
1038         Some(ty::BindByValue(_)) | None => return,
1039         Some(ty::BindByReference(m)) => m,
1040     };
1041
1042     // We now have `ref $mut_outer binding @ sub` (semantically).
1043     // Recurse into each binding in `sub` and find mutability or move conflicts.
1044     let mut conflicts_move = Vec::new();
1045     let mut conflicts_mut_mut = Vec::new();
1046     let mut conflicts_mut_ref = Vec::new();
1047     sub.each_binding(|_, hir_id, span, name| {
1048         match typeck_results.extract_binding_mode(sess, hir_id, span) {
1049             Some(ty::BindByReference(mut_inner)) => match (mut_outer, mut_inner) {
1050                 (Mutability::Not, Mutability::Not) => {} // Both sides are `ref`.
1051                 (Mutability::Mut, Mutability::Mut) => conflicts_mut_mut.push((span, name)), // 2x `ref mut`.
1052                 _ => conflicts_mut_ref.push((span, name)), // `ref` + `ref mut` in either direction.
1053             },
1054             Some(ty::BindByValue(_)) if is_binding_by_move(cx, hir_id, span) => {
1055                 conflicts_move.push((span, name)) // `ref mut?` + by-move conflict.
1056             }
1057             Some(ty::BindByValue(_)) | None => {} // `ref mut?` + by-copy is fine.
1058         }
1059     });
1060
1061     // Report errors if any.
1062     if !conflicts_mut_mut.is_empty() {
1063         // Report mutability conflicts for e.g. `ref mut x @ Some(ref mut y)`.
1064         let mut err = sess
1065             .struct_span_err(pat.span, "cannot borrow value as mutable more than once at a time");
1066         err.span_label(binding_span, format!("first mutable borrow, by `{}`, occurs here", name));
1067         for (span, name) in conflicts_mut_mut {
1068             err.span_label(span, format!("another mutable borrow, by `{}`, occurs here", name));
1069         }
1070         for (span, name) in conflicts_mut_ref {
1071             err.span_label(span, format!("also borrowed as immutable, by `{}`, here", name));
1072         }
1073         for (span, name) in conflicts_move {
1074             err.span_label(span, format!("also moved into `{}` here", name));
1075         }
1076         err.emit();
1077     } else if !conflicts_mut_ref.is_empty() {
1078         // Report mutability conflicts for e.g. `ref x @ Some(ref mut y)` or the converse.
1079         let (primary, also) = match mut_outer {
1080             Mutability::Mut => ("mutable", "immutable"),
1081             Mutability::Not => ("immutable", "mutable"),
1082         };
1083         let msg =
1084             format!("cannot borrow value as {} because it is also borrowed as {}", also, primary);
1085         let mut err = sess.struct_span_err(pat.span, &msg);
1086         err.span_label(binding_span, format!("{} borrow, by `{}`, occurs here", primary, name));
1087         for (span, name) in conflicts_mut_ref {
1088             err.span_label(span, format!("{} borrow, by `{}`, occurs here", also, name));
1089         }
1090         for (span, name) in conflicts_move {
1091             err.span_label(span, format!("also moved into `{}` here", name));
1092         }
1093         err.emit();
1094     } else if !conflicts_move.is_empty() {
1095         // Report by-ref and by-move conflicts, e.g. `ref x @ y`.
1096         let mut err =
1097             sess.struct_span_err(pat.span, "cannot move out of value because it is borrowed");
1098         err.span_label(binding_span, format!("value borrowed, by `{}`, here", name));
1099         for (span, name) in conflicts_move {
1100             err.span_label(span, format!("value moved into `{}` here", name));
1101         }
1102         err.emit();
1103     }
1104 }
1105
1106 #[derive(Clone, Copy, Debug)]
1107 pub enum LetSource {
1108     GenericLet,
1109     IfLet,
1110     IfLetGuard,
1111     LetElse(Span),
1112     WhileLet,
1113 }
1114
1115 fn let_source(tcx: TyCtxt<'_>, pat_id: HirId) -> LetSource {
1116     let hir = tcx.hir();
1117
1118     let parent = hir.get_parent_node(pat_id);
1119     let_source_parent(tcx, parent, Some(pat_id))
1120 }
1121
1122 fn let_source_parent(tcx: TyCtxt<'_>, parent: HirId, pat_id: Option<HirId>) -> LetSource {
1123     let hir = tcx.hir();
1124
1125     let parent_node = hir.get(parent);
1126
1127     match parent_node {
1128         hir::Node::Arm(hir::Arm {
1129             guard: Some(hir::Guard::IfLet(&hir::Let { pat: hir::Pat { hir_id, .. }, .. })),
1130             ..
1131         }) if Some(*hir_id) == pat_id => {
1132             return LetSource::IfLetGuard;
1133         }
1134         _ => {}
1135     }
1136
1137     let parent_parent = hir.get_parent_node(parent);
1138     let parent_parent_node = hir.get(parent_parent);
1139     if let hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(_), span, .. }) =
1140         parent_parent_node
1141     {
1142         return LetSource::LetElse(*span);
1143     }
1144
1145     let parent_parent_parent = hir.get_parent_node(parent_parent);
1146     let parent_parent_parent_parent = hir.get_parent_node(parent_parent_parent);
1147     let parent_parent_parent_parent_node = hir.get(parent_parent_parent_parent);
1148
1149     if let hir::Node::Expr(hir::Expr {
1150         kind: hir::ExprKind::Loop(_, _, hir::LoopSource::While, _),
1151         ..
1152     }) = parent_parent_parent_parent_node
1153     {
1154         return LetSource::WhileLet;
1155     }
1156
1157     if let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::If(..), .. }) = parent_parent_node {
1158         return LetSource::IfLet;
1159     }
1160
1161     LetSource::GenericLet
1162 }