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::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitableExt, TypeVisitor};
16use rustc_span::def_id::DefId;
17use rustc_span::{DUMMY_SP, Span};
18use rustc_trait_selection::traits::ObligationCause;
19use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
20use tracing::{debug, instrument, trace};
21
22use super::PatCtxt;
23use crate::errors::{
24    ConstPatternDependsOnGenericParameter, CouldNotEvalConstPattern, InvalidPattern, NaNPattern,
25    PointerPattern, SuggestEq, TypeNotPartialEq, TypeNotStructural, UnionPattern, UnsizedPattern,
26};
27
28impl<'tcx, 'ptcx> PatCtxt<'tcx, 'ptcx> {
29    /// Converts a constant to a pattern (if possible).
30    /// This means aggregate values (like structs and enums) are converted
31    /// to a pattern that matches the value (as if you'd compared via structural equality).
32    ///
33    /// Only type system constants are supported, as we are using valtrees
34    /// as an intermediate step. Unfortunately those don't carry a type
35    /// so we have to carry one ourselves.
36    x;#[instrument(level = "debug", skip(self), ret)]
37    pub(super) fn const_to_pat(
38        &self,
39        c: ty::Const<'tcx>,
40        ty: Ty<'tcx>,
41        id: hir::HirId,
42        span: Span,
43    ) -> Box<Pat<'tcx>> {
44        let mut convert = ConstToPat::new(self, id, span, c);
45
46        match c.kind() {
47            ty::ConstKind::Unevaluated(uv) => convert.unevaluated_to_pat(uv, ty),
48            ty::ConstKind::Value(value) => convert.valtree_to_pat(value),
49            _ => span_bug!(span, "Invalid `ConstKind` for `const_to_pat`: {:?}", c),
50        }
51    }
52}
53
54struct ConstToPat<'tcx> {
55    tcx: TyCtxt<'tcx>,
56    typing_env: ty::TypingEnv<'tcx>,
57    span: Span,
58    id: hir::HirId,
59
60    c: ty::Const<'tcx>,
61}
62
63impl<'tcx> ConstToPat<'tcx> {
64    fn new(pat_ctxt: &PatCtxt<'tcx, '_>, id: hir::HirId, span: Span, c: ty::Const<'tcx>) -> Self {
65        {
    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:65",
                        "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(65u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::const_to_pat"),
                        ::tracing_core::field::FieldSet::new(&["pat_ctxt.typeck_results.hir_owner"],
                            ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&pat_ctxt.typeck_results.hir_owner)
                                            as &dyn Value))])
            });
    } else { ; }
};trace!(?pat_ctxt.typeck_results.hir_owner);
66        ConstToPat { tcx: pat_ctxt.tcx, typing_env: pat_ctxt.typing_env, span, id, c }
67    }
68
69    fn type_marked_structural(&self, ty: Ty<'tcx>) -> bool {
70        ty.is_structural_eq_shallow(self.tcx)
71    }
72
73    /// We errored. Signal that in the pattern, so that follow up errors can be silenced.
74    fn mk_err(&self, mut err: Diag<'_>, ty: Ty<'tcx>) -> Box<Pat<'tcx>> {
75        if let ty::ConstKind::Unevaluated(uv) = self.c.kind() {
76            let def_kind = self.tcx.def_kind(uv.def);
77            if let hir::def::DefKind::AssocConst { .. } = def_kind
78                && let Some(def_id) = uv.def.as_local()
79            {
80                // Include the container item in the output.
81                err.span_label(self.tcx.def_span(self.tcx.local_parent(def_id)), "");
82            }
83            if let hir::def::DefKind::Const { .. } | hir::def::DefKind::AssocConst { .. } = def_kind
84            {
85                err.span_label(self.tcx.def_span(uv.def), rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("constant defined here"))msg!("constant defined here"));
86            }
87        }
88        Box::new(Pat { span: self.span, ty, kind: PatKind::Error(err.emit()), extra: None })
89    }
90
91    fn unevaluated_to_pat(
92        &mut self,
93        uv: ty::UnevaluatedConst<'tcx>,
94        ty: Ty<'tcx>,
95    ) -> Box<Pat<'tcx>> {
96        // It's not *technically* correct to be revealing opaque types here as borrowcheck has
97        // not run yet. However, CTFE itself uses `TypingMode::PostAnalysis` unconditionally even
98        // during typeck and not doing so has a lot of (undesirable) fallout (#101478, #119821).
99        // As a result we always use a revealed env when resolving the instance to evaluate.
100        //
101        // FIXME: `const_eval_resolve_for_typeck` should probably just modify the env itself
102        // instead of having this logic here
103        let typing_env = self
104            .tcx
105            .erase_and_anonymize_regions(self.typing_env)
106            .with_post_analysis_normalized(self.tcx);
107        let uv = self.tcx.erase_and_anonymize_regions(uv);
108
109        // try to resolve e.g. associated constants to their definition on an impl, and then
110        // evaluate the const.
111        let valtree = match self.tcx.const_eval_resolve_for_typeck(typing_env, uv, self.span) {
112            Ok(Ok(c)) => c,
113            Err(ErrorHandled::Reported(_, _)) => {
114                // Let's tell the use where this failing const occurs.
115                let mut err =
116                    self.tcx.dcx().create_err(CouldNotEvalConstPattern { span: self.span });
117                // We've emitted an error on the original const, it would be redundant to complain
118                // on its use as well.
119                if let ty::ConstKind::Unevaluated(uv) = self.c.kind()
120                    && let hir::def::DefKind::Const { .. } | hir::def::DefKind::AssocConst { .. } =
121                        self.tcx.def_kind(uv.def)
122                {
123                    err.downgrade_to_delayed_bug();
124                }
125                return self.mk_err(err, ty);
126            }
127            Err(ErrorHandled::TooGeneric(_)) => {
128                let mut e = self
129                    .tcx
130                    .dcx()
131                    .create_err(ConstPatternDependsOnGenericParameter { span: self.span });
132                for arg in uv.args {
133                    if let ty::GenericArgKind::Type(ty) = arg.kind()
134                        && let ty::Param(param_ty) = ty.kind()
135                    {
136                        let def_id = self.tcx.hir_enclosing_body_owner(self.id);
137                        let generics = self.tcx.generics_of(def_id);
138                        let param = generics.type_param(*param_ty, self.tcx);
139                        let span = self.tcx.def_span(param.def_id);
140                        e.span_label(span, "constant depends on this generic parameter");
141                        if let Some(ident) = self.tcx.def_ident_span(def_id)
142                            && self.tcx.sess.source_map().is_multiline(ident.between(span))
143                        {
144                            // Display the `fn` name as well in the diagnostic, as the generic isn't
145                            // in the same line and it could be confusing otherwise.
146                            e.span_label(ident, "");
147                        }
148                    }
149                }
150                return self.mk_err(e, ty);
151            }
152            Ok(Err(bad_ty)) => {
153                // The pattern cannot be turned into a valtree.
154                let e = match bad_ty.kind() {
155                    ty::Adt(def, ..) => {
156                        if !def.is_union() {
    ::core::panicking::panic("assertion failed: def.is_union()")
};assert!(def.is_union());
157                        self.tcx.dcx().create_err(UnionPattern { span: self.span })
158                    }
159                    ty::FnPtr(..) | ty::RawPtr(..) => {
160                        self.tcx.dcx().create_err(PointerPattern { span: self.span })
161                    }
162                    _ => self.tcx.dcx().create_err(InvalidPattern {
163                        span: self.span,
164                        non_sm_ty: bad_ty,
165                        prefix: bad_ty.prefix_string(self.tcx).to_string(),
166                    }),
167                };
168                return self.mk_err(e, ty);
169            }
170        };
171
172        // Lower the valtree to a THIR pattern.
173        let mut thir_pat = self.valtree_to_pat(ty::Value { ty, valtree });
174
175        if !thir_pat.references_error() {
176            // Always check for `PartialEq` if we had no other errors yet.
177            if !type_has_partial_eq_impl(self.tcx, typing_env, ty).has_impl {
178                let mut err = self.tcx.dcx().create_err(TypeNotPartialEq { span: self.span, ty });
179                extend_type_not_partial_eq(self.tcx, typing_env, ty, &mut err);
180                return self.mk_err(err, ty);
181            }
182        }
183
184        // Mark the pattern to indicate that it is the result of lowering a named
185        // constant. This is used for diagnostics.
186        thir_pat.extra.get_or_insert_default().expanded_const = Some(uv.def);
187        thir_pat
188    }
189
190    fn lower_field_values_to_fieldpats(
191        &self,
192        values: impl Iterator<Item = ty::Value<'tcx>>,
193    ) -> Vec<FieldPat<'tcx>> {
194        values
195            .enumerate()
196            .map(|(index, value)| FieldPat {
197                field: FieldIdx::new(index),
198                pattern: *self.valtree_to_pat(value),
199            })
200            .collect()
201    }
202
203    // Recursive helper for `to_pat`; invoke that (instead of calling this directly).
204    #[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(204u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::const_to_pat"),
                                    ::tracing_core::field::FieldSet::new(&["value"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&value)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: 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:215",
                                                "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(215u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_mir_build::thir::pattern::const_to_pat"),
                                                ::tracing_core::field::FieldSet::new(&["message", "adt_def",
                                                                "value.ty"],
                                                    ::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};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("ADT type in pattern is not `type_marked_structural`")
                                                                    as &dyn Value)),
                                                        (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&adt_def) as
                                                                    &dyn Value)),
                                                        (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&debug(&value.ty)
                                                                    as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        let PartialEqImplStatus {
                                is_derived, structural_partial_eq, non_blanket_impl, .. } =
                            type_has_partial_eq_impl(self.tcx, self.typing_env, ty);
                        let (manual_partialeq_impl_span,
                                manual_partialeq_impl_note) =
                            match (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")]
205    fn valtree_to_pat(&self, value: ty::Value<'tcx>) -> Box<Pat<'tcx>> {
206        let span = self.span;
207        let tcx = self.tcx;
208        let ty::Value { ty, valtree } = value;
209
210        let kind = match ty.kind() {
211            // Extremely important check for all ADTs!
212            // Make sure they are eligible to be used in patterns, and if not, emit an error.
213            ty::Adt(adt_def, _) if !self.type_marked_structural(ty) => {
214                // This ADT cannot be used as a constant in patterns.
215                debug!(?adt_def, ?value.ty, "ADT type in pattern is not `type_marked_structural`");
216                let PartialEqImplStatus {
217                    is_derived, structural_partial_eq, non_blanket_impl, ..
218                } = type_has_partial_eq_impl(self.tcx, self.typing_env, ty);
219                let (manual_partialeq_impl_span, manual_partialeq_impl_note) =
220                    match (structural_partial_eq, non_blanket_impl) {
221                        (true, _) => (None, false),
222                        (_, Some(def_id)) if def_id.is_local() && !is_derived => {
223                            (Some(tcx.def_span(def_id)), false)
224                        }
225                        _ => (None, true),
226                    };
227                let manual_partialeq_impl =
228                    manual_partialeq_impl_note || manual_partialeq_impl_span.is_some();
229                let is_local = adt_def.did().is_local();
230                let ty_def_span = tcx.def_span(adt_def.did());
231                let suggestion = if let Ok(name) = tcx.sess.source_map().span_to_snippet(self.span)
232                    && (is_local || manual_partialeq_impl)
233                {
234                    let mut hir_id = self.id;
235                    while let hir::Node::Pat(pat) = tcx.parent_hir_node(hir_id) {
236                        hir_id = pat.hir_id;
237                    }
238                    match tcx.parent_hir_node(hir_id) {
239                        hir::Node::Arm(hir::Arm { pat, guard: None, .. }) => {
240                            // Add an if condition to the match arm.
241                            Some(SuggestEq::AddIf {
242                                if_span: pat.span.shrink_to_hi(),
243                                pat_span: self.span,
244                                name,
245                                ty,
246                                manual_partialeq_impl,
247                            })
248                        }
249                        hir::Node::Arm(hir::Arm { guard: Some(guard), .. }) => {
250                            // Modify the the match arm if condition and add a check for equality.
251                            Some(SuggestEq::AddToIf {
252                                span: guard.span.shrink_to_hi(),
253                                pat_span: self.span,
254                                name,
255                                ty,
256                                manual_partialeq_impl,
257                            })
258                        }
259                        hir::Node::Expr(hir::Expr {
260                            kind: hir::ExprKind::Let(let_expr),
261                            span,
262                            ..
263                        }) => {
264                            if let_expr.pat.span == self.span {
265                                // `if let CONST = expr` -> `if CONST == expr`.
266                                Some(SuggestEq::ReplaceWithEq {
267                                    removal: span.until(self.span),
268                                    eq: self.span.between(let_expr.init.span),
269                                    ty,
270                                    manual_partialeq_impl,
271                                })
272                            } else if tcx.sess.edition().at_least_rust_2024() {
273                                // `if let Some(CONST) = expr` ->
274                                // `if let Some(binding) = expr && binding == CONST`.
275                                Some(SuggestEq::AddToLetChain {
276                                    span: span.shrink_to_hi(),
277                                    pat_span: self.span,
278                                    name,
279                                    ty,
280                                    manual_partialeq_impl,
281                                })
282                            } else {
283                                None
284                            }
285                        }
286                        hir::Node::LetStmt(let_stmt)
287                            if let Some(init) = let_stmt.init
288                                && let Some(els) = let_stmt.els
289                                && init.span.ctxt().is_root()
290                                && els.span.ctxt().is_root() =>
291                        {
292                            // `let PAT = expr else {` -> `if PAT == expr {`.
293                            Some(SuggestEq::ReplaceLetElseWithIf {
294                                if_span: let_stmt.span.until(let_stmt.pat.span),
295                                eq: let_stmt.pat.span.between(init.span),
296                                else_span: init.span.between(els.span),
297                                ty,
298                                manual_partialeq_impl,
299                            })
300                        }
301                        _ => None,
302                    }
303                } else {
304                    None
305                };
306                let err = TypeNotStructural {
307                    span,
308                    ty,
309                    ty_def_span,
310                    manual_partialeq_impl_span,
311                    manual_partialeq_impl_note,
312                    is_local,
313                    suggestion,
314                };
315                return self.mk_err(tcx.dcx().create_err(err), ty);
316            }
317            ty::Adt(adt_def, args) if adt_def.is_enum() => {
318                let (&variant_index, fields) = valtree.to_branch().split_first().unwrap();
319                let variant_index = VariantIdx::from_u32(variant_index.to_leaf().to_u32());
320                PatKind::Variant {
321                    adt_def: *adt_def,
322                    args,
323                    variant_index,
324                    subpatterns: self
325                        .lower_field_values_to_fieldpats(fields.iter().map(|ct| ct.to_value())),
326                }
327            }
328            ty::Adt(def, _) => {
329                assert!(!def.is_union()); // Valtree construction would never succeed for unions.
330                PatKind::Leaf {
331                    subpatterns: self.lower_field_values_to_fieldpats(
332                        valtree.to_branch().iter().map(|ct| ct.to_value()),
333                    ),
334                }
335            }
336            ty::Tuple(_) => PatKind::Leaf {
337                subpatterns: self.lower_field_values_to_fieldpats(
338                    valtree.to_branch().iter().map(|ct| ct.to_value()),
339                ),
340            },
341            ty::Slice(_) => PatKind::Slice {
342                prefix: valtree
343                    .to_branch()
344                    .iter()
345                    .map(|val| *self.valtree_to_pat(val.to_value()))
346                    .collect(),
347                slice: None,
348                suffix: Box::new([]),
349            },
350            ty::Array(_, _) => PatKind::Array {
351                prefix: valtree
352                    .to_branch()
353                    .iter()
354                    .map(|val| *self.valtree_to_pat(val.to_value()))
355                    .collect(),
356                slice: None,
357                suffix: Box::new([]),
358            },
359            ty::Str => {
360                // Constant/literal patterns of type `&str` are lowered to a
361                // `PatKind::Deref` wrapping a `PatKind::Constant` of type `str`.
362                // This pattern node is the `str` constant part.
363                //
364                // Under `feature(deref_patterns)`, string literal patterns can also
365                // have type `str` directly, without the `&`, in order to allow things
366                // like `deref!("...")` to work when the scrutinee is `String`.
367                PatKind::Constant { value }
368            }
369            ty::Ref(_, pointee_ty, ..) => {
370                if pointee_ty.is_str()
371                    || pointee_ty.is_slice()
372                    || pointee_ty.is_sized(tcx, self.typing_env)
373                {
374                    PatKind::Deref {
375                        // This node has type `ty::Ref`, so it's not a pin-deref.
376                        pin: hir::Pinnedness::Not,
377                        // Lower the valtree to a pattern as the pointee type.
378                        // This works because references have the same valtree
379                        // representation as their pointee.
380                        subpattern: self.valtree_to_pat(ty::Value { ty: *pointee_ty, valtree }),
381                    }
382                } else {
383                    return self.mk_err(
384                        tcx.dcx().create_err(UnsizedPattern { span, non_sm_ty: *pointee_ty }),
385                        ty,
386                    );
387                }
388            }
389            ty::Float(flt) => {
390                let v = valtree.to_leaf();
391                let is_nan = match flt {
392                    ty::FloatTy::F16 => v.to_f16().is_nan(),
393                    ty::FloatTy::F32 => v.to_f32().is_nan(),
394                    ty::FloatTy::F64 => v.to_f64().is_nan(),
395                    ty::FloatTy::F128 => v.to_f128().is_nan(),
396                };
397                if is_nan {
398                    // NaNs are not ever equal to anything so they make no sense as patterns.
399                    // Also see <https://github.com/rust-lang/rfcs/pull/3535>.
400                    return self.mk_err(tcx.dcx().create_err(NaNPattern { span }), ty);
401                } else {
402                    PatKind::Constant { value }
403                }
404            }
405            ty::Pat(..) | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::RawPtr(..) => {
406                // The raw pointers we see here have been "vetted" by valtree construction to be
407                // just integers, so we simply allow them.
408                PatKind::Constant { value }
409            }
410            ty::FnPtr(..) => {
411                unreachable!(
412                    "Valtree construction would never succeed for FnPtr, so this is unreachable."
413                )
414            }
415            _ => {
416                let err = InvalidPattern {
417                    span,
418                    non_sm_ty: ty,
419                    prefix: ty.prefix_string(tcx).to_string(),
420                };
421                return self.mk_err(tcx.dcx().create_err(err), ty);
422            }
423        };
424
425        Box::new(Pat { span, ty, kind, extra: None })
426    }
427}
428
429/// Given a type with type parameters, visit every ADT looking for types that need to
430/// `#[derive(PartialEq)]` for it to be a structural type.
431fn extend_type_not_partial_eq<'tcx>(
432    tcx: TyCtxt<'tcx>,
433    typing_env: ty::TypingEnv<'tcx>,
434    ty: Ty<'tcx>,
435    err: &mut Diag<'_>,
436) {
437    /// Collect all types that need to be `StructuralPartialEq`.
438    struct UsedParamsNeedInstantiationVisitor<'tcx> {
439        tcx: TyCtxt<'tcx>,
440        typing_env: ty::TypingEnv<'tcx>,
441        /// The user has written `impl PartialEq for Ty` which means it's non-structural.
442        adts_with_manual_partialeq: FxHashSet<Span>,
443        /// The type has no `PartialEq` implementation, neither manual or derived.
444        adts_without_partialeq: FxHashSet<Span>,
445        /// The user has written `impl PartialEq for Ty` which means it's non-structural,
446        /// but we don't have a span to point at, so we'll just add them as a `note`.
447        manual: FxHashSet<Ty<'tcx>>,
448        /// The type has no `PartialEq` implementation, neither manual or derived, but
449        /// we don't have a span to point at, so we'll just add them as a `note`.
450        without: FxHashSet<Ty<'tcx>>,
451    }
452
453    impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for UsedParamsNeedInstantiationVisitor<'tcx> {
454        type Result = ControlFlow<()>;
455        fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
456            match ty.kind() {
457                ty::Dynamic(..) => return ControlFlow::Break(()),
458                // Unsafe binders never implement `PartialEq`, so avoid walking into them
459                // which would require instantiating its binder with placeholders too.
460                ty::UnsafeBinder(..) => return ControlFlow::Break(()),
461                ty::FnPtr(..) => return ControlFlow::Continue(()),
462                ty::Adt(def, _args) => {
463                    let ty_def_id = def.did();
464                    let ty_def_span = self.tcx.def_span(ty_def_id);
465                    let PartialEqImplStatus {
466                        has_impl,
467                        is_derived,
468                        structural_partial_eq,
469                        non_blanket_impl,
470                    } = type_has_partial_eq_impl(self.tcx, self.typing_env, ty);
471                    match (has_impl, is_derived, structural_partial_eq, non_blanket_impl) {
472                        (_, _, true, _) => {}
473                        (true, false, _, Some(def_id)) if def_id.is_local() => {
474                            self.adts_with_manual_partialeq.insert(self.tcx.def_span(def_id));
475                        }
476                        (true, false, _, _) if ty_def_id.is_local() => {
477                            self.adts_with_manual_partialeq.insert(ty_def_span);
478                        }
479                        (false, _, _, _) if ty_def_id.is_local() => {
480                            self.adts_without_partialeq.insert(ty_def_span);
481                        }
482                        (true, false, _, _) => {
483                            self.manual.insert(ty);
484                        }
485                        (false, _, _, _) => {
486                            self.without.insert(ty);
487                        }
488                        _ => {}
489                    };
490                    ty.super_visit_with(self)
491                }
492                _ => ty.super_visit_with(self),
493            }
494        }
495    }
496    let mut v = UsedParamsNeedInstantiationVisitor {
497        tcx,
498        typing_env,
499        adts_with_manual_partialeq: FxHashSet::default(),
500        adts_without_partialeq: FxHashSet::default(),
501        manual: FxHashSet::default(),
502        without: FxHashSet::default(),
503    };
504    if v.visit_ty(ty).is_break() {
505        return;
506    }
507    #[allow(rustc::potential_query_instability)] // Span labels will be sorted by the rendering
508    for span in v.adts_with_manual_partialeq {
509        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");
510    }
511    #[allow(rustc::potential_query_instability)] // Span labels will be sorted by the rendering
512    for span in v.adts_without_partialeq {
513        err.span_label(
514            span,
515            "must be annotated with `#[derive(PartialEq)]` to be usable in patterns",
516        );
517    }
518    #[allow(rustc::potential_query_instability)]
519    let mut manual: Vec<_> = v.manual.into_iter().map(|t| t.to_string()).collect();
520    manual.sort();
521    for ty in manual {
522        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!(
523            "`{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"
524        ));
525    }
526    #[allow(rustc::potential_query_instability)]
527    let mut without: Vec<_> = v.without.into_iter().map(|t| t.to_string()).collect();
528    without.sort();
529    for ty in without {
530        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!(
531            "`{ty}` must be annotated with `#[derive(PartialEq)]` to be usable in patterns"
532        ));
533    }
534}
535
536#[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_field4_finish(f,
            "PartialEqImplStatus", "has_impl", &self.has_impl, "is_derived",
            &self.is_derived, "structural_partial_eq",
            &self.structural_partial_eq, "non_blanket_impl",
            &&self.non_blanket_impl)
    }
}Debug)]
537struct PartialEqImplStatus {
538    has_impl: bool,
539    is_derived: bool,
540    structural_partial_eq: bool,
541    non_blanket_impl: Option<DefId>,
542}
543
544x;#[instrument(level = "trace", skip(tcx), ret)]
545fn type_has_partial_eq_impl<'tcx>(
546    tcx: TyCtxt<'tcx>,
547    typing_env: ty::TypingEnv<'tcx>,
548    ty: Ty<'tcx>,
549) -> PartialEqImplStatus {
550    let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
551    // double-check there even *is* a semantic `PartialEq` to dispatch to.
552    //
553    // (If there isn't, then we can safely issue a hard
554    // error, because that's never worked, due to compiler
555    // using `PartialEq::eq` in this scenario in the past.)
556    let partial_eq_trait_id = tcx.require_lang_item(hir::LangItem::PartialEq, DUMMY_SP);
557    let structural_partial_eq_trait_id =
558        tcx.require_lang_item(hir::LangItem::StructuralPeq, DUMMY_SP);
559
560    let partial_eq_obligation = Obligation::new(
561        tcx,
562        ObligationCause::dummy(),
563        param_env,
564        ty::TraitRef::new(tcx, partial_eq_trait_id, [ty, ty]),
565    );
566
567    let mut automatically_derived = false;
568    let mut structural_peq = false;
569    let mut impl_def_id = None;
570    for def_id in tcx.non_blanket_impls_for_ty(partial_eq_trait_id, ty) {
571        automatically_derived = find_attr!(tcx, def_id, AutomaticallyDerived(..));
572        impl_def_id = Some(def_id);
573    }
574    for _ in tcx.non_blanket_impls_for_ty(structural_partial_eq_trait_id, ty) {
575        structural_peq = true;
576    }
577    // This *could* accept a type that isn't actually `PartialEq`, because region bounds get
578    // ignored. However that should be pretty much impossible since consts that do not depend on
579    // generics can only mention the `'static` lifetime, and how would one have a type that's
580    // `PartialEq` for some lifetime but *not* for `'static`? If this ever becomes a problem
581    // we'll need to leave some sort of trace of this requirement in the MIR so that borrowck
582    // can ensure that the type really implements `PartialEq`.
583    // We also do *not* require `const PartialEq`, not even in `const fn`. This violates the model
584    // that patterns can only do things that the code could also do without patterns, but it is
585    // needed for backwards compatibility. The actual pattern matching compares primitive values,
586    // `PartialEq::eq` never gets invoked, so there's no risk of us running non-const code.
587    PartialEqImplStatus {
588        has_impl: infcx.predicate_must_hold_modulo_regions(&partial_eq_obligation),
589        is_derived: automatically_derived,
590        structural_partial_eq: structural_peq,
591        non_blanket_impl: impl_def_id,
592    }
593}