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