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_errors::codes::*;
5use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan, msg, struct_span_code_err};
6use rustc_hir::def::*;
7use rustc_hir::def_id::{DefId, LocalDefId};
8use rustc_hir::{self as hir, BindingMode, ByRef, HirId, MatchSource};
9use rustc_infer::infer::TyCtxtInferExt;
10use rustc_lint_defs::builtin::{
11    BINDINGS_WITH_VARIANT_NAME, IRREFUTABLE_LET_PATTERNS, UNREACHABLE_PATTERNS,
12};
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::diagnostics::Uncovered;
18use rustc_pattern_analysis::rustc::{
19    Constructor, DeconstructedPat, MatchArm, RedundancyExplanation, RevealedTy,
20    RustcPatCtxt as PatCtxt, Usefulness, UsefulnessReport, WitnessPat,
21};
22use rustc_span::edit_distance::find_best_match_for_name;
23use rustc_span::hygiene::DesugaringKind;
24use rustc_span::{Ident, Span, bug};
25use rustc_trait_selection::infer::InferCtxtExt;
26use tracing::instrument;
27
28use crate::diagnostics::*;
29
30pub(crate) fn check_match(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
31    let typeck_results = tcx.typeck(def_id);
32    let (thir, expr) = tcx.thir_body(def_id)?;
33    let thir = thir.borrow();
34    let pattern_arena = TypedArena::default();
35    let dropless_arena = DroplessArena::default();
36    let mut visitor = MatchVisitor {
37        tcx,
38        thir: &*thir,
39        typeck_results,
40        typing_env: ty::TypingEnv::post_typeck_until_borrowck_for_mir_build(tcx, def_id),
41        hir_source: tcx.local_def_id_to_hir_id(def_id),
42        let_source: LetSource::None,
43        pattern_arena: &pattern_arena,
44        dropless_arena: &dropless_arena,
45        error: Ok(()),
46    };
47    visitor.visit_expr(&thir[expr]);
48
49    let origin = match tcx.def_kind(def_id) {
50        DefKind::AssocFn | DefKind::Fn => "function argument",
51        DefKind::Closure => "closure argument",
52        // other types of MIR don't have function parameters, and we don't need to
53        // categorize those for the irrefutable check.
54        _ if thir.params.is_empty() => "",
55        kind => bug_impl(None,
    format_args!("unexpected function parameters in THIR: {0:?} {1:?}", kind,
        def_id), Location::caller())bug!("unexpected function parameters in THIR: {kind:?} {def_id:?}"),
56    };
57
58    for param in thir.params.iter() {
59        if let Some(ref pattern) = param.pat {
60            visitor.check_binding_is_irrefutable(pattern, origin, None, None, None);
61        }
62    }
63    visitor.error
64}
65
66#[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]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for RefutableFlag { }
#[automatically_derived]
impl ::core::clone::Clone for RefutableFlag {
    #[inline]
    fn clone(&self) -> RefutableFlag { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for RefutableFlag { }
#[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)]
67enum RefutableFlag {
68    Irrefutable,
69    Refutable,
70}
71use RefutableFlag::*;
72
73#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for LetSource { }
#[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::marker::StructuralPartialEq for LetSource { }
#[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 { }Eq)]
74enum LetSource {
75    None,
76    PlainLet,
77    IfLet,
78    IfLetGuard,
79    LetElse,
80    WhileLet,
81    Else,
82    ElseIfLet,
83}
84
85struct MatchVisitor<'p, 'tcx> {
86    tcx: TyCtxt<'tcx>,
87    typing_env: ty::TypingEnv<'tcx>,
88    typeck_results: &'tcx ty::TypeckResults<'tcx>,
89    thir: &'p Thir<'tcx>,
90    hir_source: HirId,
91    let_source: LetSource,
92    pattern_arena: &'p TypedArena<DeconstructedPat<'p, 'tcx>>,
93    dropless_arena: &'p DroplessArena,
94    /// Tracks if we encountered an error while checking this body. That the first function to
95    /// report it stores it here. Some functions return `Result` to allow callers to short-circuit
96    /// on error, but callers don't need to store it here again.
97    error: Result<(), ErrorGuaranteed>,
98}
99
100// Visitor for a thir body. This calls `check_match` and `check_let` as appropriate.
101impl<'p, 'tcx> Visitor<'p, 'tcx> for MatchVisitor<'p, 'tcx> {
102    fn thir(&self) -> &'p Thir<'tcx> {
103        self.thir
104    }
105
106    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_build/src/thir/pattern/check_match.rs"),
                                    ::tracing_core::__macro_support::Option::Some(106u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::check_match"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("arm")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("arm");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&arm)
                                                            as &dyn ::tracing::field::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))]
107    fn visit_arm(&mut self, arm: &'p Arm<'tcx>) {
108        self.with_hir_source(arm.hir_id, |this| {
109            if let Some(expr) = arm.guard {
110                this.with_let_source(LetSource::IfLetGuard, |this| {
111                    this.visit_expr(&this.thir[expr])
112                });
113            }
114            this.visit_pat(&arm.pattern);
115            this.visit_expr(&self.thir[arm.body]);
116        });
117    }
118
119    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_build/src/thir/pattern/check_match.rs"),
                                    ::tracing_core::__macro_support::Option::Some(119u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::check_match"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ex")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ex");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ex)
                                                            as &dyn ::tracing::field::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, ref arms, match_source } => {
                    self.check_match(scrutinee, arms, match_source, ex.span);
                }
                ExprKind::LoopMatch {
                    match_data: LoopMatchMatchData {
                        scrutinee, ref arms, span
                        }, .. } => {
                    self.check_match(scrutinee, arms, MatchSource::Normal,
                        span);
                }
                ExprKind::Let { ref pat, expr } => {
                    self.check_let(pat, Some(expr), ex.span);
                }
                ExprKind::LogicalOp { op: LogicalOp::And, .. } if
                    !#[allow(non_exhaustive_omitted_patterns)] match self.let_source
                            {
                            LetSource::None => true,
                            _ => false,
                        } => {
                    let mut chain_refutabilities = Vec::new();
                    let Ok(()) =
                        self.visit_land(ex,
                            &mut chain_refutabilities) else { return };
                    if let [Some((_, Irrefutable))] = chain_refutabilities[..] {
                        self.lint_single_let(ex.span, None, None);
                    }
                    return;
                }
                _ => {}
            };
            self.with_let_source(LetSource::None,
                |this| visit::walk_expr(this, ex));
        }
    }
}#[instrument(level = "trace", skip(self))]
120    fn visit_expr(&mut self, ex: &'p Expr<'tcx>) {
121        match ex.kind {
122            ExprKind::Scope { value, hir_id, .. } => {
123                self.with_hir_source(hir_id, |this| {
124                    this.visit_expr(&this.thir[value]);
125                });
126                return;
127            }
128            ExprKind::If { cond, then, else_opt, if_then_scope: _ } => {
129                // Give a specific `let_source` for the condition.
130                let let_source = match ex.span.desugaring_kind() {
131                    Some(DesugaringKind::WhileLoop) => LetSource::WhileLet,
132                    _ => match self.let_source {
133                        LetSource::Else => LetSource::ElseIfLet,
134                        _ => LetSource::IfLet,
135                    },
136                };
137                self.with_let_source(let_source, |this| this.visit_expr(&self.thir[cond]));
138                self.with_let_source(LetSource::None, |this| {
139                    this.visit_expr(&this.thir[then]);
140                });
141                if let Some(else_) = else_opt {
142                    self.with_let_source(LetSource::Else, |this| {
143                        this.visit_expr(&this.thir[else_])
144                    });
145                }
146                return;
147            }
148            ExprKind::Match { scrutinee, ref arms, match_source } => {
149                self.check_match(scrutinee, arms, match_source, ex.span);
150            }
151            ExprKind::LoopMatch {
152                match_data: LoopMatchMatchData { scrutinee, ref arms, span },
153                ..
154            } => {
155                self.check_match(scrutinee, arms, MatchSource::Normal, span);
156            }
157            ExprKind::Let { ref pat, expr } => {
158                self.check_let(pat, Some(expr), ex.span);
159            }
160            ExprKind::LogicalOp { op: LogicalOp::And, .. }
161                if !matches!(self.let_source, LetSource::None) =>
162            {
163                let mut chain_refutabilities = Vec::new();
164                let Ok(()) = self.visit_land(ex, &mut chain_refutabilities) else { return };
165                // Lint only single irrefutable let binding.
166                if let [Some((_, Irrefutable))] = chain_refutabilities[..] {
167                    self.lint_single_let(ex.span, None, None);
168                }
169                return;
170            }
171            _ => {}
172        };
173        self.with_let_source(LetSource::None, |this| visit::walk_expr(this, ex));
174    }
175
176    fn visit_stmt(&mut self, stmt: &'p Stmt<'tcx>) {
177        match stmt.kind {
178            StmtKind::Let { ref pattern, initializer, else_block, hir_id, span, .. } => {
179                self.with_hir_source(hir_id, |this| {
180                    let let_source =
181                        if else_block.is_some() { LetSource::LetElse } else { LetSource::PlainLet };
182                    this.with_let_source(let_source, |this| {
183                        this.check_let(pattern, initializer, span)
184                    });
185                    visit::walk_stmt(this, stmt);
186                });
187            }
188            StmtKind::Expr { .. } => {
189                visit::walk_stmt(self, stmt);
190            }
191        }
192    }
193}
194
195impl<'p, 'tcx> MatchVisitor<'p, 'tcx> {
196    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_build/src/thir/pattern/check_match.rs"),
                                    ::tracing_core::__macro_support::Option::Some(196u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::check_match"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("let_source")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("let_source");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&let_source)
                                                            as &dyn ::tracing::field::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;
            f(self);
            self.let_source = old_let_source;
        }
    }
}#[instrument(level = "trace", skip(self, f))]
197    fn with_let_source(&mut self, let_source: LetSource, f: impl FnOnce(&mut Self)) {
198        let old_let_source = self.let_source;
199        self.let_source = let_source;
200        f(self);
201        self.let_source = old_let_source;
202    }
203
204    fn with_hir_source<T>(&mut self, new_hir_source: HirId, f: impl FnOnce(&mut Self) -> T) -> T {
205        let old_hir_source = self.hir_source;
206        self.hir_source = new_hir_source;
207        let ret = f(self);
208        self.hir_source = old_hir_source;
209        ret
210    }
211
212    /// Visit a nested chain of `&&`. Used for if-let chains. This must call `visit_expr` on the
213    /// subexpressions we are not handling ourselves.
214    fn visit_land(
215        &mut self,
216        ex: &'p Expr<'tcx>,
217        accumulator: &mut Vec<Option<(Span, RefutableFlag)>>,
218    ) -> Result<(), ErrorGuaranteed> {
219        match ex.kind {
220            ExprKind::Scope { value, hir_id, .. } => {
221                self.with_hir_source(hir_id, |this| this.visit_land(&this.thir[value], accumulator))
222            }
223            ExprKind::LogicalOp { op: LogicalOp::And, lhs, rhs } => {
224                // We recurse into the lhs only, because `&&` chains associate to the left.
225                let res_lhs = self.visit_land(&self.thir[lhs], accumulator);
226                let res_rhs = self.visit_land_rhs(&self.thir[rhs])?;
227                accumulator.push(res_rhs);
228                res_lhs
229            }
230            _ => {
231                let res = self.visit_land_rhs(ex)?;
232                accumulator.push(res);
233                Ok(())
234            }
235        }
236    }
237
238    /// Visit the right-hand-side of a `&&`. Used for if-let chains. Returns `Some` if the
239    /// expression was ultimately a `let ... = ...`, and `None` if it was a normal boolean
240    /// expression. This must call `visit_expr` on the subexpressions we are not handling ourselves.
241    fn visit_land_rhs(
242        &mut self,
243        ex: &'p Expr<'tcx>,
244    ) -> Result<Option<(Span, RefutableFlag)>, ErrorGuaranteed> {
245        match ex.kind {
246            ExprKind::Scope { value, hir_id, .. } => {
247                self.with_hir_source(hir_id, |this| this.visit_land_rhs(&this.thir[value]))
248            }
249            ExprKind::Let { ref pat, expr } => {
250                let expr = &self.thir()[expr];
251                self.with_let_source(LetSource::None, |this| {
252                    this.visit_expr(expr);
253                });
254                Ok(Some((ex.span, self.is_let_irrefutable(pat, Some(expr))?)))
255            }
256            _ => {
257                self.with_let_source(LetSource::None, |this| {
258                    this.visit_expr(ex);
259                });
260                Ok(None)
261            }
262        }
263    }
264
265    fn lower_pattern(
266        &mut self,
267        cx: &PatCtxt<'p, 'tcx>,
268        pat: &'p Pat<'tcx>,
269    ) -> Result<&'p DeconstructedPat<'p, 'tcx>, ErrorGuaranteed> {
270        if let Err(err) = pat.pat_error_reported() {
271            self.error = Err(err);
272            Err(err)
273        } else {
274            // Check the pattern for some things unrelated to exhaustiveness.
275            let refutable = if cx.refutable { Refutable } else { Irrefutable };
276            let mut err = Ok(());
277            pat.walk_always(|pat| {
278                check_borrow_conflicts_in_at_patterns(self, pat);
279                check_for_bindings_named_same_as_variants(self, pat, refutable);
280                err = err.and(check_never_pattern(cx, pat));
281            });
282            err?;
283            Ok(self.pattern_arena.alloc(cx.lower_pat(pat)))
284        }
285    }
286
287    /// Inspects the match scrutinee expression to determine whether the place it evaluates to may
288    /// hold invalid data.
289    fn is_known_valid_scrutinee(&self, scrutinee: &Expr<'tcx>) -> bool {
290        use ExprKind::*;
291        match &scrutinee.kind {
292            // Pointers can validly point to a place with invalid data. It is undecided whether
293            // references can too, so we conservatively assume they can.
294            Deref { .. } => false,
295            // Inherit validity of the parent place, unless the parent is an union.
296            Field { lhs, .. } => {
297                let lhs = &self.thir()[*lhs];
298                match lhs.ty.kind() {
299                    ty::Adt(def, _) if def.is_union() => false,
300                    _ => self.is_known_valid_scrutinee(lhs),
301                }
302            }
303            // Essentially a field access.
304            Index { lhs, .. } => {
305                let lhs = &self.thir()[*lhs];
306                self.is_known_valid_scrutinee(lhs)
307            }
308
309            // No-op.
310            Scope { value, .. } => self.is_known_valid_scrutinee(&self.thir()[*value]),
311
312            // Casts don't cause a load.
313            NeverToAny { source }
314            | Cast { source }
315            | ValueExpr { source }
316            | PointerCoercion { source, .. }
317            | PlaceTypeAscription { source, .. }
318            | ValueTypeAscription { source, .. }
319            | PlaceUnwrapUnsafeBinder { source }
320            | ValueUnwrapUnsafeBinder { source }
321            | WrapUnsafeBinder { source } => self.is_known_valid_scrutinee(&self.thir()[*source]),
322
323            // These diverge.
324            Become { .. }
325            | Break { .. }
326            | Continue { .. }
327            | ConstContinue { .. }
328            | Return { .. } => true,
329
330            // These are statements that evaluate to `()`.
331            Assign { .. } | AssignOp { .. } | InlineAsm { .. } | Let { .. } => true,
332
333            // These evaluate to a value.
334            RawBorrow { .. }
335            | Adt { .. }
336            | Array { .. }
337            | Binary { .. }
338            | Block { .. }
339            | Borrow { .. }
340            | Call { .. }
341            | ByUse { .. }
342            | Closure { .. }
343            | ConstBlock { .. }
344            | ConstParam { .. }
345            | If { .. }
346            | Literal { .. }
347            | LogicalOp { .. }
348            | Loop { .. }
349            | LoopMatch { .. }
350            | Match { .. }
351            | NamedConst { .. }
352            | NonHirLiteral { .. }
353            | Repeat { .. }
354            | StaticRef { .. }
355            | ThreadLocalRef { .. }
356            | Tuple { .. }
357            | Unary { .. }
358            | UpvarRef { .. }
359            | VarRef { .. }
360            | ZstLiteral { .. }
361            | Yield { .. }
362            | Reborrow { .. } => true,
363        }
364    }
365
366    fn new_cx(
367        &self,
368        refutability: RefutableFlag,
369        whole_match_span: Option<Span>,
370        scrutinee: Option<&Expr<'tcx>>,
371        scrut_span: Span,
372    ) -> PatCtxt<'p, 'tcx> {
373        let refutable = match refutability {
374            Irrefutable => false,
375            Refutable => true,
376        };
377        // If we don't have a scrutinee we're either a function parameter or a `let x;`. Both cases
378        // require validity.
379        let known_valid_scrutinee =
380            scrutinee.map(|scrut| self.is_known_valid_scrutinee(scrut)).unwrap_or(true);
381        PatCtxt {
382            tcx: self.tcx,
383            typeck_results: self.typeck_results,
384            typing_env: self.typing_env,
385            module: self.tcx.parent_module(self.hir_source),
386            dropless_arena: self.dropless_arena,
387            match_lint_level: self.hir_source,
388            whole_match_span,
389            scrut_span,
390            refutable,
391            known_valid_scrutinee,
392            internal_state: Default::default(),
393        }
394    }
395
396    fn analyze_patterns(
397        &mut self,
398        cx: &PatCtxt<'p, 'tcx>,
399        arms: &[MatchArm<'p, 'tcx>],
400        scrut_ty: Ty<'tcx>,
401    ) -> Result<UsefulnessReport<'p, 'tcx>, ErrorGuaranteed> {
402        let report =
403            rustc_pattern_analysis::rustc::analyze_match(&cx, &arms, scrut_ty).map_err(|err| {
404                self.error = Err(err);
405                err
406            })?;
407
408        // Warn unreachable subpatterns.
409        for (arm, is_useful) in report.arm_usefulness.iter() {
410            if let Usefulness::Useful(redundant_subpats) = is_useful
411                && !redundant_subpats.is_empty()
412            {
413                let mut redundant_subpats = redundant_subpats.clone();
414                // Emit lints in the order in which they occur in the file.
415                redundant_subpats.sort_unstable_by_key(|(pat, _)| pat.data().span);
416                for (pat, explanation) in redundant_subpats {
417                    report_unreachable_pattern(cx, arm.arm_data, pat, &explanation, None)
418                }
419            }
420        }
421        Ok(report)
422    }
423
424    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_build/src/thir/pattern/check_match.rs"),
                                    ::tracing_core::__macro_support::Option::Some(424u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::check_match"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("pat")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("pat");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("scrutinee")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("scrutinee");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pat)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&scrutinee)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::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 {
                if let hir::Node::LetStmt(&hir::LetStmt {
                        source: hir::LocalSource::AssignDesugar, .. }) =
                        self.tcx.hir_node(self.hir_source) {
                    self.check_binding_is_irrefutable(pat, "assignment",
                        Some(Inform { descr: "destructuring assignments" }), scrut,
                        None);
                } else {
                    self.check_binding_is_irrefutable(pat, "local binding",
                        Some(Inform { descr: "`let` bindings" }), scrut,
                        Some(span));
                }
            } else if let Ok(Irrefutable) =
                    self.is_let_irrefutable(pat, scrut) {
                if span.from_expansion() {
                    self.lint_single_let(span, None, None);
                    return;
                }
                let let_else_span =
                    self.check_irrefutable_option_some(pat, scrut, span);
                let sm = self.tcx.sess.source_map();
                let next_token_start =
                    sm.span_extend_while_whitespace(span.clone()).hi();
                let line_span =
                    sm.span_extend_to_line(span.clone()).with_lo(next_token_start);
                let else_keyword_span = sm.span_until_whitespace(line_span);
                self.lint_single_let(span, Some(else_keyword_span),
                    let_else_span);
            }
        }
    }
}#[instrument(level = "trace", skip(self))]
425    fn check_let(&mut self, pat: &'p Pat<'tcx>, scrutinee: Option<ExprId>, span: Span) {
426        assert!(self.let_source != LetSource::None);
427        let scrut = scrutinee.map(|id| &self.thir[id]);
428        if let LetSource::PlainLet = self.let_source {
429            // `lhs = rhs` destructuring assignments are lowered to a `let` tagged
430            // `AssignDesugar`; report them as assignments, not `let` bindings (#157553).
431            if let hir::Node::LetStmt(&hir::LetStmt {
432                source: hir::LocalSource::AssignDesugar,
433                ..
434            }) = self.tcx.hir_node(self.hir_source)
435            {
436                self.check_binding_is_irrefutable(
437                    pat,
438                    "assignment",
439                    Some(Inform { descr: "destructuring assignments" }),
440                    scrut,
441                    None,
442                );
443            } else {
444                self.check_binding_is_irrefutable(
445                    pat,
446                    "local binding",
447                    Some(Inform { descr: "`let` bindings" }),
448                    scrut,
449                    Some(span),
450                );
451            }
452        } else if let Ok(Irrefutable) = self.is_let_irrefutable(pat, scrut) {
453            if span.from_expansion() {
454                self.lint_single_let(span, None, None);
455                return;
456            }
457            let let_else_span = self.check_irrefutable_option_some(pat, scrut, span);
458
459            let sm = self.tcx.sess.source_map();
460            let next_token_start = sm.span_extend_while_whitespace(span.clone()).hi();
461            let line_span = sm.span_extend_to_line(span.clone()).with_lo(next_token_start);
462            let else_keyword_span = sm.span_until_whitespace(line_span);
463            self.lint_single_let(span, Some(else_keyword_span), let_else_span);
464        }
465    }
466
467    /// Check case `let x = Some(y);`, user likely intended to destructure `Option`
468    fn check_irrefutable_option_some(
469        &self,
470        pat: &'p Pat<'tcx>,
471        initializer: Option<&Expr<'tcx>>,
472        span: Span,
473    ) -> Option<LetElseReplacementSuggestion> {
474        if let sm = self.tcx.sess.source_map()
475            && let Some(initializer) = initializer
476            && let Some(s_ty) = initializer.ty.ty_adt_def()
477            && self.tcx.is_diagnostic_item(rustc_span::sym::Option, s_ty.did())
478            && let ExprKind::Scope { value, .. } = initializer.kind
479            && let initializer_expr = &self.thir[value]
480            && let ExprKind::Adt(AdtExpr { fields, .. }) = &initializer_expr.kind
481            && let Some(field) = fields.first()
482            && let inner = &self.thir[field.expr]
483            && let Some(inner_ty) = inner.ty.ty_adt_def()
484            && self.tcx.is_diagnostic_item(rustc_span::sym::Option, inner_ty.did())
485            && let Ok(rhs) = sm.span_to_snippet(inner.span)
486            && let Ok(lhs) = sm.span_to_snippet(pat.span)
487        {
488            let lhs = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Some({0})", lhs))
    })format!("Some({})", lhs);
489            Some(LetElseReplacementSuggestion { span, lhs, rhs })
490        } else {
491            None
492        }
493    }
494
495    fn check_match(
496        &mut self,
497        scrut: ExprId,
498        arms: &[ArmId],
499        source: hir::MatchSource,
500        expr_span: Span,
501    ) {
502        let scrut = &self.thir[scrut];
503        let cx = self.new_cx(Refutable, Some(expr_span), Some(scrut), scrut.span);
504
505        let mut tarms = Vec::with_capacity(arms.len());
506        for &arm in arms {
507            let arm = &self.thir.arms[arm];
508            let got_error = self.with_hir_source(arm.hir_id, |this| {
509                let Ok(pat) = this.lower_pattern(&cx, &arm.pattern) else { return true };
510                let arm =
511                    MatchArm { pat, arm_data: this.hir_source, has_guard: arm.guard.is_some() };
512                tarms.push(arm);
513                false
514            });
515            if got_error {
516                return;
517            }
518        }
519
520        let Ok(report) = self.analyze_patterns(&cx, &tarms, scrut.ty) else { return };
521
522        match source {
523            // Don't report arm reachability of desugared `match $iter.into_iter() { iter => .. }`
524            // when the iterator is an uninhabited type. unreachable_code will trigger instead.
525            hir::MatchSource::ForLoopDesugar if arms.len() == 1 => {}
526            hir::MatchSource::ForLoopDesugar
527            | hir::MatchSource::Postfix
528            | hir::MatchSource::Normal
529            | hir::MatchSource::FormatArgs => {
530                let is_match_arm =
531                    #[allow(non_exhaustive_omitted_patterns)] match source {
    hir::MatchSource::Postfix | hir::MatchSource::Normal => true,
    _ => false,
}matches!(source, hir::MatchSource::Postfix | hir::MatchSource::Normal);
532                report_arm_reachability(&cx, &report, is_match_arm);
533            }
534            // Unreachable patterns in try and await expressions occur when one of
535            // the arms are an uninhabited type. Which is OK.
536            hir::MatchSource::AwaitDesugar | hir::MatchSource::TryDesugar(_) => {}
537        }
538
539        // Check if the match is exhaustive.
540        let witnesses = report.non_exhaustiveness_witnesses;
541        if !witnesses.is_empty() {
542            if source == hir::MatchSource::ForLoopDesugar
543                && let [_, snd_arm] = *arms
544            {
545                // the for loop pattern is not irrefutable
546                let pat = &self.thir[snd_arm].pattern;
547                // `pat` should be `Some(<pat_field>)` from a desugared for loop.
548                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));
549                let PatKind::Variant { ref subpatterns, .. } = pat.kind else { bug_impl(None, format_args!("impossible case reached"), Location::caller())bug!() };
550                let [pat_field] = &subpatterns[..] else { bug_impl(None, format_args!("impossible case reached"), Location::caller())bug!() };
551                self.check_binding_is_irrefutable(
552                    &pat_field.pattern,
553                    "`for` loop binding",
554                    None,
555                    None,
556                    None,
557                );
558            } else {
559                // span after scrutinee, or after `.match`. That is, the braces, arms,
560                // and any whitespace preceding the braces.
561                let braces_span = match source {
562                    hir::MatchSource::Normal => scrut
563                        .span
564                        .find_ancestor_in_same_ctxt(expr_span)
565                        .map(|scrut_span| scrut_span.shrink_to_hi().with_hi(expr_span.hi())),
566                    hir::MatchSource::Postfix => {
567                        // This is horrendous, and we should deal with it by just
568                        // stashing the span of the braces somewhere (like in the match source).
569                        scrut.span.find_ancestor_in_same_ctxt(expr_span).and_then(|scrut_span| {
570                            let sm = self.tcx.sess.source_map();
571                            let brace_span = sm.span_extend_to_next_char(scrut_span, '{', true);
572                            if sm.span_to_snippet(sm.next_point(brace_span)).as_deref() == Ok("{") {
573                                let sp = brace_span.shrink_to_hi().with_hi(expr_span.hi());
574                                // We also need to extend backwards for whitespace
575                                sm.span_extend_prev_while(sp, |c| c.is_whitespace()).ok()
576                            } else {
577                                None
578                            }
579                        })
580                    }
581                    hir::MatchSource::ForLoopDesugar
582                    | hir::MatchSource::TryDesugar(_)
583                    | hir::MatchSource::AwaitDesugar
584                    | hir::MatchSource::FormatArgs => None,
585                };
586
587                // Check if the match would be exhaustive if all guards were removed.
588                // If so, we leave a note that guards don't count towards exhaustivity.
589                let would_be_exhaustive_without_guards = {
590                    let any_arm_has_guard = tarms.iter().any(|arm| arm.has_guard);
591                    any_arm_has_guard && {
592                        let guardless_arms: Vec<_> =
593                            tarms.iter().map(|arm| MatchArm { has_guard: false, ..*arm }).collect();
594                        rustc_pattern_analysis::rustc::analyze_match(&cx, &guardless_arms, scrut.ty)
595                            .is_ok_and(|report| report.non_exhaustiveness_witnesses.is_empty())
596                    }
597                };
598                self.error = Err(report_non_exhaustive_match(
599                    &cx,
600                    self.thir,
601                    scrut.ty,
602                    scrut.span,
603                    witnesses,
604                    arms,
605                    braces_span,
606                    would_be_exhaustive_without_guards,
607                ));
608            }
609        }
610    }
611
612    {}
#[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("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_build/src/thir/pattern/check_match.rs"),
                                    ::tracing_core::__macro_support::Option::Some(612u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::check_match"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("let_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("let_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("else_keyword_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("else_keyword_span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("let_else_span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("let_else_span");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&let_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&else_keyword_span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&let_else_span)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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