Skip to main content

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, msg, struct_span_code_err};
7use rustc_hir::def::*;
8use rustc_hir::def_id::{DefId, LocalDefId};
9use rustc_hir::{self as hir, BindingMode, ByRef, HirId, MatchSource};
10use rustc_infer::infer::TyCtxtInferExt;
11use rustc_lint_defs::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::*;
32
33pub(crate) fn check_match(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
34    let typeck_results = tcx.typeck(def_id);
35    let (thir, expr) = tcx.thir_body(def_id)?;
36    let thir = thir.borrow();
37    let pattern_arena = TypedArena::default();
38    let dropless_arena = DroplessArena::default();
39    let mut visitor = MatchVisitor {
40        tcx,
41        thir: &*thir,
42        typeck_results,
43        // FIXME(#132279): We're in a body, should handle opaques.
44        typing_env: ty::TypingEnv::non_body_analysis(tcx, def_id),
45        hir_source: tcx.local_def_id_to_hir_id(def_id),
46        let_source: LetSource::None,
47        pattern_arena: &pattern_arena,
48        dropless_arena: &dropless_arena,
49        error: Ok(()),
50    };
51    visitor.visit_expr(&thir[expr]);
52
53    let origin = match tcx.def_kind(def_id) {
54        DefKind::AssocFn | DefKind::Fn => "function argument",
55        DefKind::Closure => "closure argument",
56        // other types of MIR don't have function parameters, and we don't need to
57        // categorize those for the irrefutable check.
58        _ if thir.params.is_empty() => "",
59        kind => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected function parameters in THIR: {0:?} {1:?}",
        kind, def_id))bug!("unexpected function parameters in THIR: {kind:?} {def_id:?}"),
60    };
61
62    for param in thir.params.iter() {
63        if let Some(box ref pattern) = param.pat {
64            visitor.check_binding_is_irrefutable(pattern, origin, None, None);
65        }
66    }
67    visitor.error
68}
69
70#[derive(#[automatically_derived]
impl ::core::fmt::Debug for RefutableFlag {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                RefutableFlag::Irrefutable => "Irrefutable",
                RefutableFlag::Refutable => "Refutable",
            })
    }
}Debug, #[automatically_derived]
impl ::core::marker::Copy for RefutableFlag { }Copy, #[automatically_derived]
impl ::core::clone::Clone for RefutableFlag {
    #[inline]
    fn clone(&self) -> RefutableFlag { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for RefutableFlag {
    #[inline]
    fn eq(&self, other: &RefutableFlag) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
71enum RefutableFlag {
72    Irrefutable,
73    Refutable,
74}
75use RefutableFlag::*;
76
77#[derive(#[automatically_derived]
impl ::core::clone::Clone for LetSource {
    #[inline]
    fn clone(&self) -> LetSource { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for LetSource { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for LetSource {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                LetSource::None => "None",
                LetSource::PlainLet => "PlainLet",
                LetSource::IfLet => "IfLet",
                LetSource::IfLetGuard => "IfLetGuard",
                LetSource::LetElse => "LetElse",
                LetSource::WhileLet => "WhileLet",
                LetSource::Else => "Else",
                LetSource::ElseIfLet => "ElseIfLet",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for LetSource {
    #[inline]
    fn eq(&self, other: &LetSource) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for LetSource {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
78enum LetSource {
79    None,
80    PlainLet,
81    IfLet,
82    IfLetGuard,
83    LetElse,
84    WhileLet,
85    Else,
86    ElseIfLet,
87}
88
89struct MatchVisitor<'p, 'tcx> {
90    tcx: TyCtxt<'tcx>,
91    typing_env: ty::TypingEnv<'tcx>,
92    typeck_results: &'tcx ty::TypeckResults<'tcx>,
93    thir: &'p Thir<'tcx>,
94    hir_source: HirId,
95    let_source: LetSource,
96    pattern_arena: &'p TypedArena<DeconstructedPat<'p, 'tcx>>,
97    dropless_arena: &'p DroplessArena,
98    /// Tracks if we encountered an error while checking this body. That the first function to
99    /// report it stores it here. Some functions return `Result` to allow callers to short-circuit
100    /// on error, but callers don't need to store it here again.
101    error: Result<(), ErrorGuaranteed>,
102}
103
104// Visitor for a thir body. This calls `check_match` and `check_let` as appropriate.
105impl<'p, 'tcx> Visitor<'p, 'tcx> for MatchVisitor<'p, 'tcx> {
106    fn thir(&self) -> &'p Thir<'tcx> {
107        self.thir
108    }
109
110    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("visit_arm",
                                    "rustc_mir_build::thir::pattern::check_match",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/pattern/check_match.rs"),
                                    ::tracing_core::__macro_support::Option::Some(110u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::check_match"),
                                    ::tracing_core::field::FieldSet::new(&["arm"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&arm)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.with_hir_source(arm.hir_id,
                |this|
                    {
                        if let Some(expr) = arm.guard {
                            this.with_let_source(LetSource::IfLetGuard,
                                |this| { this.visit_expr(&this.thir[expr]) });
                        }
                        this.visit_pat(&arm.pattern);
                        this.visit_expr(&self.thir[arm.body]);
                    });
        }
    }
}#[instrument(level = "trace", skip(self))]
111    fn visit_arm(&mut self, arm: &'p Arm<'tcx>) {
112        self.with_hir_source(arm.hir_id, |this| {
113            if let Some(expr) = arm.guard {
114                this.with_let_source(LetSource::IfLetGuard, |this| {
115                    this.visit_expr(&this.thir[expr])
116                });
117            }
118            this.visit_pat(&arm.pattern);
119            this.visit_expr(&self.thir[arm.body]);
120        });
121    }
122
123    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("visit_expr",
                                    "rustc_mir_build::thir::pattern::check_match",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/pattern/check_match.rs"),
                                    ::tracing_core::__macro_support::Option::Some(123u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::check_match"),
                                    ::tracing_core::field::FieldSet::new(&["ex"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ex)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match ex.kind {
                ExprKind::Scope { value, hir_id, .. } => {
                    self.with_hir_source(hir_id,
                        |this| { this.visit_expr(&this.thir[value]); });
                    return;
                }
                ExprKind::If { cond, then, else_opt, if_then_scope: _ } => {
                    let let_source =
                        match ex.span.desugaring_kind() {
                            Some(DesugaringKind::WhileLoop) => LetSource::WhileLet,
                            _ =>
                                match self.let_source {
                                    LetSource::Else => LetSource::ElseIfLet,
                                    _ => LetSource::IfLet,
                                },
                        };
                    self.with_let_source(let_source,
                        |this| this.visit_expr(&self.thir[cond]));
                    self.with_let_source(LetSource::None,
                        |this| { this.visit_expr(&this.thir[then]); });
                    if let Some(else_) = else_opt {
                        self.with_let_source(LetSource::Else,
                            |this| { this.visit_expr(&this.thir[else_]) });
                    }
                    return;
                }
                ExprKind::Match { scrutinee, box ref arms, match_source } => {
                    self.check_match(scrutinee, arms, match_source, ex.span);
                }
                ExprKind::LoopMatch {
                    match_data: box LoopMatchMatchData {
                        scrutinee, box ref arms, span
                        }, .. } => {
                    self.check_match(scrutinee, arms, MatchSource::Normal,
                        span);
                }
                ExprKind::Let { box ref pat, expr } => {
                    self.check_let(pat, Some(expr), ex.span, None);
                }
                ExprKind::LogicalOp { op: LogicalOp::And, .. } if
                    !#[allow(non_exhaustive_omitted_patterns)] match self.let_source
                            {
                            LetSource::None => true,
                            _ => false,
                        } => {
                    let mut chain_refutabilities = Vec::new();
                    let Ok(()) =
                        self.visit_land(ex,
                            &mut chain_refutabilities) else { return };
                    if let [Some((_, Irrefutable))] = chain_refutabilities[..] {
                        self.lint_single_let(ex.span, None, None);
                    }
                    return;
                }
                _ => {}
            };
            self.with_let_source(LetSource::None,
                |this| visit::walk_expr(this, ex));
        }
    }
}#[instrument(level = "trace", skip(self))]
124    fn visit_expr(&mut self, ex: &'p Expr<'tcx>) {
125        match ex.kind {
126            ExprKind::Scope { value, hir_id, .. } => {
127                self.with_hir_source(hir_id, |this| {
128                    this.visit_expr(&this.thir[value]);
129                });
130                return;
131            }
132            ExprKind::If { cond, then, else_opt, if_then_scope: _ } => {
133                // Give a specific `let_source` for the condition.
134                let let_source = match ex.span.desugaring_kind() {
135                    Some(DesugaringKind::WhileLoop) => LetSource::WhileLet,
136                    _ => match self.let_source {
137                        LetSource::Else => LetSource::ElseIfLet,
138                        _ => LetSource::IfLet,
139                    },
140                };
141                self.with_let_source(let_source, |this| this.visit_expr(&self.thir[cond]));
142                self.with_let_source(LetSource::None, |this| {
143                    this.visit_expr(&this.thir[then]);
144                });
145                if let Some(else_) = else_opt {
146                    self.with_let_source(LetSource::Else, |this| {
147                        this.visit_expr(&this.thir[else_])
148                    });
149                }
150                return;
151            }
152            ExprKind::Match { scrutinee, box ref arms, match_source } => {
153                self.check_match(scrutinee, arms, match_source, ex.span);
154            }
155            ExprKind::LoopMatch {
156                match_data: box LoopMatchMatchData { scrutinee, box ref arms, span },
157                ..
158            } => {
159                self.check_match(scrutinee, arms, MatchSource::Normal, span);
160            }
161            ExprKind::Let { box ref pat, expr } => {
162                self.check_let(pat, Some(expr), ex.span, None);
163            }
164            ExprKind::LogicalOp { op: LogicalOp::And, .. }
165                if !matches!(self.let_source, LetSource::None) =>
166            {
167                let mut chain_refutabilities = Vec::new();
168                let Ok(()) = self.visit_land(ex, &mut chain_refutabilities) else { return };
169                // Lint only single irrefutable let binding.
170                if let [Some((_, Irrefutable))] = chain_refutabilities[..] {
171                    self.lint_single_let(ex.span, None, None);
172                }
173                return;
174            }
175            _ => {}
176        };
177        self.with_let_source(LetSource::None, |this| visit::walk_expr(this, ex));
178    }
179
180    fn visit_stmt(&mut self, stmt: &'p Stmt<'tcx>) {
181        match stmt.kind {
182            StmtKind::Let { box ref pattern, initializer, else_block, hir_id, span, .. } => {
183                self.with_hir_source(hir_id, |this| {
184                    let let_source =
185                        if else_block.is_some() { LetSource::LetElse } else { LetSource::PlainLet };
186                    let else_span = else_block.map(|bid| this.thir.blocks[bid].span);
187                    this.with_let_source(let_source, |this| {
188                        this.check_let(pattern, initializer, span, else_span)
189                    });
190                    visit::walk_stmt(this, stmt);
191                });
192            }
193            StmtKind::Expr { .. } => {
194                visit::walk_stmt(self, stmt);
195            }
196        }
197    }
198}
199
200impl<'p, 'tcx> MatchVisitor<'p, 'tcx> {
201    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("with_let_source",
                                    "rustc_mir_build::thir::pattern::check_match",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/pattern/check_match.rs"),
                                    ::tracing_core::__macro_support::Option::Some(201u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::check_match"),
                                    ::tracing_core::field::FieldSet::new(&["let_source"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&let_source)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let old_let_source = self.let_source;
            self.let_source = let_source;
            ensure_sufficient_stack(|| f(self));
            self.let_source = old_let_source;
        }
    }
}#[instrument(level = "trace", skip(self, f))]
202    fn with_let_source(&mut self, let_source: LetSource, f: impl FnOnce(&mut Self)) {
203        let old_let_source = self.let_source;
204        self.let_source = let_source;
205        ensure_sufficient_stack(|| f(self));
206        self.let_source = old_let_source;
207    }
208
209    fn with_hir_source<T>(&mut self, new_hir_source: HirId, f: impl FnOnce(&mut Self) -> T) -> T {
210        let old_hir_source = self.hir_source;
211        self.hir_source = new_hir_source;
212        let ret = f(self);
213        self.hir_source = old_hir_source;
214        ret
215    }
216
217    /// Visit a nested chain of `&&`. Used for if-let chains. This must call `visit_expr` on the
218    /// subexpressions we are not handling ourselves.
219    fn visit_land(
220        &mut self,
221        ex: &'p Expr<'tcx>,
222        accumulator: &mut Vec<Option<(Span, RefutableFlag)>>,
223    ) -> Result<(), ErrorGuaranteed> {
224        match ex.kind {
225            ExprKind::Scope { value, hir_id, .. } => {
226                self.with_hir_source(hir_id, |this| this.visit_land(&this.thir[value], accumulator))
227            }
228            ExprKind::LogicalOp { op: LogicalOp::And, lhs, rhs } => {
229                // We recurse into the lhs only, because `&&` chains associate to the left.
230                let res_lhs = self.visit_land(&self.thir[lhs], accumulator);
231                let res_rhs = self.visit_land_rhs(&self.thir[rhs])?;
232                accumulator.push(res_rhs);
233                res_lhs
234            }
235            _ => {
236                let res = self.visit_land_rhs(ex)?;
237                accumulator.push(res);
238                Ok(())
239            }
240        }
241    }
242
243    /// Visit the right-hand-side of a `&&`. Used for if-let chains. Returns `Some` if the
244    /// expression was ultimately a `let ... = ...`, and `None` if it was a normal boolean
245    /// expression. This must call `visit_expr` on the subexpressions we are not handling ourselves.
246    fn visit_land_rhs(
247        &mut self,
248        ex: &'p Expr<'tcx>,
249    ) -> Result<Option<(Span, RefutableFlag)>, ErrorGuaranteed> {
250        match ex.kind {
251            ExprKind::Scope { value, hir_id, .. } => {
252                self.with_hir_source(hir_id, |this| this.visit_land_rhs(&this.thir[value]))
253            }
254            ExprKind::Let { box ref pat, expr } => {
255                let expr = &self.thir()[expr];
256                self.with_let_source(LetSource::None, |this| {
257                    this.visit_expr(expr);
258                });
259                Ok(Some((ex.span, self.is_let_irrefutable(pat, Some(expr))?)))
260            }
261            _ => {
262                self.with_let_source(LetSource::None, |this| {
263                    this.visit_expr(ex);
264                });
265                Ok(None)
266            }
267        }
268    }
269
270    fn lower_pattern(
271        &mut self,
272        cx: &PatCtxt<'p, 'tcx>,
273        pat: &'p Pat<'tcx>,
274    ) -> Result<&'p DeconstructedPat<'p, 'tcx>, ErrorGuaranteed> {
275        if let Err(err) = pat.pat_error_reported() {
276            self.error = Err(err);
277            Err(err)
278        } else {
279            // Check the pattern for some things unrelated to exhaustiveness.
280            let refutable = if cx.refutable { Refutable } else { Irrefutable };
281            let mut err = Ok(());
282            pat.walk_always(|pat| {
283                check_borrow_conflicts_in_at_patterns(self, pat);
284                check_for_bindings_named_same_as_variants(self, pat, refutable);
285                err = err.and(check_never_pattern(cx, pat));
286            });
287            err?;
288            Ok(self.pattern_arena.alloc(cx.lower_pat(pat)))
289        }
290    }
291
292    /// Inspects the match scrutinee expression to determine whether the place it evaluates to may
293    /// hold invalid data.
294    fn is_known_valid_scrutinee(&self, scrutinee: &Expr<'tcx>) -> bool {
295        use ExprKind::*;
296        match &scrutinee.kind {
297            // Pointers can validly point to a place with invalid data. It is undecided whether
298            // references can too, so we conservatively assume they can.
299            Deref { .. } => false,
300            // Inherit validity of the parent place, unless the parent is an union.
301            Field { lhs, .. } => {
302                let lhs = &self.thir()[*lhs];
303                match lhs.ty.kind() {
304                    ty::Adt(def, _) if def.is_union() => false,
305                    _ => self.is_known_valid_scrutinee(lhs),
306                }
307            }
308            // Essentially a field access.
309            Index { lhs, .. } => {
310                let lhs = &self.thir()[*lhs];
311                self.is_known_valid_scrutinee(lhs)
312            }
313
314            // No-op.
315            Scope { value, .. } => self.is_known_valid_scrutinee(&self.thir()[*value]),
316
317            // Casts don't cause a load.
318            NeverToAny { source }
319            | Cast { source }
320            | Use { source }
321            | PointerCoercion { source, .. }
322            | PlaceTypeAscription { source, .. }
323            | ValueTypeAscription { source, .. }
324            | PlaceUnwrapUnsafeBinder { source }
325            | ValueUnwrapUnsafeBinder { source }
326            | WrapUnsafeBinder { source } => self.is_known_valid_scrutinee(&self.thir()[*source]),
327
328            // These diverge.
329            Become { .. }
330            | Break { .. }
331            | Continue { .. }
332            | ConstContinue { .. }
333            | Return { .. } => true,
334
335            // These are statements that evaluate to `()`.
336            Assign { .. } | AssignOp { .. } | InlineAsm { .. } | Let { .. } => true,
337
338            // These evaluate to a value.
339            RawBorrow { .. }
340            | Adt { .. }
341            | Array { .. }
342            | Binary { .. }
343            | Block { .. }
344            | Borrow { .. }
345            | Call { .. }
346            | ByUse { .. }
347            | Closure { .. }
348            | ConstBlock { .. }
349            | ConstParam { .. }
350            | If { .. }
351            | Literal { .. }
352            | LogicalOp { .. }
353            | Loop { .. }
354            | LoopMatch { .. }
355            | Match { .. }
356            | NamedConst { .. }
357            | NonHirLiteral { .. }
358            | Repeat { .. }
359            | StaticRef { .. }
360            | ThreadLocalRef { .. }
361            | Tuple { .. }
362            | Unary { .. }
363            | UpvarRef { .. }
364            | VarRef { .. }
365            | ZstLiteral { .. }
366            | Yield { .. } => true,
367        }
368    }
369
370    fn new_cx(
371        &self,
372        refutability: RefutableFlag,
373        whole_match_span: Option<Span>,
374        scrutinee: Option<&Expr<'tcx>>,
375        scrut_span: Span,
376    ) -> PatCtxt<'p, 'tcx> {
377        let refutable = match refutability {
378            Irrefutable => false,
379            Refutable => true,
380        };
381        // If we don't have a scrutinee we're either a function parameter or a `let x;`. Both cases
382        // require validity.
383        let known_valid_scrutinee =
384            scrutinee.map(|scrut| self.is_known_valid_scrutinee(scrut)).unwrap_or(true);
385        PatCtxt {
386            tcx: self.tcx,
387            typeck_results: self.typeck_results,
388            typing_env: self.typing_env,
389            module: self.tcx.parent_module(self.hir_source).to_def_id(),
390            dropless_arena: self.dropless_arena,
391            match_lint_level: self.hir_source,
392            whole_match_span,
393            scrut_span,
394            refutable,
395            known_valid_scrutinee,
396            internal_state: Default::default(),
397        }
398    }
399
400    fn analyze_patterns(
401        &mut self,
402        cx: &PatCtxt<'p, 'tcx>,
403        arms: &[MatchArm<'p, 'tcx>],
404        scrut_ty: Ty<'tcx>,
405    ) -> Result<UsefulnessReport<'p, 'tcx>, ErrorGuaranteed> {
406        let report =
407            rustc_pattern_analysis::rustc::analyze_match(&cx, &arms, scrut_ty).map_err(|err| {
408                self.error = Err(err);
409                err
410            })?;
411
412        // Warn unreachable subpatterns.
413        for (arm, is_useful) in report.arm_usefulness.iter() {
414            if let Usefulness::Useful(redundant_subpats) = is_useful
415                && !redundant_subpats.is_empty()
416            {
417                let mut redundant_subpats = redundant_subpats.clone();
418                // Emit lints in the order in which they occur in the file.
419                redundant_subpats.sort_unstable_by_key(|(pat, _)| pat.data().span);
420                for (pat, explanation) in redundant_subpats {
421                    report_unreachable_pattern(cx, arm.arm_data, pat, &explanation, None)
422                }
423            }
424        }
425        Ok(report)
426    }
427
428    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_let",
                                    "rustc_mir_build::thir::pattern::check_match",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/pattern/check_match.rs"),
                                    ::tracing_core::__macro_support::Option::Some(428u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::check_match"),
                                    ::tracing_core::field::FieldSet::new(&["pat", "scrutinee",
                                                    "span", "else_span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pat)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scrutinee)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&else_span)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !(self.let_source != LetSource::None) {
                ::core::panicking::panic("assertion failed: self.let_source != LetSource::None")
            };
            let scrut = scrutinee.map(|id| &self.thir[id]);
            if let LetSource::PlainLet = self.let_source {
                self.check_binding_is_irrefutable(pat, "local binding", scrut,
                    Some(span));
            } else if let Ok(Irrefutable) =
                    self.is_let_irrefutable(pat, scrut) {
                if span.from_expansion() {
                    self.lint_single_let(span, None, None);
                    return;
                }
                let let_else_span =
                    self.check_irrefutable_option_some(pat, scrut, span);
                let sm = self.tcx.sess.source_map();
                let next_token_start =
                    sm.span_extend_while_whitespace(span.clone()).hi();
                let line_span =
                    sm.span_extend_to_line(span.clone()).with_lo(next_token_start);
                let else_keyword_span = sm.span_until_whitespace(line_span);
                self.lint_single_let(span, Some(else_keyword_span),
                    let_else_span);
            }
        }
    }
}#[instrument(level = "trace", skip(self))]
429    fn check_let(
430        &mut self,
431        pat: &'p Pat<'tcx>,
432        scrutinee: Option<ExprId>,
433        span: Span,
434        else_span: Option<Span>,
435    ) {
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 if let Ok(Irrefutable) = self.is_let_irrefutable(pat, scrut) {
441            if span.from_expansion() {
442                self.lint_single_let(span, None, None);
443                return;
444            }
445            let let_else_span = self.check_irrefutable_option_some(pat, scrut, span);
446
447            let sm = self.tcx.sess.source_map();
448            let next_token_start = sm.span_extend_while_whitespace(span.clone()).hi();
449            let line_span = sm.span_extend_to_line(span.clone()).with_lo(next_token_start);
450            let else_keyword_span = sm.span_until_whitespace(line_span);
451            self.lint_single_let(span, Some(else_keyword_span), let_else_span);
452        }
453    }
454
455    /// Check case `let x = Some(y);`, user likely intended to destructure `Option`
456    fn check_irrefutable_option_some(
457        &self,
458        pat: &'p Pat<'tcx>,
459        initializer: Option<&Expr<'tcx>>,
460        span: Span,
461    ) -> Option<LetElseReplacementSuggestion> {
462        if let sm = self.tcx.sess.source_map()
463            && let Some(initializer) = initializer
464            && let Some(s_ty) = initializer.ty.ty_adt_def()
465            && self.tcx.is_diagnostic_item(rustc_span::sym::Option, s_ty.did())
466            && let ExprKind::Scope { value, .. } = initializer.kind
467            && let initializer_expr = &self.thir[value]
468            && let ExprKind::Adt(box AdtExpr { fields, .. }) = &initializer_expr.kind
469            && let Some(field) = fields.first()
470            && let inner = &self.thir[field.expr]
471            && let Some(inner_ty) = inner.ty.ty_adt_def()
472            && self.tcx.is_diagnostic_item(rustc_span::sym::Option, inner_ty.did())
473            && let Ok(rhs) = sm.span_to_snippet(inner.span)
474            && let Ok(lhs) = sm.span_to_snippet(pat.span)
475        {
476            let lhs = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Some({0})", lhs))
    })format!("Some({})", lhs);
477            Some(LetElseReplacementSuggestion { span, lhs, rhs })
478        } else {
479            None
480        }
481    }
482
483    fn check_match(
484        &mut self,
485        scrut: ExprId,
486        arms: &[ArmId],
487        source: hir::MatchSource,
488        expr_span: Span,
489    ) {
490        let scrut = &self.thir[scrut];
491        let cx = self.new_cx(Refutable, Some(expr_span), Some(scrut), scrut.span);
492
493        let mut tarms = Vec::with_capacity(arms.len());
494        for &arm in arms {
495            let arm = &self.thir.arms[arm];
496            let got_error = self.with_hir_source(arm.hir_id, |this| {
497                let Ok(pat) = this.lower_pattern(&cx, &arm.pattern) else { return true };
498                let arm =
499                    MatchArm { pat, arm_data: this.hir_source, has_guard: arm.guard.is_some() };
500                tarms.push(arm);
501                false
502            });
503            if got_error {
504                return;
505            }
506        }
507
508        let Ok(report) = self.analyze_patterns(&cx, &tarms, scrut.ty) else { return };
509
510        match source {
511            // Don't report arm reachability of desugared `match $iter.into_iter() { iter => .. }`
512            // when the iterator is an uninhabited type. unreachable_code will trigger instead.
513            hir::MatchSource::ForLoopDesugar if arms.len() == 1 => {}
514            hir::MatchSource::ForLoopDesugar
515            | hir::MatchSource::Postfix
516            | hir::MatchSource::Normal
517            | hir::MatchSource::FormatArgs => {
518                let is_match_arm =
519                    #[allow(non_exhaustive_omitted_patterns)] match source {
    hir::MatchSource::Postfix | hir::MatchSource::Normal => true,
    _ => false,
}matches!(source, hir::MatchSource::Postfix | hir::MatchSource::Normal);
520                report_arm_reachability(&cx, &report, is_match_arm);
521            }
522            // Unreachable patterns in try and await expressions occur when one of
523            // the arms are an uninhabited type. Which is OK.
524            hir::MatchSource::AwaitDesugar | hir::MatchSource::TryDesugar(_) => {}
525        }
526
527        // Check if the match is exhaustive.
528        let witnesses = report.non_exhaustiveness_witnesses;
529        if !witnesses.is_empty() {
530            if source == hir::MatchSource::ForLoopDesugar
531                && let [_, snd_arm] = *arms
532            {
533                // the for loop pattern is not irrefutable
534                let pat = &self.thir[snd_arm].pattern;
535                // `pat` should be `Some(<pat_field>)` from a desugared for loop.
536                if true {
    match (&pat.span.desugaring_kind(), &Some(DesugaringKind::ForLoop)) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_eq!(pat.span.desugaring_kind(), Some(DesugaringKind::ForLoop));
537                let PatKind::Variant { ref subpatterns, .. } = pat.kind else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
538                let [pat_field] = &subpatterns[..] else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
539                self.check_binding_is_irrefutable(
540                    &pat_field.pattern,
541                    "`for` loop binding",
542                    None,
543                    None,
544                );
545            } else {
546                // span after scrutinee, or after `.match`. That is, the braces, arms,
547                // and any whitespace preceding the braces.
548                let braces_span = match source {
549                    hir::MatchSource::Normal => scrut
550                        .span
551                        .find_ancestor_in_same_ctxt(expr_span)
552                        .map(|scrut_span| scrut_span.shrink_to_hi().with_hi(expr_span.hi())),
553                    hir::MatchSource::Postfix => {
554                        // This is horrendous, and we should deal with it by just
555                        // stashing the span of the braces somewhere (like in the match source).
556                        scrut.span.find_ancestor_in_same_ctxt(expr_span).and_then(|scrut_span| {
557                            let sm = self.tcx.sess.source_map();
558                            let brace_span = sm.span_extend_to_next_char(scrut_span, '{', true);
559                            if sm.span_to_snippet(sm.next_point(brace_span)).as_deref() == Ok("{") {
560                                let sp = brace_span.shrink_to_hi().with_hi(expr_span.hi());
561                                // We also need to extend backwards for whitespace
562                                sm.span_extend_prev_while(sp, |c| c.is_whitespace()).ok()
563                            } else {
564                                None
565                            }
566                        })
567                    }
568                    hir::MatchSource::ForLoopDesugar
569                    | hir::MatchSource::TryDesugar(_)
570                    | hir::MatchSource::AwaitDesugar
571                    | hir::MatchSource::FormatArgs => None,
572                };
573
574                // Check if the match would be exhaustive if all guards were removed.
575                // If so, we leave a note that guards don't count towards exhaustivity.
576                let would_be_exhaustive_without_guards = {
577                    let any_arm_has_guard = tarms.iter().any(|arm| arm.has_guard);
578                    any_arm_has_guard && {
579                        let guardless_arms: Vec<_> =
580                            tarms.iter().map(|arm| MatchArm { has_guard: false, ..*arm }).collect();
581                        rustc_pattern_analysis::rustc::analyze_match(&cx, &guardless_arms, scrut.ty)
582                            .is_ok_and(|report| report.non_exhaustiveness_witnesses.is_empty())
583                    }
584                };
585                self.error = Err(report_non_exhaustive_match(
586                    &cx,
587                    self.thir,
588                    scrut.ty,
589                    scrut.span,
590                    witnesses,
591                    arms,
592                    braces_span,
593                    would_be_exhaustive_without_guards,
594                ));
595            }
596        }
597    }
598
599    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("lint_single_let",
                                    "rustc_mir_build::thir::pattern::check_match",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/pattern/check_match.rs"),
                                    ::tracing_core::__macro_support::Option::Some(599u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::check_match"),
                                    ::tracing_core::field::FieldSet::new(&["let_span",
                                                    "else_keyword_span", "let_else_span"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&let_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&else_keyword_span)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&let_else_span)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            report_irrefutable_let_patterns(self.tcx, self.hir_source,
                self.let_source, 1, let_span, else_keyword_span,
                let_else_span);
        }
    }
}#[instrument(level = "trace", skip(self))]
600    fn lint_single_let(
601        &mut self,
602        let_span: Span,
603        else_keyword_span: Option<Span>,
604        let_else_span: Option<LetElseReplacementSuggestion>,
605    ) {
606        report_irrefutable_let_patterns(
607            self.tcx,
608            self.hir_source,
609            self.let_source,
610            1,
611            let_span,
612            else_keyword_span,
613            let_else_span,
614        );
615    }
616
617    fn analyze_binding(
618        &mut self,
619        pat: &'p Pat<'tcx>,
620        refutability: RefutableFlag,
621        scrut: Option<&Expr<'tcx>>,
622    ) -> Result<(PatCtxt<'p, 'tcx>, UsefulnessReport<'p, 'tcx>), ErrorGuaranteed> {
623        let cx = self.new_cx(refutability, None, scrut, pat.span);
624        let pat = self.lower_pattern(&cx, pat)?;
625        let arms = [MatchArm { pat, arm_data: self.hir_source, has_guard: false }];
626        let report = self.analyze_patterns(&cx, &arms, pat.ty().inner())?;
627        Ok((cx, report))
628    }
629
630    fn is_let_irrefutable(
631        &mut self,
632        pat: &'p Pat<'tcx>,
633        scrut: Option<&Expr<'tcx>>,
634    ) -> Result<RefutableFlag, ErrorGuaranteed> {
635        let (cx, report) = self.analyze_binding(pat, Refutable, scrut)?;
636        // Report if the pattern is unreachable, which can only occur when the type is uninhabited.
637        report_arm_reachability(&cx, &report, false);
638        // If the list of witnesses is empty, the match is exhaustive, i.e. the `if let` pattern is
639        // irrefutable.
640        Ok(if report.non_exhaustiveness_witnesses.is_empty() { Irrefutable } else { Refutable })
641    }
642
643    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_binding_is_irrefutable",
                                    "rustc_mir_build::thir::pattern::check_match",
                                    ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/pattern/check_match.rs"),
                                    ::tracing_core::__macro_support::Option::Some(643u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::check_match"),
                                    ::tracing_core::field::FieldSet::new(&["pat", "origin",
                                                    "scrut", "sp"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pat)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&origin as
                                                            &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scrut)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sp)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let pattern_ty = pat.ty;
            let Ok((cx, report)) =
                self.analyze_binding(pat, Irrefutable, scrut) else { return };
            let witnesses = report.non_exhaustiveness_witnesses;
            if witnesses.is_empty() { return; }
            let inform = sp.is_some().then_some(Inform);
            let mut let_suggestion = None;
            let mut misc_suggestion = None;
            let mut interpreted_as_const = None;
            let mut interpreted_as_const_sugg = None;
            if let Some(def_id) =
                    is_const_pat_that_looks_like_binding(self.tcx, pat) {
                let span = self.tcx.def_span(def_id);
                let variable = self.tcx.item_name(def_id).to_string();
                interpreted_as_const =
                    Some(InterpretedAsConst {
                            span,
                            variable: variable.clone(),
                        });
                interpreted_as_const_sugg =
                    Some(InterpretedAsConstSugg { span: pat.span, variable });
            } else if let PatKind::Constant { .. } = pat.kind &&
                    let Ok(snippet) =
                        self.tcx.sess.source_map().span_to_snippet(pat.span) {
                if snippet.chars().all(|c| c.is_digit(10)) {
                    misc_suggestion =
                        Some(MiscPatternSuggestion::AttemptedIntegerLiteral {
                                start_span: pat.span.shrink_to_lo(),
                            });
                }
            }
            if let Some(span) = sp &&
                            self.tcx.sess.source_map().is_span_accessible(span) &&
                        interpreted_as_const.is_none() && scrut.is_some() {
                let mut bindings = ::alloc::vec::Vec::new();
                pat.each_binding(|name, _, _, _| bindings.push(name));
                let semi_span = span.shrink_to_hi();
                let start_span = span.shrink_to_lo();
                let end_span = semi_span.shrink_to_lo();
                let count = witnesses.len();
                let_suggestion =
                    Some(if bindings.is_empty() {
                            SuggestLet::If { start_span, semi_span, count }
                        } else { SuggestLet::Else { end_span, count } });
            };
            let adt_defined_here =
                report_adt_defined_here(self.tcx, pattern_ty, &witnesses,
                    false);
            let witness_1_is_privately_uninhabited =
                if let Some(witness_1) = witnesses.get(0) &&
                                let ty::Adt(adt, args) = witness_1.ty().kind() &&
                            adt.is_enum() &&
                        let Constructor::Variant(variant_index) = witness_1.ctor() {
                    let variant_inhabited =
                        adt.variant(*variant_index).inhabited_predicate(self.tcx,
                                *adt).instantiate(self.tcx, args);
                    variant_inhabited.apply(self.tcx, cx.typing_env, cx.module)
                        &&
                        !variant_inhabited.apply_ignore_module(self.tcx,
                                cx.typing_env)
                } else { false };
            let witness_1 = cx.print_witness_pat(witnesses.get(0).unwrap());
            self.error =
                Err(self.tcx.dcx().emit_err(PatternNotCovered {
                            span: pat.span,
                            origin,
                            uncovered: Uncovered::new(pat.span, &cx, witnesses),
                            inform,
                            interpreted_as_const,
                            interpreted_as_const_sugg,
                            witness_1_is_privately_uninhabited,
                            witness_1,
                            _p: (),
                            pattern_ty,
                            let_suggestion,
                            misc_suggestion,
                            adt_defined_here,
                        }));
        }
    }
}#[instrument(level = "trace", skip(self))]
644    fn check_binding_is_irrefutable(
645        &mut self,
646        pat: &'p Pat<'tcx>,
647        origin: &str,
648        scrut: Option<&Expr<'tcx>>,
649        sp: Option<Span>,
650    ) {
651        let pattern_ty = pat.ty;
652
653        let Ok((cx, report)) = self.analyze_binding(pat, Irrefutable, scrut) else { return };
654        let witnesses = report.non_exhaustiveness_witnesses;
655        if witnesses.is_empty() {
656            // The pattern is irrefutable.
657            return;
658        }
659
660        let inform = sp.is_some().then_some(Inform);
661        let mut let_suggestion = None;
662        let mut misc_suggestion = None;
663        let mut interpreted_as_const = None;
664        let mut interpreted_as_const_sugg = None;
665
666        if let Some(def_id) = is_const_pat_that_looks_like_binding(self.tcx, pat) {
667            let span = self.tcx.def_span(def_id);
668            let variable = self.tcx.item_name(def_id).to_string();
669            // When we encounter a constant as the binding name, point at the `const` definition.
670            interpreted_as_const = Some(InterpretedAsConst { span, variable: variable.clone() });
671            interpreted_as_const_sugg = Some(InterpretedAsConstSugg { span: pat.span, variable });
672        } else if let PatKind::Constant { .. } = pat.kind
673            && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(pat.span)
674        {
675            // If the pattern to match is an integer literal:
676            if snippet.chars().all(|c| c.is_digit(10)) {
677                // Then give a suggestion, the user might've meant to create a binding instead.
678                misc_suggestion = Some(MiscPatternSuggestion::AttemptedIntegerLiteral {
679                    start_span: pat.span.shrink_to_lo(),
680                });
681            }
682        }
683
684        if let Some(span) = sp
685            && self.tcx.sess.source_map().is_span_accessible(span)
686            && interpreted_as_const.is_none()
687            && scrut.is_some()
688        {
689            let mut bindings = vec![];
690            pat.each_binding(|name, _, _, _| bindings.push(name));
691
692            let semi_span = span.shrink_to_hi();
693            let start_span = span.shrink_to_lo();
694            let end_span = semi_span.shrink_to_lo();
695            let count = witnesses.len();
696
697            let_suggestion = Some(if bindings.is_empty() {
698                SuggestLet::If { start_span, semi_span, count }
699            } else {
700                SuggestLet::Else { end_span, count }
701            });
702        };
703
704        let adt_defined_here = report_adt_defined_here(self.tcx, pattern_ty, &witnesses, false);
705
706        // Emit an extra note if the first uncovered witness would be uninhabited
707        // if we disregard visibility.
708        let witness_1_is_privately_uninhabited = if let Some(witness_1) = witnesses.get(0)
709            && let ty::Adt(adt, args) = witness_1.ty().kind()
710            && adt.is_enum()
711            && let Constructor::Variant(variant_index) = witness_1.ctor()
712        {
713            let variant_inhabited = adt
714                .variant(*variant_index)
715                .inhabited_predicate(self.tcx, *adt)
716                .instantiate(self.tcx, args);
717            variant_inhabited.apply(self.tcx, cx.typing_env, cx.module)
718                && !variant_inhabited.apply_ignore_module(self.tcx, cx.typing_env)
719        } else {
720            false
721        };
722
723        let witness_1 = cx.print_witness_pat(witnesses.get(0).unwrap());
724
725        self.error = Err(self.tcx.dcx().emit_err(PatternNotCovered {
726            span: pat.span,
727            origin,
728            uncovered: Uncovered::new(pat.span, &cx, witnesses),
729            inform,
730            interpreted_as_const,
731            interpreted_as_const_sugg,
732            witness_1_is_privately_uninhabited,
733            witness_1,
734            _p: (),
735            pattern_ty,
736            let_suggestion,
737            misc_suggestion,
738            adt_defined_here,
739        }));
740    }
741}
742
743/// Check if a by-value binding is by-value. That is, check if the binding's type is not `Copy`.
744/// Check that there are no borrow or move conflicts in `binding @ subpat` patterns.
745///
746/// For example, this would reject:
747/// - `ref x @ Some(ref mut y)`,
748/// - `ref mut x @ Some(ref y)`,
749/// - `ref mut x @ Some(ref mut y)`,
750/// - `ref mut? x @ Some(y)`, and
751/// - `x @ Some(ref mut? y)`.
752///
753/// This analysis is *not* subsumed by NLL.
754fn check_borrow_conflicts_in_at_patterns<'tcx>(cx: &MatchVisitor<'_, 'tcx>, pat: &Pat<'tcx>) {
755    // Extract `sub` in `binding @ sub`.
756    let PatKind::Binding { name, mode, ty, subpattern: Some(box ref sub), .. } = pat.kind else {
757        return;
758    };
759
760    let is_binding_by_move = |ty: Ty<'tcx>| !cx.tcx.type_is_copy_modulo_regions(cx.typing_env, ty);
761
762    let sess = cx.tcx.sess;
763
764    // Get the binding move, extract the mutability if by-ref.
765    let mut_outer = match mode.0 {
766        ByRef::No if is_binding_by_move(ty) => {
767            // We have `x @ pat` where `x` is by-move. Reject all borrows in `pat`.
768            let mut conflicts_ref = Vec::new();
769            sub.each_binding(|_, mode, _, span| {
770                if #[allow(non_exhaustive_omitted_patterns)] match mode {
    ByRef::Yes(..) => true,
    _ => false,
}matches!(mode, ByRef::Yes(..)) {
771                    conflicts_ref.push(span)
772                }
773            });
774            if !conflicts_ref.is_empty() {
775                sess.dcx().emit_err(BorrowOfMovedValue {
776                    binding_span: pat.span,
777                    conflicts_ref,
778                    name: Ident::new(name, pat.span),
779                    ty,
780                    suggest_borrowing: Some(pat.span.shrink_to_lo()),
781                });
782            }
783            return;
784        }
785        ByRef::No => return,
786        ByRef::Yes(_, m) => m,
787    };
788
789    // We now have `ref $mut_outer binding @ sub` (semantically).
790    // Recurse into each binding in `sub` and find mutability or move conflicts.
791    let mut conflicts_move = Vec::new();
792    let mut conflicts_mut_mut = Vec::new();
793    let mut conflicts_mut_ref = Vec::new();
794    sub.each_binding(|name, mode, ty, span| {
795        match mode {
796            ByRef::Yes(_, mut_inner) => match (mut_outer, mut_inner) {
797                // Both sides are `ref`.
798                (Mutability::Not, Mutability::Not) => {}
799                // 2x `ref mut`.
800                (Mutability::Mut, Mutability::Mut) => {
801                    conflicts_mut_mut.push(Conflict::Mut { span, name })
802                }
803                (Mutability::Not, Mutability::Mut) => {
804                    conflicts_mut_ref.push(Conflict::Mut { span, name })
805                }
806                (Mutability::Mut, Mutability::Not) => {
807                    conflicts_mut_ref.push(Conflict::Ref { span, name })
808                }
809            },
810            ByRef::No if is_binding_by_move(ty) => {
811                conflicts_move.push(Conflict::Moved { span, name }) // `ref mut?` + by-move conflict.
812            }
813            ByRef::No => {} // `ref mut?` + by-copy is fine.
814        }
815    });
816
817    let report_mut_mut = !conflicts_mut_mut.is_empty();
818    let report_mut_ref = !conflicts_mut_ref.is_empty();
819    let report_move_conflict = !conflicts_move.is_empty();
820
821    let mut occurrences = match mut_outer {
822        Mutability::Mut => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Conflict::Mut { span: pat.span, name }]))vec![Conflict::Mut { span: pat.span, name }],
823        Mutability::Not => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [Conflict::Ref { span: pat.span, name }]))vec![Conflict::Ref { span: pat.span, name }],
824    };
825    occurrences.extend(conflicts_mut_mut);
826    occurrences.extend(conflicts_mut_ref);
827    occurrences.extend(conflicts_move);
828
829    // Report errors if any.
830    if report_mut_mut {
831        // Report mutability conflicts for e.g. `ref mut x @ Some(ref mut y)`.
832        sess.dcx().emit_err(MultipleMutBorrows { span: pat.span, occurrences });
833    } else if report_mut_ref {
834        // Report mutability conflicts for e.g. `ref x @ Some(ref mut y)` or the converse.
835        match mut_outer {
836            Mutability::Mut => {
837                sess.dcx().emit_err(AlreadyMutBorrowed { span: pat.span, occurrences });
838            }
839            Mutability::Not => {
840                sess.dcx().emit_err(AlreadyBorrowed { span: pat.span, occurrences });
841            }
842        };
843    } else if report_move_conflict {
844        // Report by-ref and by-move conflicts, e.g. `ref x @ y`.
845        sess.dcx().emit_err(MovedWhileBorrowed { span: pat.span, occurrences });
846    }
847}
848
849fn check_for_bindings_named_same_as_variants(
850    cx: &MatchVisitor<'_, '_>,
851    pat: &Pat<'_>,
852    rf: RefutableFlag,
853) {
854    if let PatKind::Binding {
855        name,
856        mode: BindingMode(ByRef::No, Mutability::Not),
857        subpattern: None,
858        ty,
859        ..
860    } = pat.kind
861        && let ty::Adt(edef, _) = ty.peel_refs().kind()
862        && edef.is_enum()
863        && edef
864            .variants()
865            .iter()
866            .any(|variant| variant.name == name && variant.ctor_kind() == Some(CtorKind::Const))
867    {
868        let variant_count = edef.variants().len();
869        let ty_path = { let _guard = NoTrimmedGuard::new(); cx.tcx.def_path_str(edef.did()) }with_no_trimmed_paths!(cx.tcx.def_path_str(edef.did()));
870        cx.tcx.emit_node_span_lint(
871            BINDINGS_WITH_VARIANT_NAME,
872            cx.hir_source,
873            pat.span,
874            BindingsWithVariantName {
875                // If this is an irrefutable pattern, and there's > 1 variant,
876                // then we can't actually match on this. Applying the below
877                // suggestion would produce code that breaks on `check_binding_is_irrefutable`.
878                suggestion: if rf == Refutable || variant_count == 1 {
879                    Some(pat.span)
880                } else {
881                    None
882                },
883                ty_path,
884                name: Ident::new(name, pat.span),
885            },
886        )
887    }
888}
889
890/// Check that never patterns are only used on inhabited types.
891fn check_never_pattern<'tcx>(
892    cx: &PatCtxt<'_, 'tcx>,
893    pat: &Pat<'tcx>,
894) -> Result<(), ErrorGuaranteed> {
895    if let PatKind::Never = pat.kind {
896        if !cx.is_uninhabited(pat.ty) {
897            return Err(cx.tcx.dcx().emit_err(NonEmptyNeverPattern { span: pat.span, ty: pat.ty }));
898        }
899    }
900    Ok(())
901}
902
903fn report_irrefutable_let_patterns(
904    tcx: TyCtxt<'_>,
905    id: HirId,
906    source: LetSource,
907    count: usize,
908    span: Span,
909    else_keyword_span: Option<Span>,
910    let_else_span: Option<LetElseReplacementSuggestion>,
911) {
912    macro_rules! emit_diag {
913        ($lint:tt) => {{
914            tcx.emit_node_span_lint(IRREFUTABLE_LET_PATTERNS, id, span, $lint { count });
915        }};
916    }
917
918    match source {
919        LetSource::None | LetSource::PlainLet | LetSource::Else => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
920        LetSource::IfLet | LetSource::ElseIfLet => {
    tcx.emit_node_span_lint(IRREFUTABLE_LET_PATTERNS, id, span,
        IrrefutableLetPatternsIfLet { count });
}emit_diag!(IrrefutableLetPatternsIfLet),
921        LetSource::IfLetGuard => {
    tcx.emit_node_span_lint(IRREFUTABLE_LET_PATTERNS, id, span,
        IrrefutableLetPatternsIfLetGuard { count });
}emit_diag!(IrrefutableLetPatternsIfLetGuard),
922        LetSource::LetElse => {
923            let spans = match else_keyword_span {
924                Some(else_keyword_span) => {
925                    let mut spans = MultiSpan::from_span(else_keyword_span);
926                    spans.push_span_label(
927                        span,
928                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("assigning to binding pattern will always succeed"))msg!("assigning to binding pattern will always succeed"),
929                    );
930                    spans
931                }
932                None => span.into(),
933            };
934
935            tcx.emit_node_span_lint(
936                IRREFUTABLE_LET_PATTERNS,
937                id,
938                spans,
939                IrrefutableLetPatternsLetElse { be_replaced: let_else_span },
940            );
941        }
942        LetSource::WhileLet => {
    tcx.emit_node_span_lint(IRREFUTABLE_LET_PATTERNS, id, span,
        IrrefutableLetPatternsWhileLet { count });
}emit_diag!(IrrefutableLetPatternsWhileLet),
943    }
944}
945
946/// Report unreachable arms, if any.
947fn report_unreachable_pattern<'p, 'tcx>(
948    cx: &PatCtxt<'p, 'tcx>,
949    hir_id: HirId,
950    pat: &DeconstructedPat<'p, 'tcx>,
951    explanation: &RedundancyExplanation<'p, 'tcx>,
952    whole_arm_span: Option<Span>,
953) {
954    static CAP_COVERED_BY_MANY: usize = 4;
955    let pat_span = pat.data().span;
956    let mut lint = UnreachablePattern {
957        span: Some(pat_span),
958        matches_no_values: None,
959        matches_no_values_ty: **pat.ty(),
960        uninhabited_note: None,
961        covered_by_catchall: None,
962        covered_by_one: None,
963        covered_by_many: None,
964        covered_by_many_n_more_count: 0,
965        wanted_constant: None,
966        accessible_constant: None,
967        inaccessible_constant: None,
968        pattern_let_binding: None,
969        suggest_remove: None,
970    };
971    match explanation.covered_by.as_slice() {
972        [] => {
973            // Empty pattern; we report the uninhabited type that caused the emptiness.
974            lint.span = None; // Don't label the pattern itself
975            lint.uninhabited_note = Some(()); // Give a link about empty types
976            lint.matches_no_values = Some(pat_span);
977            lint.suggest_remove = whole_arm_span; // Suggest to remove the match arm
978            pat.walk(&mut |subpat| {
979                let ty = **subpat.ty();
980                if cx.is_uninhabited(ty) {
981                    lint.matches_no_values_ty = ty;
982                    false // No need to dig further.
983                } else if #[allow(non_exhaustive_omitted_patterns)] match subpat.ctor() {
    Constructor::Ref | Constructor::UnionField => true,
    _ => false,
}matches!(subpat.ctor(), Constructor::Ref | Constructor::UnionField) {
984                    false // Don't explore further since they are not by-value.
985                } else {
986                    true
987                }
988            });
989        }
990        [covering_pat] if pat_is_catchall(covering_pat) => {
991            // A binding pattern that matches all, a single binding name.
992            let pat = covering_pat.data();
993            lint.covered_by_catchall = Some(pat.span);
994            find_fallback_pattern_typo(cx, hir_id, pat, &mut lint);
995        }
996        [covering_pat] => {
997            lint.covered_by_one = Some(covering_pat.data().span);
998        }
999        covering_pats => {
1000            let mut iter = covering_pats.iter();
1001            let mut multispan = MultiSpan::from_span(pat_span);
1002            for p in iter.by_ref().take(CAP_COVERED_BY_MANY) {
1003                multispan.push_span_label(p.data().span, rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("matches some of the same values"))msg!("matches some of the same values"));
1004            }
1005            let remain = iter.count();
1006            if remain == 0 {
1007                multispan.push_span_label(pat_span, rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("collectively making this unreachable"))msg!("collectively making this unreachable"));
1008            } else {
1009                lint.covered_by_many_n_more_count = remain;
1010                multispan.push_span_label(
1011                    pat_span,
1012                    rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("...and {$covered_by_many_n_more_count} other patterns collectively make this unreachable"))msg!("...and {$covered_by_many_n_more_count} other patterns collectively make this unreachable"),
1013                );
1014            }
1015            lint.covered_by_many = Some(multispan);
1016        }
1017    }
1018    cx.tcx.emit_node_span_lint(UNREACHABLE_PATTERNS, hir_id, pat_span, lint);
1019}
1020
1021/// Detect typos that were meant to be a `const` but were interpreted as a new pattern binding.
1022fn find_fallback_pattern_typo<'tcx>(
1023    cx: &PatCtxt<'_, 'tcx>,
1024    hir_id: HirId,
1025    pat: &Pat<'tcx>,
1026    lint: &mut UnreachablePattern<'_>,
1027) {
1028    if let Level::Allow = cx.tcx.lint_level_at_node(UNREACHABLE_PATTERNS, hir_id).level {
1029        // This is because we use `with_no_trimmed_paths` later, so if we never emit the lint we'd
1030        // ICE. At the same time, we don't really need to do all of this if we won't emit anything.
1031        return;
1032    }
1033    if let PatKind::Binding { name, subpattern: None, ty, .. } = pat.kind {
1034        // See if the binding might have been a `const` that was mistyped or out of scope.
1035        let mut accessible = ::alloc::vec::Vec::new()vec![];
1036        let mut accessible_path = ::alloc::vec::Vec::new()vec![];
1037        let mut inaccessible = ::alloc::vec::Vec::new()vec![];
1038        let mut imported = ::alloc::vec::Vec::new()vec![];
1039        let mut imported_spans = ::alloc::vec::Vec::new()vec![];
1040        let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(cx.typing_env);
1041        let parent = cx.tcx.hir_get_parent_item(hir_id);
1042
1043        for item in cx.tcx.hir_crate_items(()).free_items() {
1044            if let DefKind::Use = cx.tcx.def_kind(item.owner_id) {
1045                // Look for consts being re-exported.
1046                let item = cx.tcx.hir_expect_item(item.owner_id.def_id);
1047                let hir::ItemKind::Use(path, _) = item.kind else {
1048                    continue;
1049                };
1050                if let Some(value_ns) = path.res.value_ns
1051                    && let Res::Def(DefKind::Const { .. }, id) = value_ns
1052                    && infcx.can_eq(
1053                        param_env,
1054                        ty,
1055                        cx.tcx.type_of(id).instantiate_identity().skip_norm_wip(),
1056                    )
1057                {
1058                    if cx.tcx.visibility(id).is_accessible_from(parent, cx.tcx) {
1059                        // The original const is accessible, suggest using it directly.
1060                        let item_name = cx.tcx.item_name(id);
1061                        accessible.push(item_name);
1062                        accessible_path.push({ let _guard = NoTrimmedGuard::new(); cx.tcx.def_path_str(id) }with_no_trimmed_paths!(cx.tcx.def_path_str(id)));
1063                    } else if cx.tcx.visibility(item.owner_id).is_accessible_from(parent, cx.tcx) {
1064                        // The const is accessible only through the re-export, point at
1065                        // the `use`.
1066                        let ident = item.kind.ident().unwrap();
1067                        imported.push(ident.name);
1068                        imported_spans.push(ident.span);
1069                    }
1070                }
1071            }
1072            if let DefKind::Const { .. } = cx.tcx.def_kind(item.owner_id)
1073                && infcx.can_eq(
1074                    param_env,
1075                    ty,
1076                    cx.tcx.type_of(item.owner_id).instantiate_identity().skip_norm_wip(),
1077                )
1078            {
1079                // Look for local consts.
1080                let item_name = cx.tcx.item_name(item.owner_id);
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 = { let _guard = NoTrimmedGuard::new(); cx.tcx.def_path_str(item.owner_id) }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                                && let hir::PatKind::Binding(_, _, binding_name, _) =
1153                                    let_stmt.pat.kind
1154                                && name == binding_name.name
1155                            {
1156                                lint.pattern_let_binding = Some(binding_name.span);
1157                            }
1158                        }
1159                    }
1160                    hir::Node::Item(_) => break,
1161                    _ => {}
1162                }
1163            }
1164        }
1165    }
1166}
1167
1168/// Report unreachable arms, if any.
1169fn report_arm_reachability<'p, 'tcx>(
1170    cx: &PatCtxt<'p, 'tcx>,
1171    report: &UsefulnessReport<'p, 'tcx>,
1172    is_match_arm: bool,
1173) {
1174    let sm = cx.tcx.sess.source_map();
1175    for (arm, is_useful) in report.arm_usefulness.iter() {
1176        if let Usefulness::Redundant(explanation) = is_useful {
1177            let hir_id = arm.arm_data;
1178            let arm_span = cx.tcx.hir_span(hir_id);
1179            let whole_arm_span = if is_match_arm {
1180                // If the arm is followed by a comma, extend the span to include it.
1181                if let Some(comma) = sm.span_followed_by(arm_span, ",") {
1182                    Some(arm_span.to(comma))
1183                } else {
1184                    Some(arm_span)
1185                }
1186            } else {
1187                None
1188            };
1189            report_unreachable_pattern(cx, hir_id, arm.pat, explanation, whole_arm_span)
1190        }
1191    }
1192}
1193
1194/// Checks for common cases of "catchall" patterns that may not be intended as such.
1195fn pat_is_catchall(pat: &DeconstructedPat<'_, '_>) -> bool {
1196    match pat.ctor() {
1197        Constructor::Wildcard => true,
1198        Constructor::Struct | Constructor::Ref => {
1199            pat.iter_fields().all(|ipat| pat_is_catchall(&ipat.pat))
1200        }
1201        _ => false,
1202    }
1203}
1204
1205/// If the given pattern is a named constant that looks like it could have been
1206/// intended to be a binding, returns the `DefId` of the named constant.
1207///
1208/// Diagnostics use this to give more detailed suggestions for non-exhaustive
1209/// matches.
1210fn is_const_pat_that_looks_like_binding<'tcx>(tcx: TyCtxt<'tcx>, pat: &Pat<'tcx>) -> Option<DefId> {
1211    // The pattern must be a named constant, and the name that appears in
1212    // the pattern's source text must resemble a plain identifier without any
1213    // `::` namespace separators or other non-identifier characters.
1214    if let Some(def_id) = try { pat.extra.as_deref()?.expanded_const? }
1215        && #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(def_id) {
    DefKind::Const { .. } => true,
    _ => false,
}matches!(tcx.def_kind(def_id), DefKind::Const { .. })
1216        && let Ok(snippet) = tcx.sess.source_map().span_to_snippet(pat.span)
1217        && snippet.chars().all(|c| c.is_alphanumeric() || c == '_')
1218    {
1219        Some(def_id)
1220    } else {
1221        None
1222    }
1223}
1224
1225/// Report that a match is not exhaustive.
1226fn report_non_exhaustive_match<'p, 'tcx>(
1227    cx: &PatCtxt<'p, 'tcx>,
1228    thir: &Thir<'tcx>,
1229    scrut_ty: Ty<'tcx>,
1230    sp: Span,
1231    witnesses: Vec<WitnessPat<'p, 'tcx>>,
1232    arms: &[ArmId],
1233    braces_span: Option<Span>,
1234    would_be_exhaustive_without_guards: bool,
1235) -> ErrorGuaranteed {
1236    let is_empty_match = arms.is_empty();
1237    let non_empty_enum = match scrut_ty.kind() {
1238        ty::Adt(def, _) => def.is_enum() && !def.variants().is_empty(),
1239        _ => false,
1240    };
1241    // In the case of an empty match, replace the '`_` not covered' diagnostic with something more
1242    // informative.
1243    if is_empty_match && !non_empty_enum {
1244        return cx.tcx.dcx().emit_err(NonExhaustivePatternsTypeNotEmpty {
1245            cx,
1246            scrut_span: sp,
1247            braces_span,
1248            ty: scrut_ty,
1249        });
1250    }
1251
1252    // FIXME: migration of this diagnostic will require list support
1253    let joined_patterns = joined_uncovered_patterns(cx, &witnesses);
1254    let mut err = {
    cx.tcx.dcx().struct_span_err(sp,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("non-exhaustive patterns: {0} not covered",
                            joined_patterns))
                })).with_code(E0004)
}struct_span_code_err!(
1255        cx.tcx.dcx(),
1256        sp,
1257        E0004,
1258        "non-exhaustive patterns: {joined_patterns} not covered"
1259    );
1260    err.span_label(
1261        sp,
1262        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("pattern{0} {1} not covered",
                if witnesses.len() == 1 { "" } else { "s" }, joined_patterns))
    })format!(
1263            "pattern{} {} not covered",
1264            rustc_errors::pluralize!(witnesses.len()),
1265            joined_patterns
1266        ),
1267    );
1268
1269    // Point at the definition of non-covered `enum` variants.
1270    if let Some(AdtDefinedHere { adt_def_span, ty, variants }) =
1271        report_adt_defined_here(cx.tcx, scrut_ty, &witnesses, true)
1272    {
1273        let mut multi_span = MultiSpan::from_span(adt_def_span);
1274        multi_span.push_span_label(adt_def_span, "");
1275        for Variant { span } in variants {
1276            multi_span.push_span_label(span, "not covered");
1277        }
1278        err.span_note(multi_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` defined here", ty))
    })format!("`{ty}` defined here"));
1279    }
1280    err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the matched value is of type `{0}`",
                scrut_ty))
    })format!("the matched value is of type `{}`", scrut_ty));
1281
1282    if !is_empty_match {
1283        let mut special_tys = FxIndexSet::default();
1284        // Look at the first witness.
1285        collect_special_tys(cx, &witnesses[0], &mut special_tys);
1286
1287        for ty in special_tys {
1288            if ty.is_ptr_sized_integral() {
1289                if ty.inner() == cx.tcx.types.usize {
1290                    err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}::MAX` is not treated as exhaustive, so half-open ranges are necessary to match exhaustively",
                ty))
    })format!(
1291                        "`{ty}::MAX` is not treated as exhaustive, \
1292                        so half-open ranges are necessary to match exhaustively",
1293                    ));
1294                } else if ty.inner() == cx.tcx.types.isize {
1295                    err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}::MIN` and `{0}::MAX` are not treated as exhaustive, so half-open ranges are necessary to match exhaustively",
                ty))
    })format!(
1296                        "`{ty}::MIN` and `{ty}::MAX` are not treated as exhaustive, \
1297                        so half-open ranges are necessary to match exhaustively",
1298                    ));
1299                }
1300            } else if ty.inner() == cx.tcx.types.str_ {
1301                err.note("`&str` cannot be matched exhaustively, so a wildcard `_` is necessary");
1302            } else if cx.is_foreign_non_exhaustive_enum(ty) {
1303                err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is marked as non-exhaustive, so a wildcard `_` is necessary to match exhaustively",
                ty))
    })format!("`{ty}` is marked as non-exhaustive, so a wildcard `_` is necessary to match exhaustively"));
1304            } else if cx.is_uninhabited(ty.inner()) {
1305                // The type is uninhabited yet there is a witness: we must be in the `MaybeInvalid`
1306                // case.
1307                err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` is uninhabited but is not being matched by value, so a wildcard `_` is required",
                ty))
    })format!("`{ty}` is uninhabited but is not being matched by value, so a wildcard `_` is required"));
1308            }
1309        }
1310    }
1311
1312    if let ty::Ref(_, sub_ty, _) = scrut_ty.kind() {
1313        if !sub_ty.is_inhabited_from(cx.tcx, cx.module, cx.typing_env) {
1314            err.note("references are always considered inhabited");
1315        }
1316    }
1317
1318    for &arm in arms {
1319        let arm = &thir.arms[arm];
1320        if let Some(def_id) = is_const_pat_that_looks_like_binding(cx.tcx, &arm.pattern) {
1321            let const_name = cx.tcx.item_name(def_id);
1322            err.span_label(
1323                arm.pattern.span,
1324                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this pattern doesn\'t introduce a new catch-all binding, but rather pattern matches against the value of constant `{0}`",
                const_name))
    })format!(
1325                    "this pattern doesn't introduce a new catch-all binding, but rather pattern \
1326                     matches against the value of constant `{const_name}`",
1327                ),
1328            );
1329            err.span_note(cx.tcx.def_span(def_id), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("constant `{0}` defined here",
                const_name))
    })format!("constant `{const_name}` defined here"));
1330            err.span_suggestion_verbose(
1331                arm.pattern.span.shrink_to_hi(),
1332                "if you meant to introduce a binding, use a different name",
1333                "_var".to_string(),
1334                Applicability::MaybeIncorrect,
1335            );
1336        }
1337    }
1338
1339    // Whether we suggest the actual missing patterns or `_`.
1340    let suggest_the_witnesses = witnesses.len() < 4;
1341    let suggested_arm = if suggest_the_witnesses {
1342        let pattern = witnesses
1343            .iter()
1344            .map(|witness| cx.print_witness_pat(witness))
1345            .collect::<Vec<String>>()
1346            .join(" | ");
1347        if witnesses.iter().all(|p| p.is_never_pattern()) && cx.tcx.features().never_patterns() {
1348            // Arms with a never pattern don't take a body.
1349            pattern
1350        } else {
1351            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} => todo!()", pattern))
    })format!("{pattern} => todo!()")
1352        }
1353    } else {
1354        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("_ => todo!()"))
    })format!("_ => todo!()")
1355    };
1356    let mut suggestion = None;
1357    let sm = cx.tcx.sess.source_map();
1358    match arms {
1359        [] if let Some(braces_span) = braces_span => {
1360            // Get the span for the empty match body `{}`.
1361            let (indentation, more) = if let Some(snippet) = sm.indentation_before(sp) {
1362                (::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n{0}", snippet))
    })format!("\n{snippet}"), "    ")
1363            } else {
1364                (" ".to_string(), "")
1365            };
1366            suggestion = Some((
1367                braces_span,
1368                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {{{0}{1}{2},{0}}}", indentation,
                more, suggested_arm))
    })format!(" {{{indentation}{more}{suggested_arm},{indentation}}}",),
1369            ));
1370        }
1371        [only] => {
1372            let only = &thir[*only];
1373            let (pre_indentation, is_multiline) = if let Some(snippet) =
1374                sm.indentation_before(only.span)
1375                && let Ok(with_trailing) =
1376                    sm.span_extend_while(only.span, |c| c.is_whitespace() || c == ',')
1377                && sm.is_multiline(with_trailing)
1378            {
1379                (::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n{0}", snippet))
    })format!("\n{snippet}"), true)
1380            } else {
1381                (" ".to_string(), false)
1382            };
1383            let only_body = &thir[only.body];
1384            let comma = if #[allow(non_exhaustive_omitted_patterns)] match only_body.kind {
    ExprKind::Block { .. } => true,
    _ => false,
}matches!(only_body.kind, ExprKind::Block { .. })
1385                && only.span.eq_ctxt(only_body.span)
1386                && is_multiline
1387            {
1388                ""
1389            } else {
1390                ","
1391            };
1392            suggestion = Some((
1393                only.span.shrink_to_hi(),
1394                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}{2}", comma, pre_indentation,
                suggested_arm))
    })format!("{comma}{pre_indentation}{suggested_arm}"),
1395            ));
1396        }
1397        [.., prev, last] => {
1398            let prev = &thir[*prev];
1399            let last = &thir[*last];
1400            if prev.span.eq_ctxt(last.span) {
1401                let last_body = &thir[last.body];
1402                let comma = if #[allow(non_exhaustive_omitted_patterns)] match last_body.kind {
    ExprKind::Block { .. } => true,
    _ => false,
}matches!(last_body.kind, ExprKind::Block { .. })
1403                    && last.span.eq_ctxt(last_body.span)
1404                {
1405                    ""
1406                } else {
1407                    ","
1408                };
1409                let spacing = if sm.is_multiline(prev.span.between(last.span)) {
1410                    sm.indentation_before(last.span).map(|indent| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n{0}", indent))
    })format!("\n{indent}"))
1411                } else {
1412                    Some(" ".to_string())
1413                };
1414                if let Some(spacing) = spacing {
1415                    suggestion = Some((
1416                        last.span.shrink_to_hi(),
1417                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}{2}", comma, spacing,
                suggested_arm))
    })format!("{comma}{spacing}{suggested_arm}"),
1418                    ));
1419                }
1420            }
1421        }
1422        _ => {}
1423    }
1424
1425    let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("ensure that all possible cases are being handled by adding a match arm with a wildcard pattern{0}{1}",
                if witnesses.len() > 1 && suggest_the_witnesses &&
                        suggestion.is_some() {
                    ", a match arm with multiple or-patterns"
                } else { "" },
                match witnesses.len() {
                    0 if suggestion.is_some() => " as shown",
                    0 => "",
                    1 if suggestion.is_some() =>
                        " or an explicit pattern as shown",
                    1 => " or an explicit pattern",
                    _ if suggestion.is_some() =>
                        " as shown, or multiple match arms",
                    _ => " or multiple match arms",
                }))
    })format!(
1426        "ensure that all possible cases are being handled by adding a match arm with a wildcard \
1427         pattern{}{}",
1428        if witnesses.len() > 1 && suggest_the_witnesses && suggestion.is_some() {
1429            ", a match arm with multiple or-patterns"
1430        } else {
1431            // we are either not suggesting anything, or suggesting `_`
1432            ""
1433        },
1434        match witnesses.len() {
1435            // non-exhaustive enum case
1436            0 if suggestion.is_some() => " as shown",
1437            0 => "",
1438            1 if suggestion.is_some() => " or an explicit pattern as shown",
1439            1 => " or an explicit pattern",
1440            _ if suggestion.is_some() => " as shown, or multiple match arms",
1441            _ => " or multiple match arms",
1442        },
1443    );
1444
1445    if would_be_exhaustive_without_guards {
1446        err.subdiagnostic(NonExhaustiveMatchAllArmsGuarded);
1447    }
1448    if let Some((span, sugg)) = suggestion {
1449        err.span_suggestion_verbose(span, msg, sugg, Applicability::HasPlaceholders);
1450    } else {
1451        err.help(msg);
1452    }
1453    err.emit()
1454}
1455
1456fn joined_uncovered_patterns<'p, 'tcx>(
1457    cx: &PatCtxt<'p, 'tcx>,
1458    witnesses: &[WitnessPat<'p, 'tcx>],
1459) -> String {
1460    const LIMIT: usize = 3;
1461    let pat_to_str = |pat: &WitnessPat<'p, 'tcx>| cx.print_witness_pat(pat);
1462    match witnesses {
1463        [] => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
1464        [witness] => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`",
                cx.print_witness_pat(witness)))
    })format!("`{}`", cx.print_witness_pat(witness)),
1465        [head @ .., tail] if head.len() < LIMIT => {
1466            let head: Vec<_> = head.iter().map(pat_to_str).collect();
1467            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` and `{1}`",
                head.join("`, `"), cx.print_witness_pat(tail)))
    })format!("`{}` and `{}`", head.join("`, `"), cx.print_witness_pat(tail))
1468        }
1469        _ => {
1470            let (head, tail) = witnesses.split_at(LIMIT);
1471            let head: Vec<_> = head.iter().map(pat_to_str).collect();
1472            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` and {1} more",
                head.join("`, `"), tail.len()))
    })format!("`{}` and {} more", head.join("`, `"), tail.len())
1473        }
1474    }
1475}
1476
1477/// Collect types that require specific explanations when they show up in witnesses.
1478fn collect_special_tys<'tcx>(
1479    cx: &PatCtxt<'_, 'tcx>,
1480    pat: &WitnessPat<'_, 'tcx>,
1481    special_tys: &mut FxIndexSet<RevealedTy<'tcx>>,
1482) {
1483    if #[allow(non_exhaustive_omitted_patterns)] match pat.ctor() {
    Constructor::NonExhaustive | Constructor::Never => true,
    _ => false,
}matches!(pat.ctor(), Constructor::NonExhaustive | Constructor::Never) {
1484        special_tys.insert(*pat.ty());
1485    }
1486    if let Constructor::IntRange(range) = pat.ctor() {
1487        if cx.is_range_beyond_boundaries(range, *pat.ty()) {
1488            // The range denotes the values before `isize::MIN` or the values after `usize::MAX`/`isize::MAX`.
1489            special_tys.insert(*pat.ty());
1490        }
1491    }
1492    pat.iter_fields().for_each(|field_pat| collect_special_tys(cx, field_pat, special_tys))
1493}
1494
1495fn report_adt_defined_here<'tcx>(
1496    tcx: TyCtxt<'tcx>,
1497    ty: Ty<'tcx>,
1498    witnesses: &[WitnessPat<'_, 'tcx>],
1499    point_at_non_local_ty: bool,
1500) -> Option<AdtDefinedHere<'tcx>> {
1501    let ty = ty.peel_refs();
1502    let ty::Adt(def, _) = ty.kind() else {
1503        return None;
1504    };
1505    let adt_def_span =
1506        tcx.hir_get_if_local(def.did()).and_then(|node| node.ident()).map(|ident| ident.span);
1507    let adt_def_span = if point_at_non_local_ty {
1508        adt_def_span.unwrap_or_else(|| tcx.def_span(def.did()))
1509    } else {
1510        adt_def_span?
1511    };
1512
1513    let mut variants = ::alloc::vec::Vec::new()vec![];
1514    for span in maybe_point_at_variant(tcx, *def, witnesses.iter().take(5)) {
1515        variants.push(Variant { span });
1516    }
1517    Some(AdtDefinedHere { adt_def_span, ty, variants })
1518}
1519
1520fn maybe_point_at_variant<'a, 'p: 'a, 'tcx: 'p>(
1521    tcx: TyCtxt<'tcx>,
1522    def: AdtDef<'tcx>,
1523    patterns: impl Iterator<Item = &'a WitnessPat<'p, 'tcx>>,
1524) -> Vec<Span> {
1525    let mut covered = ::alloc::vec::Vec::new()vec![];
1526    for pattern in patterns {
1527        if let Constructor::Variant(variant_index) = pattern.ctor() {
1528            if let ty::Adt(this_def, _) = pattern.ty().kind()
1529                && this_def.did() != def.did()
1530            {
1531                continue;
1532            }
1533            let sp = def.variant(*variant_index).ident(tcx).span;
1534            if covered.contains(&sp) {
1535                // Don't point at variants that have already been covered due to other patterns to avoid
1536                // visual clutter.
1537                continue;
1538            }
1539            covered.push(sp);
1540        }
1541        covered.extend(maybe_point_at_variant(tcx, def, pattern.iter_fields()));
1542    }
1543    covered
1544}