rustc_mir_build/thir/pattern/
check_match.rs

1use rustc_arena::{DroplessArena, TypedArena};
2use rustc_ast::Mutability;
3use rustc_data_structures::fx::FxIndexSet;
4use rustc_data_structures::stack::ensure_sufficient_stack;
5use rustc_errors::codes::*;
6use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan, struct_span_code_err};
7use rustc_hir::def::*;
8use rustc_hir::def_id::LocalDefId;
9use rustc_hir::{self as hir, BindingMode, ByRef, HirId};
10use rustc_infer::infer::TyCtxtInferExt;
11use rustc_lint::Level;
12use rustc_middle::bug;
13use rustc_middle::thir::visit::Visitor;
14use rustc_middle::thir::*;
15use rustc_middle::ty::print::with_no_trimmed_paths;
16use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt};
17use rustc_pattern_analysis::errors::Uncovered;
18use rustc_pattern_analysis::rustc::{
19    Constructor, DeconstructedPat, MatchArm, RedundancyExplanation, RevealedTy,
20    RustcPatCtxt as PatCtxt, Usefulness, UsefulnessReport, WitnessPat,
21};
22use rustc_session::lint::builtin::{
23    BINDINGS_WITH_VARIANT_NAME, IRREFUTABLE_LET_PATTERNS, UNREACHABLE_PATTERNS,
24};
25use rustc_span::edit_distance::find_best_match_for_name;
26use rustc_span::hygiene::DesugaringKind;
27use rustc_span::{Ident, Span};
28use rustc_trait_selection::infer::InferCtxtExt;
29use tracing::instrument;
30
31use crate::errors::*;
32use crate::fluent_generated as fluent;
33
34pub(crate) fn check_match(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
35    let typeck_results = tcx.typeck(def_id);
36    let (thir, expr) = tcx.thir_body(def_id)?;
37    let thir = thir.borrow();
38    let pattern_arena = TypedArena::default();
39    let dropless_arena = DroplessArena::default();
40    let mut visitor = MatchVisitor {
41        tcx,
42        thir: &*thir,
43        typeck_results,
44        // FIXME(#132279): We're in a body, should handle opaques.
45        typing_env: ty::TypingEnv::non_body_analysis(tcx, def_id),
46        lint_level: tcx.local_def_id_to_hir_id(def_id),
47        let_source: LetSource::None,
48        pattern_arena: &pattern_arena,
49        dropless_arena: &dropless_arena,
50        error: Ok(()),
51    };
52    visitor.visit_expr(&thir[expr]);
53
54    let origin = match tcx.def_kind(def_id) {
55        DefKind::AssocFn | DefKind::Fn => "function argument",
56        DefKind::Closure => "closure argument",
57        // other types of MIR don't have function parameters, and we don't need to
58        // categorize those for the irrefutable check.
59        _ if thir.params.is_empty() => "",
60        kind => bug!("unexpected function parameters in THIR: {kind:?} {def_id:?}"),
61    };
62
63    for param in thir.params.iter() {
64        if let Some(box ref pattern) = param.pat {
65            visitor.check_binding_is_irrefutable(pattern, origin, None, None);
66        }
67    }
68    visitor.error
69}
70
71#[derive(Debug, Copy, Clone, PartialEq)]
72enum RefutableFlag {
73    Irrefutable,
74    Refutable,
75}
76use RefutableFlag::*;
77
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79enum LetSource {
80    None,
81    PlainLet,
82    IfLet,
83    IfLetGuard,
84    LetElse,
85    WhileLet,
86    Else,
87    ElseIfLet,
88}
89
90struct MatchVisitor<'p, 'tcx> {
91    tcx: TyCtxt<'tcx>,
92    typing_env: ty::TypingEnv<'tcx>,
93    typeck_results: &'tcx ty::TypeckResults<'tcx>,
94    thir: &'p Thir<'tcx>,
95    lint_level: HirId,
96    let_source: LetSource,
97    pattern_arena: &'p TypedArena<DeconstructedPat<'p, 'tcx>>,
98    dropless_arena: &'p DroplessArena,
99    /// Tracks if we encountered an error while checking this body. That the first function to
100    /// report it stores it here. Some functions return `Result` to allow callers to short-circuit
101    /// on error, but callers don't need to store it here again.
102    error: Result<(), ErrorGuaranteed>,
103}
104
105// Visitor for a thir body. This calls `check_match`, `check_let` and `check_let_chain` as
106// appropriate.
107impl<'p, 'tcx> Visitor<'p, 'tcx> for MatchVisitor<'p, 'tcx> {
108    fn thir(&self) -> &'p Thir<'tcx> {
109        self.thir
110    }
111
112    #[instrument(level = "trace", skip(self))]
113    fn visit_arm(&mut self, arm: &'p Arm<'tcx>) {
114        self.with_lint_level(arm.lint_level, |this| {
115            if let Some(expr) = arm.guard {
116                this.with_let_source(LetSource::IfLetGuard, |this| {
117                    this.visit_expr(&this.thir[expr])
118                });
119            }
120            this.visit_pat(&arm.pattern);
121            this.visit_expr(&self.thir[arm.body]);
122        });
123    }
124
125    #[instrument(level = "trace", skip(self))]
126    fn visit_expr(&mut self, ex: &'p Expr<'tcx>) {
127        match ex.kind {
128            ExprKind::Scope { value, lint_level, .. } => {
129                self.with_lint_level(lint_level, |this| {
130                    this.visit_expr(&this.thir[value]);
131                });
132                return;
133            }
134            ExprKind::If { cond, then, else_opt, if_then_scope: _ } => {
135                // Give a specific `let_source` for the condition.
136                let let_source = match ex.span.desugaring_kind() {
137                    Some(DesugaringKind::WhileLoop) => LetSource::WhileLet,
138                    _ => match self.let_source {
139                        LetSource::Else => LetSource::ElseIfLet,
140                        _ => LetSource::IfLet,
141                    },
142                };
143                self.with_let_source(let_source, |this| this.visit_expr(&self.thir[cond]));
144                self.with_let_source(LetSource::None, |this| {
145                    this.visit_expr(&this.thir[then]);
146                });
147                if let Some(else_) = else_opt {
148                    self.with_let_source(LetSource::Else, |this| {
149                        this.visit_expr(&this.thir[else_])
150                    });
151                }
152                return;
153            }
154            ExprKind::Match { scrutinee, box ref arms, match_source } => {
155                self.check_match(scrutinee, arms, match_source, ex.span);
156            }
157            ExprKind::Let { box ref pat, expr } => {
158                self.check_let(pat, Some(expr), ex.span);
159            }
160            ExprKind::LogicalOp { op: LogicalOp::And, .. }
161                if !matches!(self.let_source, LetSource::None) =>
162            {
163                let mut chain_refutabilities = Vec::new();
164                let Ok(()) = self.visit_land(ex, &mut chain_refutabilities) else { return };
165                // If at least one of the operands is a `let ... = ...`.
166                if chain_refutabilities.iter().any(|x| x.is_some()) {
167                    self.check_let_chain(chain_refutabilities, ex.span);
168                }
169                return;
170            }
171            _ => {}
172        };
173        self.with_let_source(LetSource::None, |this| visit::walk_expr(this, ex));
174    }
175
176    fn visit_stmt(&mut self, stmt: &'p Stmt<'tcx>) {
177        match stmt.kind {
178            StmtKind::Let {
179                box ref pattern, initializer, else_block, lint_level, span, ..
180            } => {
181                self.with_lint_level(lint_level, |this| {
182                    let let_source =
183                        if else_block.is_some() { LetSource::LetElse } else { LetSource::PlainLet };
184                    this.with_let_source(let_source, |this| {
185                        this.check_let(pattern, initializer, span)
186                    });
187                    visit::walk_stmt(this, stmt);
188                });
189            }
190            StmtKind::Expr { .. } => {
191                visit::walk_stmt(self, stmt);
192            }
193        }
194    }
195}
196
197impl<'p, 'tcx> MatchVisitor<'p, 'tcx> {
198    #[instrument(level = "trace", skip(self, f))]
199    fn with_let_source(&mut self, let_source: LetSource, f: impl FnOnce(&mut Self)) {
200        let old_let_source = self.let_source;
201        self.let_source = let_source;
202        ensure_sufficient_stack(|| f(self));
203        self.let_source = old_let_source;
204    }
205
206    fn with_lint_level<T>(
207        &mut self,
208        new_lint_level: LintLevel,
209        f: impl FnOnce(&mut Self) -> T,
210    ) -> T {
211        if let LintLevel::Explicit(hir_id) = new_lint_level {
212            let old_lint_level = self.lint_level;
213            self.lint_level = hir_id;
214            let ret = f(self);
215            self.lint_level = old_lint_level;
216            ret
217        } else {
218            f(self)
219        }
220    }
221
222    /// Visit a nested chain of `&&`. Used for if-let chains. This must call `visit_expr` on the
223    /// subexpressions we are not handling ourselves.
224    fn visit_land(
225        &mut self,
226        ex: &'p Expr<'tcx>,
227        accumulator: &mut Vec<Option<(Span, RefutableFlag)>>,
228    ) -> Result<(), ErrorGuaranteed> {
229        match ex.kind {
230            ExprKind::Scope { value, lint_level, .. } => self.with_lint_level(lint_level, |this| {
231                this.visit_land(&this.thir[value], accumulator)
232            }),
233            ExprKind::LogicalOp { op: LogicalOp::And, lhs, rhs } => {
234                // We recurse into the lhs only, because `&&` chains associate to the left.
235                let res_lhs = self.visit_land(&self.thir[lhs], accumulator);
236                let res_rhs = self.visit_land_rhs(&self.thir[rhs])?;
237                accumulator.push(res_rhs);
238                res_lhs
239            }
240            _ => {
241                let res = self.visit_land_rhs(ex)?;
242                accumulator.push(res);
243                Ok(())
244            }
245        }
246    }
247
248    /// Visit the right-hand-side of a `&&`. Used for if-let chains. Returns `Some` if the
249    /// expression was ultimately a `let ... = ...`, and `None` if it was a normal boolean
250    /// expression. This must call `visit_expr` on the subexpressions we are not handling ourselves.
251    fn visit_land_rhs(
252        &mut self,
253        ex: &'p Expr<'tcx>,
254    ) -> Result<Option<(Span, RefutableFlag)>, ErrorGuaranteed> {
255        match ex.kind {
256            ExprKind::Scope { value, lint_level, .. } => {
257                self.with_lint_level(lint_level, |this| this.visit_land_rhs(&this.thir[value]))
258            }
259            ExprKind::Let { box ref pat, expr } => {
260                let expr = &self.thir()[expr];
261                self.with_let_source(LetSource::None, |this| {
262                    this.visit_expr(expr);
263                });
264                Ok(Some((ex.span, self.is_let_irrefutable(pat, Some(expr))?)))
265            }
266            _ => {
267                self.with_let_source(LetSource::None, |this| {
268                    this.visit_expr(ex);
269                });
270                Ok(None)
271            }
272        }
273    }
274
275    fn lower_pattern(
276        &mut self,
277        cx: &PatCtxt<'p, 'tcx>,
278        pat: &'p Pat<'tcx>,
279    ) -> Result<&'p DeconstructedPat<'p, 'tcx>, ErrorGuaranteed> {
280        if let Err(err) = pat.pat_error_reported() {
281            self.error = Err(err);
282            Err(err)
283        } else {
284            // Check the pattern for some things unrelated to exhaustiveness.
285            let refutable = if cx.refutable { Refutable } else { Irrefutable };
286            let mut err = Ok(());
287            pat.walk_always(|pat| {
288                check_borrow_conflicts_in_at_patterns(self, pat);
289                check_for_bindings_named_same_as_variants(self, pat, refutable);
290                err = err.and(check_never_pattern(cx, pat));
291            });
292            err?;
293            Ok(self.pattern_arena.alloc(cx.lower_pat(pat)))
294        }
295    }
296
297    /// Inspects the match scrutinee expression to determine whether the place it evaluates to may
298    /// hold invalid data.
299    fn is_known_valid_scrutinee(&self, scrutinee: &Expr<'tcx>) -> bool {
300        use ExprKind::*;
301        match &scrutinee.kind {
302            // Pointers can validly point to a place with invalid data. It is undecided whether
303            // references can too, so we conservatively assume they can.
304            Deref { .. } => false,
305            // Inherit validity of the parent place, unless the parent is an union.
306            Field { lhs, .. } => {
307                let lhs = &self.thir()[*lhs];
308                match lhs.ty.kind() {
309                    ty::Adt(def, _) if def.is_union() => false,
310                    _ => self.is_known_valid_scrutinee(lhs),
311                }
312            }
313            // Essentially a field access.
314            Index { lhs, .. } => {
315                let lhs = &self.thir()[*lhs];
316                self.is_known_valid_scrutinee(lhs)
317            }
318
319            // No-op.
320            Scope { value, .. } => self.is_known_valid_scrutinee(&self.thir()[*value]),
321
322            // Casts don't cause a load.
323            NeverToAny { source }
324            | Cast { source }
325            | Use { source }
326            | PointerCoercion { source, .. }
327            | PlaceTypeAscription { source, .. }
328            | ValueTypeAscription { source, .. }
329            | PlaceUnwrapUnsafeBinder { source }
330            | ValueUnwrapUnsafeBinder { source }
331            | WrapUnsafeBinder { source } => self.is_known_valid_scrutinee(&self.thir()[*source]),
332
333            // These diverge.
334            Become { .. }
335            | Break { .. }
336            | Continue { .. }
337            | ConstContinue { .. }
338            | Return { .. } => true,
339
340            // These are statements that evaluate to `()`.
341            Assign { .. } | AssignOp { .. } | InlineAsm { .. } | Let { .. } => true,
342
343            // These evaluate to a value.
344            RawBorrow { .. }
345            | Adt { .. }
346            | Array { .. }
347            | Binary { .. }
348            | Block { .. }
349            | Borrow { .. }
350            | Box { .. }
351            | Call { .. }
352            | ByUse { .. }
353            | Closure { .. }
354            | ConstBlock { .. }
355            | ConstParam { .. }
356            | If { .. }
357            | Literal { .. }
358            | LogicalOp { .. }
359            | Loop { .. }
360            | LoopMatch { .. }
361            | Match { .. }
362            | NamedConst { .. }
363            | NonHirLiteral { .. }
364            | OffsetOf { .. }
365            | Repeat { .. }
366            | StaticRef { .. }
367            | ThreadLocalRef { .. }
368            | Tuple { .. }
369            | Unary { .. }
370            | UpvarRef { .. }
371            | VarRef { .. }
372            | ZstLiteral { .. }
373            | Yield { .. } => true,
374        }
375    }
376
377    fn new_cx(
378        &self,
379        refutability: RefutableFlag,
380        whole_match_span: Option<Span>,
381        scrutinee: Option<&Expr<'tcx>>,
382        scrut_span: Span,
383    ) -> PatCtxt<'p, 'tcx> {
384        let refutable = match refutability {
385            Irrefutable => false,
386            Refutable => true,
387        };
388        // If we don't have a scrutinee we're either a function parameter or a `let x;`. Both cases
389        // require validity.
390        let known_valid_scrutinee =
391            scrutinee.map(|scrut| self.is_known_valid_scrutinee(scrut)).unwrap_or(true);
392        PatCtxt {
393            tcx: self.tcx,
394            typeck_results: self.typeck_results,
395            typing_env: self.typing_env,
396            module: self.tcx.parent_module(self.lint_level).to_def_id(),
397            dropless_arena: self.dropless_arena,
398            match_lint_level: self.lint_level,
399            whole_match_span,
400            scrut_span,
401            refutable,
402            known_valid_scrutinee,
403        }
404    }
405
406    fn analyze_patterns(
407        &mut self,
408        cx: &PatCtxt<'p, 'tcx>,
409        arms: &[MatchArm<'p, 'tcx>],
410        scrut_ty: Ty<'tcx>,
411    ) -> Result<UsefulnessReport<'p, 'tcx>, ErrorGuaranteed> {
412        let report =
413            rustc_pattern_analysis::rustc::analyze_match(&cx, &arms, scrut_ty).map_err(|err| {
414                self.error = Err(err);
415                err
416            })?;
417
418        // Warn unreachable subpatterns.
419        for (arm, is_useful) in report.arm_usefulness.iter() {
420            if let Usefulness::Useful(redundant_subpats) = is_useful
421                && !redundant_subpats.is_empty()
422            {
423                let mut redundant_subpats = redundant_subpats.clone();
424                // Emit lints in the order in which they occur in the file.
425                redundant_subpats.sort_unstable_by_key(|(pat, _)| pat.data().span);
426                for (pat, explanation) in redundant_subpats {
427                    report_unreachable_pattern(cx, arm.arm_data, pat, &explanation, None)
428                }
429            }
430        }
431        Ok(report)
432    }
433
434    #[instrument(level = "trace", skip(self))]
435    fn check_let(&mut self, pat: &'p Pat<'tcx>, scrutinee: Option<ExprId>, span: Span) {
436        assert!(self.let_source != LetSource::None);
437        let scrut = scrutinee.map(|id| &self.thir[id]);
438        if let LetSource::PlainLet = self.let_source {
439            self.check_binding_is_irrefutable(pat, "local binding", scrut, Some(span))
440        } else {
441            let Ok(refutability) = self.is_let_irrefutable(pat, scrut) else { return };
442            if matches!(refutability, Irrefutable) {
443                report_irrefutable_let_patterns(
444                    self.tcx,
445                    self.lint_level,
446                    self.let_source,
447                    1,
448                    span,
449                );
450            }
451        }
452    }
453
454    fn check_match(
455        &mut self,
456        scrut: ExprId,
457        arms: &[ArmId],
458        source: hir::MatchSource,
459        expr_span: Span,
460    ) {
461        let scrut = &self.thir[scrut];
462        let cx = self.new_cx(Refutable, Some(expr_span), Some(scrut), scrut.span);
463
464        let mut tarms = Vec::with_capacity(arms.len());
465        for &arm in arms {
466            let arm = &self.thir.arms[arm];
467            let got_error = self.with_lint_level(arm.lint_level, |this| {
468                let Ok(pat) = this.lower_pattern(&cx, &arm.pattern) else { return true };
469                let arm =
470                    MatchArm { pat, arm_data: this.lint_level, has_guard: arm.guard.is_some() };
471                tarms.push(arm);
472                false
473            });
474            if got_error {
475                return;
476            }
477        }
478
479        let Ok(report) = self.analyze_patterns(&cx, &tarms, scrut.ty) else { return };
480
481        match source {
482            // Don't report arm reachability of desugared `match $iter.into_iter() { iter => .. }`
483            // when the iterator is an uninhabited type. unreachable_code will trigger instead.
484            hir::MatchSource::ForLoopDesugar if arms.len() == 1 => {}
485            hir::MatchSource::ForLoopDesugar
486            | hir::MatchSource::Postfix
487            | hir::MatchSource::Normal
488            | hir::MatchSource::FormatArgs => {
489                let is_match_arm =
490                    matches!(source, hir::MatchSource::Postfix | hir::MatchSource::Normal);
491                report_arm_reachability(&cx, &report, is_match_arm);
492            }
493            // Unreachable patterns in try and await expressions occur when one of
494            // the arms are an uninhabited type. Which is OK.
495            hir::MatchSource::AwaitDesugar | hir::MatchSource::TryDesugar(_) => {}
496        }
497
498        // Check if the match is exhaustive.
499        let witnesses = report.non_exhaustiveness_witnesses;
500        if !witnesses.is_empty() {
501            if source == hir::MatchSource::ForLoopDesugar
502                && let [_, snd_arm] = *arms
503            {
504                // the for loop pattern is not irrefutable
505                let pat = &self.thir[snd_arm].pattern;
506                // `pat` should be `Some(<pat_field>)` from a desugared for loop.
507                debug_assert_eq!(pat.span.desugaring_kind(), Some(DesugaringKind::ForLoop));
508                let PatKind::Variant { ref subpatterns, .. } = pat.kind else { bug!() };
509                let [pat_field] = &subpatterns[..] else { bug!() };
510                self.check_binding_is_irrefutable(
511                    &pat_field.pattern,
512                    "`for` loop binding",
513                    None,
514                    None,
515                );
516            } else {
517                // span after scrutinee, or after `.match`. That is, the braces, arms,
518                // and any whitespace preceding the braces.
519                let braces_span = match source {
520                    hir::MatchSource::Normal => scrut
521                        .span
522                        .find_ancestor_in_same_ctxt(expr_span)
523                        .map(|scrut_span| scrut_span.shrink_to_hi().with_hi(expr_span.hi())),
524                    hir::MatchSource::Postfix => {
525                        // This is horrendous, and we should deal with it by just
526                        // stashing the span of the braces somewhere (like in the match source).
527                        scrut.span.find_ancestor_in_same_ctxt(expr_span).and_then(|scrut_span| {
528                            let sm = self.tcx.sess.source_map();
529                            let brace_span = sm.span_extend_to_next_char(scrut_span, '{', true);
530                            if sm.span_to_snippet(sm.next_point(brace_span)).as_deref() == Ok("{") {
531                                let sp = brace_span.shrink_to_hi().with_hi(expr_span.hi());
532                                // We also need to extend backwards for whitespace
533                                sm.span_extend_prev_while(sp, |c| c.is_whitespace()).ok()
534                            } else {
535                                None
536                            }
537                        })
538                    }
539                    hir::MatchSource::ForLoopDesugar
540                    | hir::MatchSource::TryDesugar(_)
541                    | hir::MatchSource::AwaitDesugar
542                    | hir::MatchSource::FormatArgs => None,
543                };
544                self.error = Err(report_non_exhaustive_match(
545                    &cx,
546                    self.thir,
547                    scrut.ty,
548                    scrut.span,
549                    witnesses,
550                    arms,
551                    braces_span,
552                ));
553            }
554        }
555    }
556
557    #[instrument(level = "trace", skip(self))]
558    fn check_let_chain(
559        &mut self,
560        chain_refutabilities: Vec<Option<(Span, RefutableFlag)>>,
561        whole_chain_span: Span,
562    ) {
563        assert!(self.let_source != LetSource::None);
564
565        if chain_refutabilities.iter().all(|r| matches!(*r, Some((_, Irrefutable)))) {
566            // The entire chain is made up of irrefutable `let` statements
567            report_irrefutable_let_patterns(
568                self.tcx,
569                self.lint_level,
570                self.let_source,
571                chain_refutabilities.len(),
572                whole_chain_span,
573            );
574            return;
575        }
576
577        if let Some(until) =
578            chain_refutabilities.iter().position(|r| !matches!(*r, Some((_, Irrefutable))))
579            && until > 0
580        {
581            // The chain has a non-zero prefix of irrefutable `let` statements.
582
583            // Check if the let source is while, for there is no alternative place to put a prefix,
584            // and we shouldn't lint.
585            // For let guards inside a match, prefixes might use bindings of the match pattern,
586            // so can't always be moved out.
587            // For `else if let`, an extra indentation level would be required to move the bindings.
588            // FIXME: Add checking whether the bindings are actually used in the prefix,
589            // and lint if they are not.
590            if !matches!(
591                self.let_source,
592                LetSource::WhileLet | LetSource::IfLetGuard | LetSource::ElseIfLet
593            ) {
594                // Emit the lint
595                let prefix = &chain_refutabilities[..until];
596                let span_start = prefix[0].unwrap().0;
597                let span_end = prefix.last().unwrap().unwrap().0;
598                let span = span_start.to(span_end);
599                let count = prefix.len();
600                self.tcx.emit_node_span_lint(
601                    IRREFUTABLE_LET_PATTERNS,
602                    self.lint_level,
603                    span,
604                    LeadingIrrefutableLetPatterns { count },
605                );
606            }
607        }
608
609        if let Some(from) =
610            chain_refutabilities.iter().rposition(|r| !matches!(*r, Some((_, Irrefutable))))
611            && from != (chain_refutabilities.len() - 1)
612        {
613            // The chain has a non-empty suffix of irrefutable `let` statements
614            let suffix = &chain_refutabilities[from + 1..];
615            let span_start = suffix[0].unwrap().0;
616            let span_end = suffix.last().unwrap().unwrap().0;
617            let span = span_start.to(span_end);
618            let count = suffix.len();
619            self.tcx.emit_node_span_lint(
620                IRREFUTABLE_LET_PATTERNS,
621                self.lint_level,
622                span,
623                TrailingIrrefutableLetPatterns { count },
624            );
625        }
626    }
627
628    fn analyze_binding(
629        &mut self,
630        pat: &'p Pat<'tcx>,
631        refutability: RefutableFlag,
632        scrut: Option<&Expr<'tcx>>,
633    ) -> Result<(PatCtxt<'p, 'tcx>, UsefulnessReport<'p, 'tcx>), ErrorGuaranteed> {
634        let cx = self.new_cx(refutability, None, scrut, pat.span);
635        let pat = self.lower_pattern(&cx, pat)?;
636        let arms = [MatchArm { pat, arm_data: self.lint_level, has_guard: false }];
637        let report = self.analyze_patterns(&cx, &arms, pat.ty().inner())?;
638        Ok((cx, report))
639    }
640
641    fn is_let_irrefutable(
642        &mut self,
643        pat: &'p Pat<'tcx>,
644        scrut: Option<&Expr<'tcx>>,
645    ) -> Result<RefutableFlag, ErrorGuaranteed> {
646        let (cx, report) = self.analyze_binding(pat, Refutable, scrut)?;
647        // Report if the pattern is unreachable, which can only occur when the type is uninhabited.
648        report_arm_reachability(&cx, &report, false);
649        // If the list of witnesses is empty, the match is exhaustive, i.e. the `if let` pattern is
650        // irrefutable.
651        Ok(if report.non_exhaustiveness_witnesses.is_empty() { Irrefutable } else { Refutable })
652    }
653
654    #[instrument(level = "trace", skip(self))]
655    fn check_binding_is_irrefutable(
656        &mut self,
657        pat: &'p Pat<'tcx>,
658        origin: &str,
659        scrut: Option<&Expr<'tcx>>,
660        sp: Option<Span>,
661    ) {
662        let pattern_ty = pat.ty;
663
664        let Ok((cx, report)) = self.analyze_binding(pat, Irrefutable, scrut) else { return };
665        let witnesses = report.non_exhaustiveness_witnesses;
666        if witnesses.is_empty() {
667            // The pattern is irrefutable.
668            return;
669        }
670
671        let inform = sp.is_some().then_some(Inform);
672        let mut let_suggestion = None;
673        let mut misc_suggestion = None;
674        let mut interpreted_as_const = None;
675        let mut interpreted_as_const_sugg = None;
676
677        // These next few matches want to peek through `AscribeUserType` to see
678        // the underlying pattern.
679        let mut unpeeled_pat = pat;
680        while let PatKind::AscribeUserType { ref subpattern, .. } = unpeeled_pat.kind {
681            unpeeled_pat = subpattern;
682        }
683
684        if let PatKind::ExpandedConstant { def_id, .. } = unpeeled_pat.kind
685            && let DefKind::Const = self.tcx.def_kind(def_id)
686            && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(pat.span)
687            // We filter out paths with multiple path::segments.
688            && snippet.chars().all(|c| c.is_alphanumeric() || c == '_')
689        {
690            let span = self.tcx.def_span(def_id);
691            let variable = self.tcx.item_name(def_id).to_string();
692            // When we encounter a constant as the binding name, point at the `const` definition.
693            interpreted_as_const = Some(InterpretedAsConst { span, variable: variable.clone() });
694            interpreted_as_const_sugg = Some(InterpretedAsConstSugg { span: pat.span, variable });
695        } else if let PatKind::Constant { .. } = unpeeled_pat.kind
696            && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(pat.span)
697        {
698            // If the pattern to match is an integer literal:
699            if snippet.chars().all(|c| c.is_digit(10)) {
700                // Then give a suggestion, the user might've meant to create a binding instead.
701                misc_suggestion = Some(MiscPatternSuggestion::AttemptedIntegerLiteral {
702                    start_span: pat.span.shrink_to_lo(),
703                });
704            }
705        }
706
707        if let Some(span) = sp
708            && self.tcx.sess.source_map().is_span_accessible(span)
709            && interpreted_as_const.is_none()
710            && scrut.is_some()
711        {
712            let mut bindings = vec![];
713            pat.each_binding(|name, _, _, _| bindings.push(name));
714
715            let semi_span = span.shrink_to_hi();
716            let start_span = span.shrink_to_lo();
717            let end_span = semi_span.shrink_to_lo();
718            let count = witnesses.len();
719
720            let_suggestion = Some(if bindings.is_empty() {
721                SuggestLet::If { start_span, semi_span, count }
722            } else {
723                SuggestLet::Else { end_span, count }
724            });
725        };
726
727        let adt_defined_here = report_adt_defined_here(self.tcx, pattern_ty, &witnesses, false);
728
729        // Emit an extra note if the first uncovered witness would be uninhabited
730        // if we disregard visibility.
731        let witness_1_is_privately_uninhabited = if let Some(witness_1) = witnesses.get(0)
732            && let ty::Adt(adt, args) = witness_1.ty().kind()
733            && adt.is_enum()
734            && let Constructor::Variant(variant_index) = witness_1.ctor()
735        {
736            let variant_inhabited = adt
737                .variant(*variant_index)
738                .inhabited_predicate(self.tcx, *adt)
739                .instantiate(self.tcx, args);
740            variant_inhabited.apply(self.tcx, cx.typing_env, cx.module)
741                && !variant_inhabited.apply_ignore_module(self.tcx, cx.typing_env)
742        } else {
743            false
744        };
745
746        let witness_1 = cx.print_witness_pat(witnesses.get(0).unwrap());
747
748        self.error = Err(self.tcx.dcx().emit_err(PatternNotCovered {
749            span: pat.span,
750            origin,
751            uncovered: Uncovered::new(pat.span, &cx, witnesses),
752            inform,
753            interpreted_as_const,
754            interpreted_as_const_sugg,
755            witness_1_is_privately_uninhabited,
756            witness_1,
757            _p: (),
758            pattern_ty,
759            let_suggestion,
760            misc_suggestion,
761            adt_defined_here,
762        }));
763    }
764}
765
766/// Check if a by-value binding is by-value. That is, check if the binding's type is not `Copy`.
767/// Check that there are no borrow or move conflicts in `binding @ subpat` patterns.
768///
769/// For example, this would reject:
770/// - `ref x @ Some(ref mut y)`,
771/// - `ref mut x @ Some(ref y)`,
772/// - `ref mut x @ Some(ref mut y)`,
773/// - `ref mut? x @ Some(y)`, and
774/// - `x @ Some(ref mut? y)`.
775///
776/// This analysis is *not* subsumed by NLL.
777fn check_borrow_conflicts_in_at_patterns<'tcx>(cx: &MatchVisitor<'_, 'tcx>, pat: &Pat<'tcx>) {
778    // Extract `sub` in `binding @ sub`.
779    let PatKind::Binding { name, mode, ty, subpattern: Some(box ref sub), .. } = pat.kind else {
780        return;
781    };
782
783    let is_binding_by_move = |ty: Ty<'tcx>| !cx.tcx.type_is_copy_modulo_regions(cx.typing_env, ty);
784
785    let sess = cx.tcx.sess;
786
787    // Get the binding move, extract the mutability if by-ref.
788    let mut_outer = match mode.0 {
789        ByRef::No if is_binding_by_move(ty) => {
790            // We have `x @ pat` where `x` is by-move. Reject all borrows in `pat`.
791            let mut conflicts_ref = Vec::new();
792            sub.each_binding(|_, mode, _, span| {
793                if matches!(mode, ByRef::Yes(_)) {
794                    conflicts_ref.push(span)
795                }
796            });
797            if !conflicts_ref.is_empty() {
798                sess.dcx().emit_err(BorrowOfMovedValue {
799                    binding_span: pat.span,
800                    conflicts_ref,
801                    name: Ident::new(name, pat.span),
802                    ty,
803                    suggest_borrowing: Some(pat.span.shrink_to_lo()),
804                });
805            }
806            return;
807        }
808        ByRef::No => return,
809        ByRef::Yes(m) => m,
810    };
811
812    // We now have `ref $mut_outer binding @ sub` (semantically).
813    // Recurse into each binding in `sub` and find mutability or move conflicts.
814    let mut conflicts_move = Vec::new();
815    let mut conflicts_mut_mut = Vec::new();
816    let mut conflicts_mut_ref = Vec::new();
817    sub.each_binding(|name, mode, ty, span| {
818        match mode {
819            ByRef::Yes(mut_inner) => match (mut_outer, mut_inner) {
820                // Both sides are `ref`.
821                (Mutability::Not, Mutability::Not) => {}
822                // 2x `ref mut`.
823                (Mutability::Mut, Mutability::Mut) => {
824                    conflicts_mut_mut.push(Conflict::Mut { span, name })
825                }
826                (Mutability::Not, Mutability::Mut) => {
827                    conflicts_mut_ref.push(Conflict::Mut { span, name })
828                }
829                (Mutability::Mut, Mutability::Not) => {
830                    conflicts_mut_ref.push(Conflict::Ref { span, name })
831                }
832            },
833            ByRef::No if is_binding_by_move(ty) => {
834                conflicts_move.push(Conflict::Moved { span, name }) // `ref mut?` + by-move conflict.
835            }
836            ByRef::No => {} // `ref mut?` + by-copy is fine.
837        }
838    });
839
840    let report_mut_mut = !conflicts_mut_mut.is_empty();
841    let report_mut_ref = !conflicts_mut_ref.is_empty();
842    let report_move_conflict = !conflicts_move.is_empty();
843
844    let mut occurrences = match mut_outer {
845        Mutability::Mut => vec![Conflict::Mut { span: pat.span, name }],
846        Mutability::Not => vec![Conflict::Ref { span: pat.span, name }],
847    };
848    occurrences.extend(conflicts_mut_mut);
849    occurrences.extend(conflicts_mut_ref);
850    occurrences.extend(conflicts_move);
851
852    // Report errors if any.
853    if report_mut_mut {
854        // Report mutability conflicts for e.g. `ref mut x @ Some(ref mut y)`.
855        sess.dcx().emit_err(MultipleMutBorrows { span: pat.span, occurrences });
856    } else if report_mut_ref {
857        // Report mutability conflicts for e.g. `ref x @ Some(ref mut y)` or the converse.
858        match mut_outer {
859            Mutability::Mut => {
860                sess.dcx().emit_err(AlreadyMutBorrowed { span: pat.span, occurrences });
861            }
862            Mutability::Not => {
863                sess.dcx().emit_err(AlreadyBorrowed { span: pat.span, occurrences });
864            }
865        };
866    } else if report_move_conflict {
867        // Report by-ref and by-move conflicts, e.g. `ref x @ y`.
868        sess.dcx().emit_err(MovedWhileBorrowed { span: pat.span, occurrences });
869    }
870}
871
872fn check_for_bindings_named_same_as_variants(
873    cx: &MatchVisitor<'_, '_>,
874    pat: &Pat<'_>,
875    rf: RefutableFlag,
876) {
877    if let PatKind::Binding {
878        name,
879        mode: BindingMode(ByRef::No, Mutability::Not),
880        subpattern: None,
881        ty,
882        ..
883    } = pat.kind
884        && let ty::Adt(edef, _) = ty.peel_refs().kind()
885        && edef.is_enum()
886        && edef
887            .variants()
888            .iter()
889            .any(|variant| variant.name == name && variant.ctor_kind() == Some(CtorKind::Const))
890    {
891        let variant_count = edef.variants().len();
892        let ty_path = with_no_trimmed_paths!(cx.tcx.def_path_str(edef.did()));
893        cx.tcx.emit_node_span_lint(
894            BINDINGS_WITH_VARIANT_NAME,
895            cx.lint_level,
896            pat.span,
897            BindingsWithVariantName {
898                // If this is an irrefutable pattern, and there's > 1 variant,
899                // then we can't actually match on this. Applying the below
900                // suggestion would produce code that breaks on `check_binding_is_irrefutable`.
901                suggestion: if rf == Refutable || variant_count == 1 {
902                    Some(pat.span)
903                } else {
904                    None
905                },
906                ty_path,
907                name: Ident::new(name, pat.span),
908            },
909        )
910    }
911}
912
913/// Check that never patterns are only used on inhabited types.
914fn check_never_pattern<'tcx>(
915    cx: &PatCtxt<'_, 'tcx>,
916    pat: &Pat<'tcx>,
917) -> Result<(), ErrorGuaranteed> {
918    if let PatKind::Never = pat.kind {
919        if !cx.is_uninhabited(pat.ty) {
920            return Err(cx.tcx.dcx().emit_err(NonEmptyNeverPattern { span: pat.span, ty: pat.ty }));
921        }
922    }
923    Ok(())
924}
925
926fn report_irrefutable_let_patterns(
927    tcx: TyCtxt<'_>,
928    id: HirId,
929    source: LetSource,
930    count: usize,
931    span: Span,
932) {
933    macro_rules! emit_diag {
934        ($lint:tt) => {{
935            tcx.emit_node_span_lint(IRREFUTABLE_LET_PATTERNS, id, span, $lint { count });
936        }};
937    }
938
939    match source {
940        LetSource::None | LetSource::PlainLet | LetSource::Else => bug!(),
941        LetSource::IfLet | LetSource::ElseIfLet => emit_diag!(IrrefutableLetPatternsIfLet),
942        LetSource::IfLetGuard => emit_diag!(IrrefutableLetPatternsIfLetGuard),
943        LetSource::LetElse => emit_diag!(IrrefutableLetPatternsLetElse),
944        LetSource::WhileLet => emit_diag!(IrrefutableLetPatternsWhileLet),
945    }
946}
947
948/// Report unreachable arms, if any.
949fn report_unreachable_pattern<'p, 'tcx>(
950    cx: &PatCtxt<'p, 'tcx>,
951    hir_id: HirId,
952    pat: &DeconstructedPat<'p, 'tcx>,
953    explanation: &RedundancyExplanation<'p, 'tcx>,
954    whole_arm_span: Option<Span>,
955) {
956    static CAP_COVERED_BY_MANY: usize = 4;
957    let pat_span = pat.data().span;
958    let mut lint = UnreachablePattern {
959        span: Some(pat_span),
960        matches_no_values: None,
961        matches_no_values_ty: **pat.ty(),
962        uninhabited_note: None,
963        covered_by_catchall: None,
964        covered_by_one: None,
965        covered_by_many: None,
966        covered_by_many_n_more_count: 0,
967        wanted_constant: None,
968        accessible_constant: None,
969        inaccessible_constant: None,
970        pattern_let_binding: None,
971        suggest_remove: None,
972    };
973    match explanation.covered_by.as_slice() {
974        [] => {
975            // Empty pattern; we report the uninhabited type that caused the emptiness.
976            lint.span = None; // Don't label the pattern itself
977            lint.uninhabited_note = Some(()); // Give a link about empty types
978            lint.matches_no_values = Some(pat_span);
979            lint.suggest_remove = whole_arm_span; // Suggest to remove the match arm
980            pat.walk(&mut |subpat| {
981                let ty = **subpat.ty();
982                if cx.is_uninhabited(ty) {
983                    lint.matches_no_values_ty = ty;
984                    false // No need to dig further.
985                } else if matches!(subpat.ctor(), Constructor::Ref | Constructor::UnionField) {
986                    false // Don't explore further since they are not by-value.
987                } else {
988                    true
989                }
990            });
991        }
992        [covering_pat] if pat_is_catchall(covering_pat) => {
993            // A binding pattern that matches all, a single binding name.
994            let pat = covering_pat.data();
995            lint.covered_by_catchall = Some(pat.span);
996            find_fallback_pattern_typo(cx, hir_id, pat, &mut lint);
997        }
998        [covering_pat] => {
999            lint.covered_by_one = Some(covering_pat.data().span);
1000        }
1001        covering_pats => {
1002            let mut iter = covering_pats.iter();
1003            let mut multispan = MultiSpan::from_span(pat_span);
1004            for p in iter.by_ref().take(CAP_COVERED_BY_MANY) {
1005                multispan.push_span_label(
1006                    p.data().span,
1007                    fluent::mir_build_unreachable_matches_same_values,
1008                );
1009            }
1010            let remain = iter.count();
1011            if remain == 0 {
1012                multispan.push_span_label(
1013                    pat_span,
1014                    fluent::mir_build_unreachable_making_this_unreachable,
1015                );
1016            } else {
1017                lint.covered_by_many_n_more_count = remain;
1018                multispan.push_span_label(
1019                    pat_span,
1020                    fluent::mir_build_unreachable_making_this_unreachable_n_more,
1021                );
1022            }
1023            lint.covered_by_many = Some(multispan);
1024        }
1025    }
1026    cx.tcx.emit_node_span_lint(UNREACHABLE_PATTERNS, hir_id, pat_span, lint);
1027}
1028
1029/// Detect typos that were meant to be a `const` but were interpreted as a new pattern binding.
1030fn find_fallback_pattern_typo<'tcx>(
1031    cx: &PatCtxt<'_, 'tcx>,
1032    hir_id: HirId,
1033    pat: &Pat<'tcx>,
1034    lint: &mut UnreachablePattern<'_>,
1035) {
1036    if let Level::Allow = cx.tcx.lint_level_at_node(UNREACHABLE_PATTERNS, hir_id).level {
1037        // This is because we use `with_no_trimmed_paths` later, so if we never emit the lint we'd
1038        // ICE. At the same time, we don't really need to do all of this if we won't emit anything.
1039        return;
1040    }
1041    if let PatKind::Binding { name, subpattern: None, ty, .. } = pat.kind {
1042        // See if the binding might have been a `const` that was mistyped or out of scope.
1043        let mut accessible = vec![];
1044        let mut accessible_path = vec![];
1045        let mut inaccessible = vec![];
1046        let mut imported = vec![];
1047        let mut imported_spans = vec![];
1048        let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(cx.typing_env);
1049        let parent = cx.tcx.hir_get_parent_item(hir_id);
1050
1051        for item in cx.tcx.hir_crate_items(()).free_items() {
1052            if let DefKind::Use = cx.tcx.def_kind(item.owner_id) {
1053                // Look for consts being re-exported.
1054                let item = cx.tcx.hir_expect_item(item.owner_id.def_id);
1055                let hir::ItemKind::Use(path, _) = item.kind else {
1056                    continue;
1057                };
1058                if let Some(value_ns) = path.res.value_ns
1059                    && let Res::Def(DefKind::Const, id) = value_ns
1060                    && infcx.can_eq(param_env, ty, cx.tcx.type_of(id).instantiate_identity())
1061                {
1062                    if cx.tcx.visibility(id).is_accessible_from(parent, cx.tcx) {
1063                        // The original const is accessible, suggest using it directly.
1064                        let item_name = cx.tcx.item_name(id);
1065                        accessible.push(item_name);
1066                        accessible_path.push(with_no_trimmed_paths!(cx.tcx.def_path_str(id)));
1067                    } else if cx.tcx.visibility(item.owner_id).is_accessible_from(parent, cx.tcx) {
1068                        // The const is accessible only through the re-export, point at
1069                        // the `use`.
1070                        let ident = item.kind.ident().unwrap();
1071                        imported.push(ident.name);
1072                        imported_spans.push(ident.span);
1073                    }
1074                }
1075            }
1076            if let DefKind::Const = cx.tcx.def_kind(item.owner_id)
1077                && infcx.can_eq(param_env, ty, cx.tcx.type_of(item.owner_id).instantiate_identity())
1078            {
1079                // Look for local consts.
1080                let item_name = cx.tcx.item_name(item.owner_id.into());
1081                let vis = cx.tcx.visibility(item.owner_id);
1082                if vis.is_accessible_from(parent, cx.tcx) {
1083                    accessible.push(item_name);
1084                    // FIXME: the line below from PR #135310 is a workaround for the ICE in issue
1085                    // #135289, where a macro in a dependency can create unreachable patterns in the
1086                    // current crate. Path trimming expects diagnostics for a typoed const, but no
1087                    // diagnostics are emitted and we ICE. See
1088                    // `tests/ui/resolve/const-with-typo-in-pattern-binding-ice-135289.rs` for a
1089                    // test that reproduces the ICE if we don't use `with_no_trimmed_paths!`.
1090                    let path = with_no_trimmed_paths!(cx.tcx.def_path_str(item.owner_id));
1091                    accessible_path.push(path);
1092                } else if name == item_name {
1093                    // The const exists somewhere in this crate, but it can't be imported
1094                    // from this pattern's scope. We'll just point at its definition.
1095                    inaccessible.push(cx.tcx.def_span(item.owner_id));
1096                }
1097            }
1098        }
1099        if let Some((i, &const_name)) =
1100            accessible.iter().enumerate().find(|&(_, &const_name)| const_name == name)
1101        {
1102            // The pattern name is an exact match, so the pattern needed to be imported.
1103            lint.wanted_constant = Some(WantedConstant {
1104                span: pat.span,
1105                is_typo: false,
1106                const_name: const_name.to_string(),
1107                const_path: accessible_path[i].clone(),
1108            });
1109        } else if let Some(name) = find_best_match_for_name(&accessible, name, None) {
1110            // The pattern name is likely a typo.
1111            lint.wanted_constant = Some(WantedConstant {
1112                span: pat.span,
1113                is_typo: true,
1114                const_name: name.to_string(),
1115                const_path: name.to_string(),
1116            });
1117        } else if let Some(i) =
1118            imported.iter().enumerate().find(|&(_, &const_name)| const_name == name).map(|(i, _)| i)
1119        {
1120            // The const with the exact name wasn't re-exported from an import in this
1121            // crate, we point at the import.
1122            lint.accessible_constant = Some(imported_spans[i]);
1123        } else if let Some(name) = find_best_match_for_name(&imported, name, None) {
1124            // The typoed const wasn't re-exported by an import in this crate, we suggest
1125            // the right name (which will likely require another follow up suggestion).
1126            lint.wanted_constant = Some(WantedConstant {
1127                span: pat.span,
1128                is_typo: true,
1129                const_path: name.to_string(),
1130                const_name: name.to_string(),
1131            });
1132        } else if !inaccessible.is_empty() {
1133            for span in inaccessible {
1134                // The const with the exact name match isn't accessible, we just point at it.
1135                lint.inaccessible_constant = Some(span);
1136            }
1137        } else {
1138            // Look for local bindings for people that might have gotten confused with how
1139            // `let` and `const` works.
1140            for (_, node) in cx.tcx.hir_parent_iter(hir_id) {
1141                match node {
1142                    hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Let(let_stmt), .. }) => {
1143                        if let hir::PatKind::Binding(_, _, binding_name, _) = let_stmt.pat.kind {
1144                            if name == binding_name.name {
1145                                lint.pattern_let_binding = Some(binding_name.span);
1146                            }
1147                        }
1148                    }
1149                    hir::Node::Block(hir::Block { stmts, .. }) => {
1150                        for stmt in *stmts {
1151                            if let hir::StmtKind::Let(let_stmt) = stmt.kind {
1152                                if let hir::PatKind::Binding(_, _, binding_name, _) =
1153                                    let_stmt.pat.kind
1154                                {
1155                                    if name == binding_name.name {
1156                                        lint.pattern_let_binding = Some(binding_name.span);
1157                                    }
1158                                }
1159                            }
1160                        }
1161                    }
1162                    hir::Node::Item(_) => break,
1163                    _ => {}
1164                }
1165            }
1166        }
1167    }
1168}
1169
1170/// Report unreachable arms, if any.
1171fn report_arm_reachability<'p, 'tcx>(
1172    cx: &PatCtxt<'p, 'tcx>,
1173    report: &UsefulnessReport<'p, 'tcx>,
1174    is_match_arm: bool,
1175) {
1176    let sm = cx.tcx.sess.source_map();
1177    for (arm, is_useful) in report.arm_usefulness.iter() {
1178        if let Usefulness::Redundant(explanation) = is_useful {
1179            let hir_id = arm.arm_data;
1180            let arm_span = cx.tcx.hir_span(hir_id);
1181            let whole_arm_span = if is_match_arm {
1182                // If the arm is followed by a comma, extend the span to include it.
1183                let with_whitespace = sm.span_extend_while_whitespace(arm_span);
1184                if let Some(comma) = sm.span_look_ahead(with_whitespace, ",", Some(1)) {
1185                    Some(arm_span.to(comma))
1186                } else {
1187                    Some(arm_span)
1188                }
1189            } else {
1190                None
1191            };
1192            report_unreachable_pattern(cx, hir_id, arm.pat, explanation, whole_arm_span)
1193        }
1194    }
1195}
1196
1197/// Checks for common cases of "catchall" patterns that may not be intended as such.
1198fn pat_is_catchall(pat: &DeconstructedPat<'_, '_>) -> bool {
1199    match pat.ctor() {
1200        Constructor::Wildcard => true,
1201        Constructor::Struct | Constructor::Ref => {
1202            pat.iter_fields().all(|ipat| pat_is_catchall(&ipat.pat))
1203        }
1204        _ => false,
1205    }
1206}
1207
1208/// Report that a match is not exhaustive.
1209fn report_non_exhaustive_match<'p, 'tcx>(
1210    cx: &PatCtxt<'p, 'tcx>,
1211    thir: &Thir<'tcx>,
1212    scrut_ty: Ty<'tcx>,
1213    sp: Span,
1214    witnesses: Vec<WitnessPat<'p, 'tcx>>,
1215    arms: &[ArmId],
1216    braces_span: Option<Span>,
1217) -> ErrorGuaranteed {
1218    let is_empty_match = arms.is_empty();
1219    let non_empty_enum = match scrut_ty.kind() {
1220        ty::Adt(def, _) => def.is_enum() && !def.variants().is_empty(),
1221        _ => false,
1222    };
1223    // In the case of an empty match, replace the '`_` not covered' diagnostic with something more
1224    // informative.
1225    if is_empty_match && !non_empty_enum {
1226        return cx.tcx.dcx().emit_err(NonExhaustivePatternsTypeNotEmpty {
1227            cx,
1228            scrut_span: sp,
1229            braces_span,
1230            ty: scrut_ty,
1231        });
1232    }
1233
1234    // FIXME: migration of this diagnostic will require list support
1235    let joined_patterns = joined_uncovered_patterns(cx, &witnesses);
1236    let mut err = struct_span_code_err!(
1237        cx.tcx.dcx(),
1238        sp,
1239        E0004,
1240        "non-exhaustive patterns: {joined_patterns} not covered"
1241    );
1242    err.span_label(
1243        sp,
1244        format!(
1245            "pattern{} {} not covered",
1246            rustc_errors::pluralize!(witnesses.len()),
1247            joined_patterns
1248        ),
1249    );
1250
1251    // Point at the definition of non-covered `enum` variants.
1252    if let Some(AdtDefinedHere { adt_def_span, ty, variants }) =
1253        report_adt_defined_here(cx.tcx, scrut_ty, &witnesses, true)
1254    {
1255        let mut multi_span = MultiSpan::from_span(adt_def_span);
1256        multi_span.push_span_label(adt_def_span, "");
1257        for Variant { span } in variants {
1258            multi_span.push_span_label(span, "not covered");
1259        }
1260        err.span_note(multi_span, format!("`{ty}` defined here"));
1261    }
1262    err.note(format!("the matched value is of type `{}`", scrut_ty));
1263
1264    if !is_empty_match {
1265        let mut special_tys = FxIndexSet::default();
1266        // Look at the first witness.
1267        collect_special_tys(cx, &witnesses[0], &mut special_tys);
1268
1269        for ty in special_tys {
1270            if ty.is_ptr_sized_integral() {
1271                if ty.inner() == cx.tcx.types.usize {
1272                    err.note(format!(
1273                        "`{ty}` does not have a fixed maximum value, so half-open ranges are \
1274                         necessary to match exhaustively",
1275                    ));
1276                } else if ty.inner() == cx.tcx.types.isize {
1277                    err.note(format!(
1278                        "`{ty}` does not have fixed minimum and maximum values, so half-open \
1279                         ranges are necessary to match exhaustively",
1280                    ));
1281                }
1282            } else if ty.inner() == cx.tcx.types.str_ {
1283                err.note("`&str` cannot be matched exhaustively, so a wildcard `_` is necessary");
1284            } else if cx.is_foreign_non_exhaustive_enum(ty) {
1285                err.note(format!("`{ty}` is marked as non-exhaustive, so a wildcard `_` is necessary to match exhaustively"));
1286            } else if cx.is_uninhabited(ty.inner()) {
1287                // The type is uninhabited yet there is a witness: we must be in the `MaybeInvalid`
1288                // case.
1289                err.note(format!("`{ty}` is uninhabited but is not being matched by value, so a wildcard `_` is required"));
1290            }
1291        }
1292    }
1293
1294    if let ty::Ref(_, sub_ty, _) = scrut_ty.kind() {
1295        if !sub_ty.is_inhabited_from(cx.tcx, cx.module, cx.typing_env) {
1296            err.note("references are always considered inhabited");
1297        }
1298    }
1299
1300    for &arm in arms {
1301        let arm = &thir.arms[arm];
1302        if let PatKind::ExpandedConstant { def_id, .. } = arm.pattern.kind
1303            && !matches!(cx.tcx.def_kind(def_id), DefKind::InlineConst)
1304            && let Ok(snippet) = cx.tcx.sess.source_map().span_to_snippet(arm.pattern.span)
1305            // We filter out paths with multiple path::segments.
1306            && snippet.chars().all(|c| c.is_alphanumeric() || c == '_')
1307        {
1308            let const_name = cx.tcx.item_name(def_id);
1309            err.span_label(
1310                arm.pattern.span,
1311                format!(
1312                    "this pattern doesn't introduce a new catch-all binding, but rather pattern \
1313                     matches against the value of constant `{const_name}`",
1314                ),
1315            );
1316            err.span_note(cx.tcx.def_span(def_id), format!("constant `{const_name}` defined here"));
1317            err.span_suggestion_verbose(
1318                arm.pattern.span.shrink_to_hi(),
1319                "if you meant to introduce a binding, use a different name",
1320                "_var".to_string(),
1321                Applicability::MaybeIncorrect,
1322            );
1323        }
1324    }
1325
1326    // Whether we suggest the actual missing patterns or `_`.
1327    let suggest_the_witnesses = witnesses.len() < 4;
1328    let suggested_arm = if suggest_the_witnesses {
1329        let pattern = witnesses
1330            .iter()
1331            .map(|witness| cx.print_witness_pat(witness))
1332            .collect::<Vec<String>>()
1333            .join(" | ");
1334        if witnesses.iter().all(|p| p.is_never_pattern()) && cx.tcx.features().never_patterns() {
1335            // Arms with a never pattern don't take a body.
1336            pattern
1337        } else {
1338            format!("{pattern} => todo!()")
1339        }
1340    } else {
1341        format!("_ => todo!()")
1342    };
1343    let mut suggestion = None;
1344    let sm = cx.tcx.sess.source_map();
1345    match arms {
1346        [] if let Some(braces_span) = braces_span => {
1347            // Get the span for the empty match body `{}`.
1348            let (indentation, more) = if let Some(snippet) = sm.indentation_before(sp) {
1349                (format!("\n{snippet}"), "    ")
1350            } else {
1351                (" ".to_string(), "")
1352            };
1353            suggestion = Some((
1354                braces_span,
1355                format!(" {{{indentation}{more}{suggested_arm},{indentation}}}",),
1356            ));
1357        }
1358        [only] => {
1359            let only = &thir[*only];
1360            let (pre_indentation, is_multiline) = if let Some(snippet) =
1361                sm.indentation_before(only.span)
1362                && let Ok(with_trailing) =
1363                    sm.span_extend_while(only.span, |c| c.is_whitespace() || c == ',')
1364                && sm.is_multiline(with_trailing)
1365            {
1366                (format!("\n{snippet}"), true)
1367            } else {
1368                (" ".to_string(), false)
1369            };
1370            let only_body = &thir[only.body];
1371            let comma = if matches!(only_body.kind, ExprKind::Block { .. })
1372                && only.span.eq_ctxt(only_body.span)
1373                && is_multiline
1374            {
1375                ""
1376            } else {
1377                ","
1378            };
1379            suggestion = Some((
1380                only.span.shrink_to_hi(),
1381                format!("{comma}{pre_indentation}{suggested_arm}"),
1382            ));
1383        }
1384        [.., prev, last] => {
1385            let prev = &thir[*prev];
1386            let last = &thir[*last];
1387            if prev.span.eq_ctxt(last.span) {
1388                let last_body = &thir[last.body];
1389                let comma = if matches!(last_body.kind, ExprKind::Block { .. })
1390                    && last.span.eq_ctxt(last_body.span)
1391                {
1392                    ""
1393                } else {
1394                    ","
1395                };
1396                let spacing = if sm.is_multiline(prev.span.between(last.span)) {
1397                    sm.indentation_before(last.span).map(|indent| format!("\n{indent}"))
1398                } else {
1399                    Some(" ".to_string())
1400                };
1401                if let Some(spacing) = spacing {
1402                    suggestion = Some((
1403                        last.span.shrink_to_hi(),
1404                        format!("{comma}{spacing}{suggested_arm}"),
1405                    ));
1406                }
1407            }
1408        }
1409        _ => {}
1410    }
1411
1412    let msg = format!(
1413        "ensure that all possible cases are being handled by adding a match arm with a wildcard \
1414         pattern{}{}",
1415        if witnesses.len() > 1 && suggest_the_witnesses && suggestion.is_some() {
1416            ", a match arm with multiple or-patterns"
1417        } else {
1418            // we are either not suggesting anything, or suggesting `_`
1419            ""
1420        },
1421        match witnesses.len() {
1422            // non-exhaustive enum case
1423            0 if suggestion.is_some() => " as shown",
1424            0 => "",
1425            1 if suggestion.is_some() => " or an explicit pattern as shown",
1426            1 => " or an explicit pattern",
1427            _ if suggestion.is_some() => " as shown, or multiple match arms",
1428            _ => " or multiple match arms",
1429        },
1430    );
1431
1432    let all_arms_have_guards = arms.iter().all(|arm_id| thir[*arm_id].guard.is_some());
1433    if !is_empty_match && all_arms_have_guards {
1434        err.subdiagnostic(NonExhaustiveMatchAllArmsGuarded);
1435    }
1436    if let Some((span, sugg)) = suggestion {
1437        err.span_suggestion_verbose(span, msg, sugg, Applicability::HasPlaceholders);
1438    } else {
1439        err.help(msg);
1440    }
1441    err.emit()
1442}
1443
1444fn joined_uncovered_patterns<'p, 'tcx>(
1445    cx: &PatCtxt<'p, 'tcx>,
1446    witnesses: &[WitnessPat<'p, 'tcx>],
1447) -> String {
1448    const LIMIT: usize = 3;
1449    let pat_to_str = |pat: &WitnessPat<'p, 'tcx>| cx.print_witness_pat(pat);
1450    match witnesses {
1451        [] => bug!(),
1452        [witness] => format!("`{}`", cx.print_witness_pat(witness)),
1453        [head @ .., tail] if head.len() < LIMIT => {
1454            let head: Vec<_> = head.iter().map(pat_to_str).collect();
1455            format!("`{}` and `{}`", head.join("`, `"), cx.print_witness_pat(tail))
1456        }
1457        _ => {
1458            let (head, tail) = witnesses.split_at(LIMIT);
1459            let head: Vec<_> = head.iter().map(pat_to_str).collect();
1460            format!("`{}` and {} more", head.join("`, `"), tail.len())
1461        }
1462    }
1463}
1464
1465/// Collect types that require specific explanations when they show up in witnesses.
1466fn collect_special_tys<'tcx>(
1467    cx: &PatCtxt<'_, 'tcx>,
1468    pat: &WitnessPat<'_, 'tcx>,
1469    special_tys: &mut FxIndexSet<RevealedTy<'tcx>>,
1470) {
1471    if matches!(pat.ctor(), Constructor::NonExhaustive | Constructor::Never) {
1472        special_tys.insert(*pat.ty());
1473    }
1474    if let Constructor::IntRange(range) = pat.ctor() {
1475        if cx.is_range_beyond_boundaries(range, *pat.ty()) {
1476            // The range denotes the values before `isize::MIN` or the values after `usize::MAX`/`isize::MAX`.
1477            special_tys.insert(*pat.ty());
1478        }
1479    }
1480    pat.iter_fields().for_each(|field_pat| collect_special_tys(cx, field_pat, special_tys))
1481}
1482
1483fn report_adt_defined_here<'tcx>(
1484    tcx: TyCtxt<'tcx>,
1485    ty: Ty<'tcx>,
1486    witnesses: &[WitnessPat<'_, 'tcx>],
1487    point_at_non_local_ty: bool,
1488) -> Option<AdtDefinedHere<'tcx>> {
1489    let ty = ty.peel_refs();
1490    let ty::Adt(def, _) = ty.kind() else {
1491        return None;
1492    };
1493    let adt_def_span =
1494        tcx.hir_get_if_local(def.did()).and_then(|node| node.ident()).map(|ident| ident.span);
1495    let adt_def_span = if point_at_non_local_ty {
1496        adt_def_span.unwrap_or_else(|| tcx.def_span(def.did()))
1497    } else {
1498        adt_def_span?
1499    };
1500
1501    let mut variants = vec![];
1502    for span in maybe_point_at_variant(tcx, *def, witnesses.iter().take(5)) {
1503        variants.push(Variant { span });
1504    }
1505    Some(AdtDefinedHere { adt_def_span, ty, variants })
1506}
1507
1508fn maybe_point_at_variant<'a, 'p: 'a, 'tcx: 'p>(
1509    tcx: TyCtxt<'tcx>,
1510    def: AdtDef<'tcx>,
1511    patterns: impl Iterator<Item = &'a WitnessPat<'p, 'tcx>>,
1512) -> Vec<Span> {
1513    let mut covered = vec![];
1514    for pattern in patterns {
1515        if let Constructor::Variant(variant_index) = pattern.ctor() {
1516            if let ty::Adt(this_def, _) = pattern.ty().kind()
1517                && this_def.did() != def.did()
1518            {
1519                continue;
1520            }
1521            let sp = def.variant(*variant_index).ident(tcx).span;
1522            if covered.contains(&sp) {
1523                // Don't point at variants that have already been covered due to other patterns to avoid
1524                // visual clutter.
1525                continue;
1526            }
1527            covered.push(sp);
1528        }
1529        covered.extend(maybe_point_at_variant(tcx, def, pattern.iter_fields()));
1530    }
1531    covered
1532}