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, TypeNotPartialEq, TypeNotStructural, UnionPattern, UnsizedPattern,
26};
27
28impl<'tcx> PatCtxt<'tcx> {
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                err.span_label(self.tcx.def_span(uv.def), rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("constant defined here"))msg!("constant defined here"));
85            }
86        }
87        Box::new(Pat { span: self.span, ty, kind: PatKind::Error(err.emit()), extra: None })
88    }
89
90    fn unevaluated_to_pat(
91        &mut self,
92        uv: ty::UnevaluatedConst<'tcx>,
93        ty: Ty<'tcx>,
94    ) -> Box<Pat<'tcx>> {
95        // It's not *technically* correct to be revealing opaque types here as borrowcheck has
96        // not run yet. However, CTFE itself uses `TypingMode::PostAnalysis` unconditionally even
97        // during typeck and not doing so has a lot of (undesirable) fallout (#101478, #119821).
98        // As a result we always use a revealed env when resolving the instance to evaluate.
99        //
100        // FIXME: `const_eval_resolve_for_typeck` should probably just modify the env itself
101        // instead of having this logic here
102        let typing_env = self
103            .tcx
104            .erase_and_anonymize_regions(self.typing_env)
105            .with_post_analysis_normalized(self.tcx);
106        let uv = self.tcx.erase_and_anonymize_regions(uv);
107
108        // try to resolve e.g. associated constants to their definition on an impl, and then
109        // evaluate the const.
110        let valtree = match self.tcx.const_eval_resolve_for_typeck(typing_env, uv, self.span) {
111            Ok(Ok(c)) => c,
112            Err(ErrorHandled::Reported(_, _)) => {
113                // Let's tell the use where this failing const occurs.
114                let mut err =
115                    self.tcx.dcx().create_err(CouldNotEvalConstPattern { span: self.span });
116                // We've emitted an error on the original const, it would be redundant to complain
117                // on its use as well.
118                if let ty::ConstKind::Unevaluated(uv) = self.c.kind()
119                    && let hir::def::DefKind::Const | hir::def::DefKind::AssocConst =
120                        self.tcx.def_kind(uv.def)
121                {
122                    err.downgrade_to_delayed_bug();
123                }
124                return self.mk_err(err, ty);
125            }
126            Err(ErrorHandled::TooGeneric(_)) => {
127                let mut e = self
128                    .tcx
129                    .dcx()
130                    .create_err(ConstPatternDependsOnGenericParameter { span: self.span });
131                for arg in uv.args {
132                    if let ty::GenericArgKind::Type(ty) = arg.kind()
133                        && let ty::Param(param_ty) = ty.kind()
134                    {
135                        let def_id = self.tcx.hir_enclosing_body_owner(self.id);
136                        let generics = self.tcx.generics_of(def_id);
137                        let param = generics.type_param(*param_ty, self.tcx);
138                        let span = self.tcx.def_span(param.def_id);
139                        e.span_label(span, "constant depends on this generic parameter");
140                        if let Some(ident) = self.tcx.def_ident_span(def_id)
141                            && self.tcx.sess.source_map().is_multiline(ident.between(span))
142                        {
143                            // Display the `fn` name as well in the diagnostic, as the generic isn't
144                            // in the same line and it could be confusing otherwise.
145                            e.span_label(ident, "");
146                        }
147                    }
148                }
149                return self.mk_err(e, ty);
150            }
151            Ok(Err(bad_ty)) => {
152                // The pattern cannot be turned into a valtree.
153                let e = match bad_ty.kind() {
154                    ty::Adt(def, ..) => {
155                        if !def.is_union() {
    ::core::panicking::panic("assertion failed: def.is_union()")
};assert!(def.is_union());
156                        self.tcx.dcx().create_err(UnionPattern { span: self.span })
157                    }
158                    ty::FnPtr(..) | ty::RawPtr(..) => {
159                        self.tcx.dcx().create_err(PointerPattern { span: self.span })
160                    }
161                    _ => self.tcx.dcx().create_err(InvalidPattern {
162                        span: self.span,
163                        non_sm_ty: bad_ty,
164                        prefix: bad_ty.prefix_string(self.tcx).to_string(),
165                    }),
166                };
167                return self.mk_err(e, ty);
168            }
169        };
170
171        // Lower the valtree to a THIR pattern.
172        let mut thir_pat = self.valtree_to_pat(ty::Value { ty, valtree });
173
174        if !thir_pat.references_error() {
175            // Always check for `PartialEq` if we had no other errors yet.
176            if !type_has_partial_eq_impl(self.tcx, typing_env, ty).has_impl {
177                let mut err = self.tcx.dcx().create_err(TypeNotPartialEq { span: self.span, ty });
178                extend_type_not_partial_eq(self.tcx, typing_env, ty, &mut err);
179                return self.mk_err(err, ty);
180            }
181        }
182
183        // Mark the pattern to indicate that it is the result of lowering a named
184        // constant. This is used for diagnostics.
185        thir_pat.extra.get_or_insert_default().expanded_const = Some(uv.def);
186        thir_pat
187    }
188
189    fn lower_field_values_to_fieldpats(
190        &self,
191        values: impl Iterator<Item = ty::Value<'tcx>>,
192    ) -> Vec<FieldPat<'tcx>> {
193        values
194            .enumerate()
195            .map(|(index, value)| FieldPat {
196                field: FieldIdx::new(index),
197                pattern: *self.valtree_to_pat(value),
198            })
199            .collect()
200    }
201
202    // Recursive helper for `to_pat`; invoke that (instead of calling this directly).
203    #[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(203u32),
                                    ::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:214",
                                                "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(214u32),
                                                ::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 ty_def_span = tcx.def_span(adt_def.did());
                        let err =
                            TypeNotStructural {
                                span,
                                ty,
                                ty_def_span,
                                manual_partialeq_impl_span,
                                manual_partialeq_impl_note,
                            };
                        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")]
204    fn valtree_to_pat(&self, value: ty::Value<'tcx>) -> Box<Pat<'tcx>> {
205        let span = self.span;
206        let tcx = self.tcx;
207        let ty::Value { ty, valtree } = value;
208
209        let kind = match ty.kind() {
210            // Extremely important check for all ADTs!
211            // Make sure they are eligible to be used in patterns, and if not, emit an error.
212            ty::Adt(adt_def, _) if !self.type_marked_structural(ty) => {
213                // This ADT cannot be used as a constant in patterns.
214                debug!(?adt_def, ?value.ty, "ADT type in pattern is not `type_marked_structural`");
215                let PartialEqImplStatus {
216                    is_derived, structural_partial_eq, non_blanket_impl, ..
217                } = type_has_partial_eq_impl(self.tcx, self.typing_env, ty);
218                let (manual_partialeq_impl_span, manual_partialeq_impl_note) =
219                    match (structural_partial_eq, non_blanket_impl) {
220                        (true, _) => (None, false),
221                        (_, Some(def_id)) if def_id.is_local() && !is_derived => {
222                            (Some(tcx.def_span(def_id)), false)
223                        }
224                        _ => (None, true),
225                    };
226                let ty_def_span = tcx.def_span(adt_def.did());
227                let err = TypeNotStructural {
228                    span,
229                    ty,
230                    ty_def_span,
231                    manual_partialeq_impl_span,
232                    manual_partialeq_impl_note,
233                };
234                return self.mk_err(tcx.dcx().create_err(err), ty);
235            }
236            ty::Adt(adt_def, args) if adt_def.is_enum() => {
237                let (&variant_index, fields) = valtree.to_branch().split_first().unwrap();
238                let variant_index = VariantIdx::from_u32(variant_index.to_leaf().to_u32());
239                PatKind::Variant {
240                    adt_def: *adt_def,
241                    args,
242                    variant_index,
243                    subpatterns: self
244                        .lower_field_values_to_fieldpats(fields.iter().map(|ct| ct.to_value())),
245                }
246            }
247            ty::Adt(def, _) => {
248                assert!(!def.is_union()); // Valtree construction would never succeed for unions.
249                PatKind::Leaf {
250                    subpatterns: self.lower_field_values_to_fieldpats(
251                        valtree.to_branch().iter().map(|ct| ct.to_value()),
252                    ),
253                }
254            }
255            ty::Tuple(_) => PatKind::Leaf {
256                subpatterns: self.lower_field_values_to_fieldpats(
257                    valtree.to_branch().iter().map(|ct| ct.to_value()),
258                ),
259            },
260            ty::Slice(_) => PatKind::Slice {
261                prefix: valtree
262                    .to_branch()
263                    .iter()
264                    .map(|val| *self.valtree_to_pat(val.to_value()))
265                    .collect(),
266                slice: None,
267                suffix: Box::new([]),
268            },
269            ty::Array(_, _) => PatKind::Array {
270                prefix: valtree
271                    .to_branch()
272                    .iter()
273                    .map(|val| *self.valtree_to_pat(val.to_value()))
274                    .collect(),
275                slice: None,
276                suffix: Box::new([]),
277            },
278            ty::Str => {
279                // Constant/literal patterns of type `&str` are lowered to a
280                // `PatKind::Deref` wrapping a `PatKind::Constant` of type `str`.
281                // This pattern node is the `str` constant part.
282                //
283                // Under `feature(deref_patterns)`, string literal patterns can also
284                // have type `str` directly, without the `&`, in order to allow things
285                // like `deref!("...")` to work when the scrutinee is `String`.
286                PatKind::Constant { value }
287            }
288            ty::Ref(_, pointee_ty, ..) => {
289                if pointee_ty.is_str()
290                    || pointee_ty.is_slice()
291                    || pointee_ty.is_sized(tcx, self.typing_env)
292                {
293                    PatKind::Deref {
294                        // This node has type `ty::Ref`, so it's not a pin-deref.
295                        pin: hir::Pinnedness::Not,
296                        // Lower the valtree to a pattern as the pointee type.
297                        // This works because references have the same valtree
298                        // representation as their pointee.
299                        subpattern: self.valtree_to_pat(ty::Value { ty: *pointee_ty, valtree }),
300                    }
301                } else {
302                    return self.mk_err(
303                        tcx.dcx().create_err(UnsizedPattern { span, non_sm_ty: *pointee_ty }),
304                        ty,
305                    );
306                }
307            }
308            ty::Float(flt) => {
309                let v = valtree.to_leaf();
310                let is_nan = match flt {
311                    ty::FloatTy::F16 => v.to_f16().is_nan(),
312                    ty::FloatTy::F32 => v.to_f32().is_nan(),
313                    ty::FloatTy::F64 => v.to_f64().is_nan(),
314                    ty::FloatTy::F128 => v.to_f128().is_nan(),
315                };
316                if is_nan {
317                    // NaNs are not ever equal to anything so they make no sense as patterns.
318                    // Also see <https://github.com/rust-lang/rfcs/pull/3535>.
319                    return self.mk_err(tcx.dcx().create_err(NaNPattern { span }), ty);
320                } else {
321                    PatKind::Constant { value }
322                }
323            }
324            ty::Pat(..) | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::RawPtr(..) => {
325                // The raw pointers we see here have been "vetted" by valtree construction to be
326                // just integers, so we simply allow them.
327                PatKind::Constant { value }
328            }
329            ty::FnPtr(..) => {
330                unreachable!(
331                    "Valtree construction would never succeed for FnPtr, so this is unreachable."
332                )
333            }
334            _ => {
335                let err = InvalidPattern {
336                    span,
337                    non_sm_ty: ty,
338                    prefix: ty.prefix_string(tcx).to_string(),
339                };
340                return self.mk_err(tcx.dcx().create_err(err), ty);
341            }
342        };
343
344        Box::new(Pat { span, ty, kind, extra: None })
345    }
346}
347
348/// Given a type with type parameters, visit every ADT looking for types that need to
349/// `#[derive(PartialEq)]` for it to be a structural type.
350fn extend_type_not_partial_eq<'tcx>(
351    tcx: TyCtxt<'tcx>,
352    typing_env: ty::TypingEnv<'tcx>,
353    ty: Ty<'tcx>,
354    err: &mut Diag<'_>,
355) {
356    /// Collect all types that need to be `StructuralPartialEq`.
357    struct UsedParamsNeedInstantiationVisitor<'tcx> {
358        tcx: TyCtxt<'tcx>,
359        typing_env: ty::TypingEnv<'tcx>,
360        /// The user has written `impl PartialEq for Ty` which means it's non-structural.
361        adts_with_manual_partialeq: FxHashSet<Span>,
362        /// The type has no `PartialEq` implementation, neither manual or derived.
363        adts_without_partialeq: FxHashSet<Span>,
364        /// The user has written `impl PartialEq for Ty` which means it's non-structural,
365        /// but we don't have a span to point at, so we'll just add them as a `note`.
366        manual: FxHashSet<Ty<'tcx>>,
367        /// The type has no `PartialEq` implementation, neither manual or derived, but
368        /// we don't have a span to point at, so we'll just add them as a `note`.
369        without: FxHashSet<Ty<'tcx>>,
370    }
371
372    impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for UsedParamsNeedInstantiationVisitor<'tcx> {
373        type Result = ControlFlow<()>;
374        fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
375            match ty.kind() {
376                ty::Dynamic(..) => return ControlFlow::Break(()),
377                // Unsafe binders never implement `PartialEq`, so avoid walking into them
378                // which would require instantiating its binder with placeholders too.
379                ty::UnsafeBinder(..) => return ControlFlow::Break(()),
380                ty::FnPtr(..) => return ControlFlow::Continue(()),
381                ty::Adt(def, _args) => {
382                    let ty_def_id = def.did();
383                    let ty_def_span = self.tcx.def_span(ty_def_id);
384                    let PartialEqImplStatus {
385                        has_impl,
386                        is_derived,
387                        structural_partial_eq,
388                        non_blanket_impl,
389                    } = type_has_partial_eq_impl(self.tcx, self.typing_env, ty);
390                    match (has_impl, is_derived, structural_partial_eq, non_blanket_impl) {
391                        (_, _, true, _) => {}
392                        (true, false, _, Some(def_id)) if def_id.is_local() => {
393                            self.adts_with_manual_partialeq.insert(self.tcx.def_span(def_id));
394                        }
395                        (true, false, _, _) if ty_def_id.is_local() => {
396                            self.adts_with_manual_partialeq.insert(ty_def_span);
397                        }
398                        (false, _, _, _) if ty_def_id.is_local() => {
399                            self.adts_without_partialeq.insert(ty_def_span);
400                        }
401                        (true, false, _, _) => {
402                            self.manual.insert(ty);
403                        }
404                        (false, _, _, _) => {
405                            self.without.insert(ty);
406                        }
407                        _ => {}
408                    };
409                    ty.super_visit_with(self)
410                }
411                _ => ty.super_visit_with(self),
412            }
413        }
414    }
415    let mut v = UsedParamsNeedInstantiationVisitor {
416        tcx,
417        typing_env,
418        adts_with_manual_partialeq: FxHashSet::default(),
419        adts_without_partialeq: FxHashSet::default(),
420        manual: FxHashSet::default(),
421        without: FxHashSet::default(),
422    };
423    if v.visit_ty(ty).is_break() {
424        return;
425    }
426    #[allow(rustc::potential_query_instability)] // Span labels will be sorted by the rendering
427    for span in v.adts_with_manual_partialeq {
428        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");
429    }
430    #[allow(rustc::potential_query_instability)] // Span labels will be sorted by the rendering
431    for span in v.adts_without_partialeq {
432        err.span_label(
433            span,
434            "must be annotated with `#[derive(PartialEq)]` to be usable in patterns",
435        );
436    }
437    #[allow(rustc::potential_query_instability)]
438    let mut manual: Vec<_> = v.manual.into_iter().map(|t| t.to_string()).collect();
439    manual.sort();
440    for ty in manual {
441        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!(
442            "`{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"
443        ));
444    }
445    #[allow(rustc::potential_query_instability)]
446    let mut without: Vec<_> = v.without.into_iter().map(|t| t.to_string()).collect();
447    without.sort();
448    for ty in without {
449        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!(
450            "`{ty}` must be annotated with `#[derive(PartialEq)]` to be usable in patterns"
451        ));
452    }
453}
454
455#[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)]
456struct PartialEqImplStatus {
457    has_impl: bool,
458    is_derived: bool,
459    structural_partial_eq: bool,
460    non_blanket_impl: Option<DefId>,
461}
462
463x;#[instrument(level = "trace", skip(tcx), ret)]
464fn type_has_partial_eq_impl<'tcx>(
465    tcx: TyCtxt<'tcx>,
466    typing_env: ty::TypingEnv<'tcx>,
467    ty: Ty<'tcx>,
468) -> PartialEqImplStatus {
469    let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
470    // double-check there even *is* a semantic `PartialEq` to dispatch to.
471    //
472    // (If there isn't, then we can safely issue a hard
473    // error, because that's never worked, due to compiler
474    // using `PartialEq::eq` in this scenario in the past.)
475    let partial_eq_trait_id = tcx.require_lang_item(hir::LangItem::PartialEq, DUMMY_SP);
476    let structural_partial_eq_trait_id =
477        tcx.require_lang_item(hir::LangItem::StructuralPeq, DUMMY_SP);
478
479    let partial_eq_obligation = Obligation::new(
480        tcx,
481        ObligationCause::dummy(),
482        param_env,
483        ty::TraitRef::new(tcx, partial_eq_trait_id, [ty, ty]),
484    );
485
486    let mut automatically_derived = false;
487    let mut structural_peq = false;
488    let mut impl_def_id = None;
489    for def_id in tcx.non_blanket_impls_for_ty(partial_eq_trait_id, ty) {
490        automatically_derived = find_attr!(tcx, def_id, AutomaticallyDerived(..));
491        impl_def_id = Some(def_id);
492    }
493    for _ in tcx.non_blanket_impls_for_ty(structural_partial_eq_trait_id, ty) {
494        structural_peq = true;
495    }
496    // This *could* accept a type that isn't actually `PartialEq`, because region bounds get
497    // ignored. However that should be pretty much impossible since consts that do not depend on
498    // generics can only mention the `'static` lifetime, and how would one have a type that's
499    // `PartialEq` for some lifetime but *not* for `'static`? If this ever becomes a problem
500    // we'll need to leave some sort of trace of this requirement in the MIR so that borrowck
501    // can ensure that the type really implements `PartialEq`.
502    // We also do *not* require `const PartialEq`, not even in `const fn`. This violates the model
503    // that patterns can only do things that the code could also do without patterns, but it is
504    // needed for backwards compatibility. The actual pattern matching compares primitive values,
505    // `PartialEq::eq` never gets invoked, so there's no risk of us running non-const code.
506    PartialEqImplStatus {
507        has_impl: infcx.predicate_must_hold_modulo_regions(&partial_eq_obligation),
508        is_derived: automatically_derived,
509        structural_partial_eq: structural_peq,
510        non_blanket_impl: impl_def_id,
511    }
512}