Skip to main content

rustc_mir_build/thir/pattern/
const_to_pat.rs

1use core::ops::ControlFlow;
2
3use rustc_abi::{FieldIdx, VariantIdx};
4use rustc_apfloat::Float;
5use rustc_data_structures::fx::FxHashSet;
6use rustc_errors::{Diag, msg};
7use rustc_hir as hir;
8use rustc_hir::find_attr;
9use rustc_index::Idx;
10use rustc_infer::infer::TyCtxtInferExt;
11use rustc_infer::traits::Obligation;
12use rustc_middle::mir::interpret::ErrorHandled;
13use rustc_middle::span_bug;
14use rustc_middle::thir::{FieldPat, Pat, PatKind};
15use rustc_middle::ty::{
16    self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitableExt, TypeVisitor, Unnormalized,
17};
18use rustc_span::def_id::DefId;
19use rustc_span::{DUMMY_SP, Span};
20use rustc_trait_selection::error_reporting::traits::ambiguity::{
21    CandidateSource, compute_applicable_impls_for_diagnostics,
22};
23use rustc_trait_selection::traits::ObligationCause;
24use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
25use tracing::{debug, instrument, trace};
26
27use super::PatCtxt;
28use crate::diagnostics::{
29    ConstPatternDependsOnGenericParameter, CouldNotEvalConstPattern, InvalidPattern, NaNPattern,
30    PointerPattern, SuggestEq, TypeNotPartialEq, TypeNotStructural, UnionPattern, UnsizedPattern,
31};
32
33impl<'tcx, 'ptcx> PatCtxt<'tcx, 'ptcx> {
34    /// Converts a constant to a pattern (if possible).
35    /// This means aggregate values (like structs and enums) are converted
36    /// to a pattern that matches the value (as if you'd compared via structural equality).
37    ///
38    /// Only type system constants are supported, as we are using valtrees
39    /// as an intermediate step. Unfortunately those don't carry a type
40    /// so we have to carry one ourselves.
41    x;#[instrument(level = "debug", skip(self), ret)]
42    pub(super) fn const_to_pat(
43        &self,
44        c: ty::Const<'tcx>,
45        ty: Ty<'tcx>,
46        id: hir::HirId,
47        span: Span,
48    ) -> Box<Pat<'tcx>> {
49        let mut convert = ConstToPat::new(self, id, span, c);
50
51        match c.kind() {
52            ty::ConstKind::Alias(_, alias_const) => convert.alias_to_pat(alias_const, ty),
53            ty::ConstKind::Value(value) => convert.valtree_to_pat(value),
54            _ => span_bug!(span, "Invalid `ConstKind` for `const_to_pat`: {:?}", c),
55        }
56    }
57}
58
59struct ConstToPat<'tcx> {
60    tcx: TyCtxt<'tcx>,
61    typing_env: ty::TypingEnv<'tcx>,
62    span: Span,
63    id: hir::HirId,
64
65    c: ty::Const<'tcx>,
66}
67
68impl<'tcx> ConstToPat<'tcx> {
69    fn new(pat_ctxt: &PatCtxt<'tcx, '_>, id: hir::HirId, span: Span, c: ty::Const<'tcx>) -> Self {
70        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs:70",
                        "rustc_mir_build::thir::pattern::const_to_pat",
                        ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs"),
                        ::tracing_core::__macro_support::Option::Some(70u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::const_to_pat"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("pat_ctxt.typeck_results.hir_owner")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("pat_ctxt.typeck_results.hir_owner");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pat_ctxt.typeck_results.hir_owner)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!(?pat_ctxt.typeck_results.hir_owner);
71        ConstToPat { tcx: pat_ctxt.tcx, typing_env: pat_ctxt.typing_env, span, id, c }
72    }
73
74    fn type_marked_structural(&self, ty: Ty<'tcx>) -> bool {
75        ty.is_structural_eq_shallow(self.tcx)
76    }
77
78    /// We errored. Signal that in the pattern, so that follow up errors can be silenced.
79    fn mk_err(&self, mut err: Diag<'_>, ty: Ty<'tcx>) -> Box<Pat<'tcx>> {
80        if let ty::ConstKind::Alias(_, alias_const) = self.c.kind() {
81            if let ty::AliasConstKind::Projection { def_id }
82            | ty::AliasConstKind::Inherent { def_id } = alias_const.kind
83                && let Some(def_id) = def_id.as_local()
84            {
85                // Include the container item in the output.
86                err.span_label(self.tcx.def_span(self.tcx.local_parent(def_id)), "");
87            }
88            if let ty::AliasConstKind::Projection { def_id }
89            | ty::AliasConstKind::Inherent { def_id }
90            | ty::AliasConstKind::Free { def_id } = alias_const.kind
91            {
92                err.span_label(self.tcx.def_span(def_id), rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("constant defined here"))msg!("constant defined here"));
93            }
94        }
95        Box::new(Pat { span: self.span, ty, kind: PatKind::Error(err.emit()), extra: None })
96    }
97
98    fn alias_to_pat(&mut self, alias_const: ty::AliasConst<'tcx>, ty: Ty<'tcx>) -> Box<Pat<'tcx>> {
99        // It's not *technically* correct to be revealing opaque types here as borrowcheck has
100        // not run yet. However, CTFE itself uses `TypingMode::PostAnalysis` unconditionally even
101        // during typeck and not doing so has a lot of (undesirable) fallout (#101478, #119821).
102        // As a result we always use a revealed env when resolving the instance to evaluate.
103        //
104        // FIXME: `const_eval_resolve_for_typeck` should probably just modify the env itself
105        // instead of having this logic here
106        let typing_env =
107            self.tcx.erase_and_anonymize_regions(self.typing_env).with_codegen_normalized(self.tcx);
108        let alias_const = self.tcx.erase_and_anonymize_regions(alias_const);
109
110        let mk_too_generic_err = || {
111            let mut err = self
112                .tcx
113                .dcx()
114                .create_err(ConstPatternDependsOnGenericParameter { span: self.span });
115            for arg in alias_const.args {
116                if let ty::GenericArgKind::Type(ty) = arg.kind()
117                    && let ty::Param(param_ty) = ty.kind()
118                {
119                    let def_id = self.tcx.hir_enclosing_body_owner(self.id);
120                    let generics = self.tcx.generics_of(def_id);
121                    let param = generics.type_param(*param_ty, self.tcx);
122                    let span = self.tcx.def_span(param.def_id);
123                    err.span_label(span, "constant depends on this generic parameter");
124                    if let Some(ident) = self.tcx.def_ident_span(def_id)
125                        && self.tcx.sess.source_map().is_multiline(ident.between(span))
126                    {
127                        // Display the `fn` name as well in the diagnostic, as the generic isn't
128                        // in the same line and it could be confusing otherwise.
129                        err.span_label(ident, "");
130                    }
131                }
132            }
133            return self.mk_err(err, ty);
134        };
135
136        // FIXME(gca): This will become insufficient once associated constants can be
137        // implemented as `type` consts (project-const-generics#76). At that point it'll
138        // become necessary to just use type system normalization for all const patterns
139        // but that's not yet possible.
140        let const_value = if alias_const.kind.is_type_const(self.tcx) {
141            let Ok(normalize) = self
142                .tcx
143                .try_normalize_erasing_regions(self.typing_env, Unnormalized::new_wip(self.c))
144            else {
145                let err = self.tcx.dcx().create_err(CouldNotEvalConstPattern { span: self.span });
146                return self.mk_err(err, ty);
147            };
148
149            let ty::ConstKind::Value(value) = normalize.kind() else {
150                let err = self.tcx.dcx().create_err(CouldNotEvalConstPattern { span: self.span });
151                return self.mk_err(err, ty);
152            };
153            value
154        } else {
155            // try to resolve e.g. associated constants to their definition on an impl, and then
156            // evaluate the const.
157            let valtree =
158                match self.tcx.const_eval_resolve_for_typeck(typing_env, alias_const, self.span) {
159                    Ok(Ok(c)) => c,
160                    Err(ErrorHandled::Reported(_, _)) => {
161                        // Let's tell the use where this failing const occurs.
162                        let mut err =
163                            self.tcx.dcx().create_err(CouldNotEvalConstPattern { span: self.span });
164                        // We've emitted an error on the original const, it would be redundant to complain
165                        // on its use as well.
166                        if let ty::ConstKind::Alias(_, alias_const) = self.c.kind()
167                            && let ty::AliasConstKind::Projection { .. }
168                            | ty::AliasConstKind::Inherent { .. }
169                            | ty::AliasConstKind::Free { .. } = alias_const.kind
170                        {
171                            err.downgrade_to_delayed_bug();
172                        }
173                        return self.mk_err(err, ty);
174                    }
175                    Err(ErrorHandled::TooGeneric(_)) => {
176                        return mk_too_generic_err();
177                    }
178                    Ok(Err(bad_ty)) => {
179                        // The pattern cannot be turned into a valtree.
180                        let e = match bad_ty.kind() {
181                            ty::Adt(def, ..) => {
182                                if !def.is_union() {
    ::core::panicking::panic("assertion failed: def.is_union()")
};assert!(def.is_union());
183                                self.tcx.dcx().create_err(UnionPattern { span: self.span })
184                            }
185                            ty::FnPtr(..) | ty::RawPtr(..) => {
186                                self.tcx.dcx().create_err(PointerPattern { span: self.span })
187                            }
188                            _ => self.tcx.dcx().create_err(InvalidPattern {
189                                span: self.span,
190                                non_sm_ty: bad_ty,
191                                prefix: bad_ty.prefix_string(self.tcx).to_string(),
192                            }),
193                        };
194                        return self.mk_err(e, ty);
195                    }
196                };
197
198            // Lower the valtree to a THIR pattern.
199            ty::Value { ty, valtree }
200        };
201        if const_value.ty.has_param() {
202            return mk_too_generic_err();
203        }
204        let mut thir_pat = self.valtree_to_pat(const_value);
205
206        if !thir_pat.references_error() {
207            // Always check for `PartialEq` if we had no other errors yet.
208            if !type_has_partial_eq_impl(self.tcx, typing_env, ty).has_impl {
209                let mut err = self.tcx.dcx().create_err(TypeNotPartialEq { span: self.span, ty });
210                extend_type_not_partial_eq(self.tcx, typing_env, ty, &mut err);
211                return self.mk_err(err, ty);
212            }
213        }
214
215        // Mark the pattern to indicate that it is the result of lowering a named
216        // constant. This is used for diagnostics.
217        thir_pat.extra.get_or_insert_default().expanded_const = alias_const.kind.opt_def_id();
218        thir_pat
219    }
220
221    fn lower_field_values_to_fieldpats(
222        &self,
223        values: impl Iterator<Item = ty::Value<'tcx>>,
224    ) -> Vec<FieldPat<'tcx>> {
225        values
226            .enumerate()
227            .map(|(index, value)| FieldPat {
228                field: FieldIdx::new(index),
229                pattern: *self.valtree_to_pat(value),
230            })
231            .collect()
232    }
233
234    // Recursive helper for `to_pat`; invoke that (instead of calling this directly).
235    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::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("valtree_to_pat",
                                    "rustc_mir_build::thir::pattern::const_to_pat",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs"),
                                    ::tracing_core::__macro_support::Option::Some(235u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::const_to_pat"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("value")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("value");
                                                        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::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::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(&value)
                                                            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: Box<Pat<'tcx>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let span = self.span;
            let tcx = self.tcx;
            let ty::Value { ty, valtree } = value;
            let kind =
                match ty.kind() {
                    ty::Adt(adt_def, _) if !self.type_marked_structural(ty) => {
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs:247",
                                                "rustc_mir_build::thir::pattern::const_to_pat",
                                                ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs"),
                                                ::tracing_core::__macro_support::Option::Some(247u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::const_to_pat"),
                                                ::tracing_core::field::FieldSet::new(&["message",
                                                                {
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("adt_def")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("adt_def");
                                                                    NAME.as_str()
                                                                },
                                                                {
                                                                    const NAME:
                                                                        ::tracing::__macro_support::FieldName<{
                                                                            ::tracing::__macro_support::FieldName::len("value.ty")
                                                                        }> =
                                                                        ::tracing::__macro_support::FieldName::new("value.ty");
                                                                    NAME.as_str()
                                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("ADT type in pattern is not `type_marked_structural`")
                                                                    as &dyn ::tracing::field::Value)),
                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&adt_def)
                                                                    as &dyn ::tracing::field::Value)),
                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&value.ty)
                                                                    as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        let PartialEqImplStatus {
                                is_derived,
                                possibly_inapplicable_structural_partial_eq,
                                non_blanket_impl,
                                possibly_inapplicable_derived_partial_eq,
                                has_impl, .. } =
                            type_has_partial_eq_impl(self.tcx, self.typing_env, ty);
                        if possibly_inapplicable_derived_partial_eq && !has_impl {
                            let mut err =
                                self.tcx.dcx().create_err(TypeNotPartialEq {
                                        span: self.span,
                                        ty,
                                    });
                            extend_type_not_partial_eq(self.tcx, self.typing_env, ty,
                                &mut err);
                            return self.mk_err(err, ty);
                        }
                        let (manual_partialeq_impl_span,
                                manual_partialeq_impl_note) =
                            match (possibly_inapplicable_structural_partial_eq,
                                    non_blanket_impl) {
                                (true, _) => (None, false),
                                (_, Some(def_id)) if def_id.is_local() && !is_derived => {
                                    (Some(tcx.def_span(def_id)), false)
                                }
                                _ => (None, true),
                            };
                        let manual_partialeq_impl =
                            manual_partialeq_impl_note ||
                                manual_partialeq_impl_span.is_some();
                        let is_local = adt_def.did().is_local();
                        let ty_def_span = tcx.def_span(adt_def.did());
                        let suggestion =
                            if let Ok(name) =
                                        tcx.sess.source_map().span_to_snippet(self.span) &&
                                    (is_local || manual_partialeq_impl) {
                                let mut hir_id = self.id;
                                while let hir::Node::Pat(pat) = tcx.parent_hir_node(hir_id)
                                    {
                                    hir_id = pat.hir_id;
                                }
                                match tcx.parent_hir_node(hir_id) {
                                    hir::Node::Arm(hir::Arm { pat, guard: None, .. }) => {
                                        Some(SuggestEq::AddIf {
                                                if_span: pat.span.shrink_to_hi(),
                                                pat_span: self.span,
                                                name,
                                                ty,
                                                manual_partialeq_impl,
                                            })
                                    }
                                    hir::Node::Arm(hir::Arm { guard: Some(guard), .. }) => {
                                        Some(SuggestEq::AddToIf {
                                                span: guard.span.shrink_to_hi(),
                                                pat_span: self.span,
                                                name,
                                                ty,
                                                manual_partialeq_impl,
                                            })
                                    }
                                    hir::Node::Expr(hir::Expr {
                                        kind: hir::ExprKind::Let(let_expr), span, .. }) => {
                                        if let_expr.pat.span == self.span {
                                            Some(SuggestEq::ReplaceWithEq {
                                                    removal: span.until(self.span),
                                                    eq: self.span.between(let_expr.init.span),
                                                    ty,
                                                    manual_partialeq_impl,
                                                })
                                        } else if tcx.sess.edition().at_least_rust_2024() {
                                            Some(SuggestEq::AddToLetChain {
                                                    span: span.shrink_to_hi(),
                                                    pat_span: self.span,
                                                    name,
                                                    ty,
                                                    manual_partialeq_impl,
                                                })
                                        } else { None }
                                    }
                                    hir::Node::LetStmt(let_stmt) if
                                        let Some(init) = let_stmt.init &&
                                                    let Some(els) = let_stmt.els && init.span.ctxt().is_root()
                                            && els.span.ctxt().is_root() => {
                                        Some(SuggestEq::ReplaceLetElseWithIf {
                                                if_span: let_stmt.span.until(let_stmt.pat.span),
                                                eq: let_stmt.pat.span.between(init.span),
                                                else_span: init.span.between(els.span),
                                                ty,
                                                manual_partialeq_impl,
                                            })
                                    }
                                    _ => None,
                                }
                            } else { None };
                        let err =
                            TypeNotStructural {
                                span,
                                ty,
                                ty_def_span,
                                manual_partialeq_impl_span,
                                manual_partialeq_impl_note,
                                is_local,
                                suggestion,
                            };
                        return self.mk_err(tcx.dcx().create_err(err), ty);
                    }
                    ty::Adt(adt_def, args) if adt_def.is_enum() => {
                        let (&variant_index, fields) =
                            valtree.to_branch().split_first().unwrap();
                        let variant_index =
                            VariantIdx::from_u32(variant_index.to_leaf().to_u32());
                        PatKind::Variant {
                            adt_def: *adt_def,
                            args,
                            variant_index,
                            subpatterns: self.lower_field_values_to_fieldpats(fields.iter().map(|ct|
                                        ct.to_value())),
                        }
                    }
                    ty::Adt(def, _) => {
                        if !!def.is_union() {
                            ::core::panicking::panic("assertion failed: !def.is_union()")
                        };
                        PatKind::Leaf {
                            subpatterns: self.lower_field_values_to_fieldpats(valtree.to_branch().iter().map(|ct|
                                        ct.to_value())),
                        }
                    }
                    ty::Tuple(_) =>
                        PatKind::Leaf {
                            subpatterns: self.lower_field_values_to_fieldpats(valtree.to_branch().iter().map(|ct|
                                        ct.to_value())),
                        },
                    ty::Slice(_) =>
                        PatKind::Slice {
                            prefix: valtree.to_branch().iter().map(|val|
                                        *self.valtree_to_pat(val.to_value())).collect(),
                            slice: None,
                            suffix: Box::new([]),
                        },
                    ty::Array(_, _) =>
                        PatKind::Array {
                            prefix: valtree.to_branch().iter().map(|val|
                                        *self.valtree_to_pat(val.to_value())).collect(),
                            slice: None,
                            suffix: Box::new([]),
                        },
                    ty::Str => { PatKind::Constant { value } }
                    ty::Ref(_, pointee_ty, ..) => {
                        if pointee_ty.is_str() || pointee_ty.is_slice() ||
                                pointee_ty.is_sized(tcx, self.typing_env) {
                            PatKind::Deref {
                                pin: hir::Pinnedness::Not,
                                subpattern: self.valtree_to_pat(ty::Value {
                                        ty: *pointee_ty,
                                        valtree,
                                    }),
                            }
                        } else {
                            return self.mk_err(tcx.dcx().create_err(UnsizedPattern {
                                            span,
                                            non_sm_ty: *pointee_ty,
                                        }), ty);
                        }
                    }
                    ty::Float(flt) => {
                        let v = valtree.to_leaf();
                        let is_nan =
                            match flt {
                                ty::FloatTy::F16 => v.to_f16().is_nan(),
                                ty::FloatTy::F32 => v.to_f32().is_nan(),
                                ty::FloatTy::F64 => v.to_f64().is_nan(),
                                ty::FloatTy::F128 => v.to_f128().is_nan(),
                            };
                        if is_nan {
                            return self.mk_err(tcx.dcx().create_err(NaNPattern {
                                            span,
                                        }), ty);
                        } else { PatKind::Constant { value } }
                    }
                    ty::Pat(..) | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_)
                        | ty::RawPtr(..) => {
                        PatKind::Constant { value }
                    }
                    ty::FnPtr(..) => {
                        {
                            ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
                                    format_args!("Valtree construction would never succeed for FnPtr, so this is unreachable.")));
                        }
                    }
                    _ => {
                        let err =
                            InvalidPattern {
                                span,
                                non_sm_ty: ty,
                                prefix: ty.prefix_string(tcx).to_string(),
                            };
                        return self.mk_err(tcx.dcx().create_err(err), ty);
                    }
                };
            Box::new(Pat { span, ty, kind, extra: None })
        }
    }
}#[instrument(skip(self), level = "debug")]
236    fn valtree_to_pat(&self, value: ty::Value<'tcx>) -> Box<Pat<'tcx>> {
237        let span = self.span;
238        let tcx = self.tcx;
239        let ty::Value { ty, valtree } = value;
240
241        let kind = match ty.kind() {
242            // Extremely important check for all ADTs!
243            // Make sure they are eligible to be used in patterns (structural), and if not, emit an
244            // error.
245            ty::Adt(adt_def, _) if !self.type_marked_structural(ty) => {
246                // This ADT cannot be used as a constant in patterns.
247                debug!(?adt_def, ?value.ty, "ADT type in pattern is not `type_marked_structural`");
248                let PartialEqImplStatus {
249                    is_derived,
250                    possibly_inapplicable_structural_partial_eq,
251                    non_blanket_impl,
252                    possibly_inapplicable_derived_partial_eq,
253                    has_impl,
254                    ..
255                } = type_has_partial_eq_impl(self.tcx, self.typing_env, ty);
256
257                // If we have a derived PartialEq impl but it does not apply,
258                // then error about that instead, because `TypeNotStructural` gives advice that is
259                // relevant only when the problem is that `ty` does not derive `PartialEq`.
260                //
261                // Note that this is a duplicate of a check in `alias_to_pat()`,
262                // which we would run later if we weren’t emitting an error now.
263                if possibly_inapplicable_derived_partial_eq && !has_impl {
264                    let mut err =
265                        self.tcx.dcx().create_err(TypeNotPartialEq { span: self.span, ty });
266                    extend_type_not_partial_eq(self.tcx, self.typing_env, ty, &mut err);
267                    return self.mk_err(err, ty);
268                }
269
270                let (manual_partialeq_impl_span, manual_partialeq_impl_note) =
271                    match (possibly_inapplicable_structural_partial_eq, non_blanket_impl) {
272                        (true, _) => (None, false),
273                        (_, Some(def_id)) if def_id.is_local() && !is_derived => {
274                            (Some(tcx.def_span(def_id)), false)
275                        }
276                        _ => (None, true),
277                    };
278                let manual_partialeq_impl =
279                    manual_partialeq_impl_note || manual_partialeq_impl_span.is_some();
280                let is_local = adt_def.did().is_local();
281                let ty_def_span = tcx.def_span(adt_def.did());
282                let suggestion = if let Ok(name) = tcx.sess.source_map().span_to_snippet(self.span)
283                    && (is_local || manual_partialeq_impl)
284                {
285                    let mut hir_id = self.id;
286                    while let hir::Node::Pat(pat) = tcx.parent_hir_node(hir_id) {
287                        hir_id = pat.hir_id;
288                    }
289                    match tcx.parent_hir_node(hir_id) {
290                        hir::Node::Arm(hir::Arm { pat, guard: None, .. }) => {
291                            // Add an if condition to the match arm.
292                            Some(SuggestEq::AddIf {
293                                if_span: pat.span.shrink_to_hi(),
294                                pat_span: self.span,
295                                name,
296                                ty,
297                                manual_partialeq_impl,
298                            })
299                        }
300                        hir::Node::Arm(hir::Arm { guard: Some(guard), .. }) => {
301                            // Modify the the match arm if condition and add a check for equality.
302                            Some(SuggestEq::AddToIf {
303                                span: guard.span.shrink_to_hi(),
304                                pat_span: self.span,
305                                name,
306                                ty,
307                                manual_partialeq_impl,
308                            })
309                        }
310                        hir::Node::Expr(hir::Expr {
311                            kind: hir::ExprKind::Let(let_expr),
312                            span,
313                            ..
314                        }) => {
315                            if let_expr.pat.span == self.span {
316                                // `if let CONST = expr` -> `if CONST == expr`.
317                                Some(SuggestEq::ReplaceWithEq {
318                                    removal: span.until(self.span),
319                                    eq: self.span.between(let_expr.init.span),
320                                    ty,
321                                    manual_partialeq_impl,
322                                })
323                            } else if tcx.sess.edition().at_least_rust_2024() {
324                                // `if let Some(CONST) = expr` ->
325                                // `if let Some(binding) = expr && binding == CONST`.
326                                Some(SuggestEq::AddToLetChain {
327                                    span: span.shrink_to_hi(),
328                                    pat_span: self.span,
329                                    name,
330                                    ty,
331                                    manual_partialeq_impl,
332                                })
333                            } else {
334                                None
335                            }
336                        }
337                        hir::Node::LetStmt(let_stmt)
338                            if let Some(init) = let_stmt.init
339                                && let Some(els) = let_stmt.els
340                                && init.span.ctxt().is_root()
341                                && els.span.ctxt().is_root() =>
342                        {
343                            // `let PAT = expr else {` -> `if PAT == expr {`.
344                            Some(SuggestEq::ReplaceLetElseWithIf {
345                                if_span: let_stmt.span.until(let_stmt.pat.span),
346                                eq: let_stmt.pat.span.between(init.span),
347                                else_span: init.span.between(els.span),
348                                ty,
349                                manual_partialeq_impl,
350                            })
351                        }
352                        _ => None,
353                    }
354                } else {
355                    None
356                };
357                let err = TypeNotStructural {
358                    span,
359                    ty,
360                    ty_def_span,
361                    manual_partialeq_impl_span,
362                    manual_partialeq_impl_note,
363                    is_local,
364                    suggestion,
365                };
366                return self.mk_err(tcx.dcx().create_err(err), ty);
367            }
368            ty::Adt(adt_def, args) if adt_def.is_enum() => {
369                let (&variant_index, fields) = valtree.to_branch().split_first().unwrap();
370                let variant_index = VariantIdx::from_u32(variant_index.to_leaf().to_u32());
371                PatKind::Variant {
372                    adt_def: *adt_def,
373                    args,
374                    variant_index,
375                    subpatterns: self
376                        .lower_field_values_to_fieldpats(fields.iter().map(|ct| ct.to_value())),
377                }
378            }
379            ty::Adt(def, _) => {
380                assert!(!def.is_union()); // Valtree construction would never succeed for unions.
381                PatKind::Leaf {
382                    subpatterns: self.lower_field_values_to_fieldpats(
383                        valtree.to_branch().iter().map(|ct| ct.to_value()),
384                    ),
385                }
386            }
387            ty::Tuple(_) => PatKind::Leaf {
388                subpatterns: self.lower_field_values_to_fieldpats(
389                    valtree.to_branch().iter().map(|ct| ct.to_value()),
390                ),
391            },
392            ty::Slice(_) => PatKind::Slice {
393                prefix: valtree
394                    .to_branch()
395                    .iter()
396                    .map(|val| *self.valtree_to_pat(val.to_value()))
397                    .collect(),
398                slice: None,
399                suffix: Box::new([]),
400            },
401            ty::Array(_, _) => PatKind::Array {
402                prefix: valtree
403                    .to_branch()
404                    .iter()
405                    .map(|val| *self.valtree_to_pat(val.to_value()))
406                    .collect(),
407                slice: None,
408                suffix: Box::new([]),
409            },
410            ty::Str => {
411                // Constant/literal patterns of type `&str` are lowered to a
412                // `PatKind::Deref` wrapping a `PatKind::Constant` of type `str`.
413                // This pattern node is the `str` constant part.
414                //
415                // Under `feature(deref_patterns)`, string literal patterns can also
416                // have type `str` directly, without the `&`, in order to allow things
417                // like `deref!("...")` to work when the scrutinee is `String`.
418                PatKind::Constant { value }
419            }
420            ty::Ref(_, pointee_ty, ..) => {
421                if pointee_ty.is_str()
422                    || pointee_ty.is_slice()
423                    || pointee_ty.is_sized(tcx, self.typing_env)
424                {
425                    PatKind::Deref {
426                        // This node has type `ty::Ref`, so it's not a pin-deref.
427                        pin: hir::Pinnedness::Not,
428                        // Lower the valtree to a pattern as the pointee type.
429                        // This works because references have the same valtree
430                        // representation as their pointee.
431                        subpattern: self.valtree_to_pat(ty::Value { ty: *pointee_ty, valtree }),
432                    }
433                } else {
434                    return self.mk_err(
435                        tcx.dcx().create_err(UnsizedPattern { span, non_sm_ty: *pointee_ty }),
436                        ty,
437                    );
438                }
439            }
440            ty::Float(flt) => {
441                let v = valtree.to_leaf();
442                let is_nan = match flt {
443                    ty::FloatTy::F16 => v.to_f16().is_nan(),
444                    ty::FloatTy::F32 => v.to_f32().is_nan(),
445                    ty::FloatTy::F64 => v.to_f64().is_nan(),
446                    ty::FloatTy::F128 => v.to_f128().is_nan(),
447                };
448                if is_nan {
449                    // NaNs are not ever equal to anything so they make no sense as patterns.
450                    // Also see <https://github.com/rust-lang/rfcs/pull/3535>.
451                    return self.mk_err(tcx.dcx().create_err(NaNPattern { span }), ty);
452                } else {
453                    PatKind::Constant { value }
454                }
455            }
456            ty::Pat(..) | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::RawPtr(..) => {
457                // The raw pointers we see here have been "vetted" by valtree construction to be
458                // just integers, so we simply allow them.
459                PatKind::Constant { value }
460            }
461            ty::FnPtr(..) => {
462                unreachable!(
463                    "Valtree construction would never succeed for FnPtr, so this is unreachable."
464                )
465            }
466            _ => {
467                let err = InvalidPattern {
468                    span,
469                    non_sm_ty: ty,
470                    prefix: ty.prefix_string(tcx).to_string(),
471                };
472                return self.mk_err(tcx.dcx().create_err(err), ty);
473            }
474        };
475
476        Box::new(Pat { span, ty, kind, extra: None })
477    }
478}
479
480/// Given a type with type parameters, visit every ADT looking for types that need to
481/// `#[derive(PartialEq)]` for it to be a structural type.
482fn extend_type_not_partial_eq<'tcx>(
483    tcx: TyCtxt<'tcx>,
484    typing_env: ty::TypingEnv<'tcx>,
485    ty: Ty<'tcx>,
486    err: &mut Diag<'_>,
487) {
488    /// Collect all types that need to be `StructuralPartialEq`.
489    struct UsedParamsNeedInstantiationVisitor<'tcx> {
490        tcx: TyCtxt<'tcx>,
491        typing_env: ty::TypingEnv<'tcx>,
492        /// The user has written `impl PartialEq for Ty` which means it's non-structural.
493        adts_with_manual_partialeq: FxHashSet<Span>,
494        /// The type has no `PartialEq` implementation, neither manual or derived.
495        adts_without_partialeq: FxHashSet<Span>,
496        /// The user has written `impl PartialEq for Ty` which means it's non-structural,
497        /// but we don't have a span to point at, so we'll just add them as a `note`.
498        manual: FxHashSet<Ty<'tcx>>,
499        /// The type has no `PartialEq` implementation, neither manual or derived, but
500        /// we don't have a span to point at, so we'll just add them as a `note`.
501        without: FxHashSet<Ty<'tcx>>,
502    }
503
504    impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for UsedParamsNeedInstantiationVisitor<'tcx> {
505        type Result = ControlFlow<()>;
506        fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
507            match ty.kind() {
508                ty::Dynamic(..) => return ControlFlow::Break(()),
509                // Unsafe binders never implement `PartialEq`, so avoid walking into them
510                // which would require instantiating its binder with placeholders too.
511                ty::UnsafeBinder(..) => return ControlFlow::Break(()),
512                ty::FnPtr(..) => return ControlFlow::Continue(()),
513                ty::Adt(def, _args) => {
514                    let ty_def_id = def.did();
515                    let ty_def_span = self.tcx.def_span(ty_def_id);
516                    let PartialEqImplStatus {
517                        has_impl,
518                        is_derived,
519                        possibly_inapplicable_structural_partial_eq: structural_partial_eq,
520                        non_blanket_impl,
521                        possibly_inapplicable_derived_partial_eq: _,
522                    } = type_has_partial_eq_impl(self.tcx, self.typing_env, ty);
523                    match (has_impl, is_derived, structural_partial_eq, non_blanket_impl) {
524                        (_, _, true, _) => {}
525                        (true, false, _, Some(def_id)) if def_id.is_local() => {
526                            self.adts_with_manual_partialeq.insert(self.tcx.def_span(def_id));
527                        }
528                        (true, false, _, _) if ty_def_id.is_local() => {
529                            self.adts_with_manual_partialeq.insert(ty_def_span);
530                        }
531                        (false, _, _, _) if ty_def_id.is_local() => {
532                            self.adts_without_partialeq.insert(ty_def_span);
533                        }
534                        (true, false, _, _) => {
535                            self.manual.insert(ty);
536                        }
537                        (false, _, _, _) => {
538                            self.without.insert(ty);
539                        }
540                        _ => {}
541                    };
542                    ty.super_visit_with(self)
543                }
544                _ => ty.super_visit_with(self),
545            }
546        }
547    }
548    let mut v = UsedParamsNeedInstantiationVisitor {
549        tcx,
550        typing_env,
551        adts_with_manual_partialeq: FxHashSet::default(),
552        adts_without_partialeq: FxHashSet::default(),
553        manual: FxHashSet::default(),
554        without: FxHashSet::default(),
555    };
556    if v.visit_ty(ty).is_break() {
557        return;
558    }
559    #[allow(rustc::potential_query_instability)] // Span labels will be sorted by the rendering
560    for span in v.adts_with_manual_partialeq {
561        err.span_note(span, "the `PartialEq` trait must be derived, manual `impl`s are not sufficient; see https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html for details");
562    }
563    #[allow(rustc::potential_query_instability)] // Span labels will be sorted by the rendering
564    for span in v.adts_without_partialeq {
565        err.span_label(
566            span,
567            "must be annotated with `#[derive(PartialEq)]` to be usable in patterns",
568        );
569    }
570    #[allow(rustc::potential_query_instability)]
571    let mut manual: Vec<_> = v.manual.into_iter().map(|t| t.to_string()).collect();
572    manual.sort();
573    for ty in manual {
574        err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` must be annotated with `#[derive(PartialEq)]` to be usable in patterns, manual `impl`s are not sufficient; see https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html for details",
                ty))
    })format!(
575            "`{ty}` must be annotated with `#[derive(PartialEq)]` to be usable in patterns, manual `impl`s are not sufficient; see https://doc.rust-lang.org/stable/std/marker/trait.StructuralPartialEq.html for details"
576        ));
577    }
578    #[allow(rustc::potential_query_instability)]
579    let mut without: Vec<_> = v.without.into_iter().map(|t| t.to_string()).collect();
580    without.sort();
581    for ty in without {
582        err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` must be annotated with `#[derive(PartialEq)]` to be usable in patterns",
                ty))
    })format!(
583            "`{ty}` must be annotated with `#[derive(PartialEq)]` to be usable in patterns"
584        ));
585    }
586}
587
588#[derive(#[automatically_derived]
impl ::core::fmt::Debug for PartialEqImplStatus {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field5_finish(f,
            "PartialEqImplStatus", "has_impl", &self.has_impl, "is_derived",
            &self.is_derived, "non_blanket_impl", &self.non_blanket_impl,
            "possibly_inapplicable_structural_partial_eq",
            &self.possibly_inapplicable_structural_partial_eq,
            "possibly_inapplicable_derived_partial_eq",
            &&self.possibly_inapplicable_derived_partial_eq)
    }
}Debug)]
589struct PartialEqImplStatus {
590    /// There is a `PartialEq` impl that applies to the type.
591    has_impl: bool,
592
593    /// The `PartialEq` impl is `#[automatically_derived]`.
594    is_derived: bool,
595    /// The `DefId` of the same impl that `is_derived` refers to.
596    non_blanket_impl: Option<DefId>,
597
598    /// If true, there is a `StructuralPartialEq` implementation,
599    /// but its bounds might not be satisfied.
600    possibly_inapplicable_structural_partial_eq: bool,
601    /// If true, there is a derived `PartialEq` implementation for the type,
602    /// but its bounds might not be satisfied.
603    possibly_inapplicable_derived_partial_eq: bool,
604}
605
606x;#[instrument(level = "trace", skip(tcx), ret)]
607fn type_has_partial_eq_impl<'tcx>(
608    tcx: TyCtxt<'tcx>,
609    typing_env: ty::TypingEnv<'tcx>,
610    ty: Ty<'tcx>,
611) -> PartialEqImplStatus {
612    let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
613    // double-check there even *is* a semantic `PartialEq` to dispatch to.
614    //
615    // (If there isn't, then we can safely issue a hard
616    // error, because that's never worked, due to compiler
617    // using `PartialEq::eq` in this scenario in the past.)
618    let partial_eq_trait_id = tcx.require_lang_item(hir::LangItem::PartialEq, DUMMY_SP);
619    let structural_partial_eq_trait_id =
620        tcx.require_lang_item(hir::LangItem::StructuralPeq, DUMMY_SP);
621
622    // This *could* accept a type that isn't actually `PartialEq`, because region bounds get
623    // ignored. However that should be pretty much impossible since consts that do not depend on
624    // generics can only mention the `'static` lifetime, and how would one have a type that's
625    // `PartialEq` for some lifetime but *not* for `'static`? If this ever becomes a problem
626    // we'll need to leave some sort of trace of this requirement in the MIR so that borrowck
627    // can ensure that the type really implements `PartialEq`.
628    // We also do *not* require `const PartialEq`, not even in `const fn`. This violates the model
629    // that patterns can only do things that the code could also do without patterns, but it is
630    // needed for backwards compatibility. The actual pattern matching compares primitive values,
631    // `PartialEq::eq` never gets invoked, so there's no risk of us running non-const code.
632    let has_impl = {
633        let obligation = Obligation::new(
634            tcx,
635            ObligationCause::dummy(),
636            param_env,
637            ty::TraitRef::new(tcx, partial_eq_trait_id, [ty, ty]),
638        );
639        infcx.predicate_must_hold_modulo_regions(&obligation)
640    };
641
642    // Determine whether there are is a derived `PartialEq` implementation, whether or not its
643    // bounds are met.
644    let possibly_inapplicable_derived_partial_eq = {
645        let obligation = Obligation::new(
646            tcx,
647            ObligationCause::dummy(),
648            param_env,
649            ty::Binder::dummy(ty::TraitRef::new(tcx, partial_eq_trait_id, [ty, ty])),
650        );
651        compute_applicable_impls_for_diagnostics(&infcx, &obligation, true).iter().any(
652            |candidate_source| {
653                matches!(
654                    candidate_source,
655                    &CandidateSource::DefId(def_id)
656                    if find_attr!(tcx, def_id, AutomaticallyDerived)
657                )
658            },
659        )
660    };
661
662    let possibly_inapplicable_structural_partial_eq = {
663        let obligation = Obligation::new(
664            tcx,
665            ObligationCause::dummy(),
666            param_env,
667            ty::Binder::dummy(ty::TraitRef::new(tcx, structural_partial_eq_trait_id, [ty])),
668        );
669        compute_applicable_impls_for_diagnostics(&infcx, &obligation, true)
670            .iter()
671            .any(|candidate_source| matches!(candidate_source, CandidateSource::DefId(_)))
672    };
673
674    let mut automatically_derived = false;
675    let mut impl_def_id = None;
676    for def_id in tcx.non_blanket_impls_for_ty(partial_eq_trait_id, ty) {
677        automatically_derived = find_attr!(tcx, def_id, AutomaticallyDerived);
678        impl_def_id = Some(def_id);
679    }
680
681    PartialEqImplStatus {
682        has_impl,
683        is_derived: automatically_derived,
684        possibly_inapplicable_structural_partial_eq,
685        non_blanket_impl: impl_def_id,
686        possibly_inapplicable_derived_partial_eq,
687    }
688}