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