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