Skip to main content

rustc_hir_analysis/coherence/
builtin.rs

1//! Check properties that are required by built-in traits and set
2//! up data structures required by type-checking/codegen.
3
4use std::collections::BTreeMap;
5
6use rustc_data_structures::fx::FxHashSet;
7use rustc_errors::{ErrorGuaranteed, MultiSpan};
8use rustc_hir as hir;
9use rustc_hir::ItemKind;
10use rustc_hir::def_id::{DefId, LocalDefId};
11use rustc_hir::lang_items::LangItem;
12use rustc_infer::infer::{self, RegionResolutionError, SubregionOrigin, TyCtxtInferExt};
13use rustc_infer::traits::Obligation;
14use rustc_middle::ty::adjustment::CoerceUnsizedInfo;
15use rustc_middle::ty::print::PrintTraitRefExt as _;
16use rustc_middle::ty::{
17    self, Ty, TyCtxt, TypeVisitableExt, TypingMode, suggest_constraining_type_params,
18};
19use rustc_span::{DUMMY_SP, Span, sym};
20use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
21use rustc_trait_selection::traits::misc::{
22    ConstParamTyImplementationError, CopyImplementationError, InfringingFieldsReason,
23    type_allowed_to_implement_const_param_ty, type_allowed_to_implement_copy,
24};
25use rustc_trait_selection::traits::{self, ObligationCause, ObligationCtxt};
26use tracing::debug;
27
28use crate::errors;
29
30pub(super) fn check_trait<'tcx>(
31    tcx: TyCtxt<'tcx>,
32    trait_def_id: DefId,
33    impl_def_id: LocalDefId,
34    impl_header: ty::ImplTraitHeader<'tcx>,
35) -> Result<(), ErrorGuaranteed> {
36    let lang_items = tcx.lang_items();
37    let checker = Checker { tcx, trait_def_id, impl_def_id, impl_header };
38    checker.check(lang_items.drop_trait(), visit_implementation_of_drop)?;
39    checker.check(lang_items.async_drop_trait(), visit_implementation_of_drop)?;
40    checker.check(lang_items.copy_trait(), visit_implementation_of_copy)?;
41    checker.check(lang_items.unpin_trait(), visit_implementation_of_unpin)?;
42    checker.check(lang_items.const_param_ty_trait(), |checker| {
43        visit_implementation_of_const_param_ty(checker)
44    })?;
45    checker.check(lang_items.coerce_unsized_trait(), visit_implementation_of_coerce_unsized)?;
46    checker
47        .check(lang_items.dispatch_from_dyn_trait(), visit_implementation_of_dispatch_from_dyn)?;
48    checker.check(
49        lang_items.coerce_pointee_validated_trait(),
50        visit_implementation_of_coerce_pointee_validity,
51    )?;
52    Ok(())
53}
54
55struct Checker<'tcx> {
56    tcx: TyCtxt<'tcx>,
57    trait_def_id: DefId,
58    impl_def_id: LocalDefId,
59    impl_header: ty::ImplTraitHeader<'tcx>,
60}
61
62impl<'tcx> Checker<'tcx> {
63    fn check(
64        &self,
65        trait_def_id: Option<DefId>,
66        f: impl FnOnce(&Self) -> Result<(), ErrorGuaranteed>,
67    ) -> Result<(), ErrorGuaranteed> {
68        if Some(self.trait_def_id) == trait_def_id { f(self) } else { Ok(()) }
69    }
70}
71
72fn visit_implementation_of_drop(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
73    let tcx = checker.tcx;
74    let impl_did = checker.impl_def_id;
75    // Destructors only work on local ADT types.
76    match checker.impl_header.trait_ref.instantiate_identity().self_ty().kind() {
77        ty::Adt(def, _) if def.did().is_local() => return Ok(()),
78        ty::Error(_) => return Ok(()),
79        _ => {}
80    }
81
82    let impl_ = tcx.hir_expect_item(impl_did).expect_impl();
83
84    Err(tcx.dcx().emit_err(errors::DropImplOnWrongItem {
85        span: impl_.self_ty.span,
86        trait_: tcx.item_name(checker.impl_header.trait_ref.skip_binder().def_id),
87    }))
88}
89
90fn visit_implementation_of_copy(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
91    let tcx = checker.tcx;
92    let impl_header = checker.impl_header;
93    let impl_did = checker.impl_def_id;
94    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/coherence/builtin.rs:94",
                        "rustc_hir_analysis::coherence::builtin",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/coherence/builtin.rs"),
                        ::tracing_core::__macro_support::Option::Some(94u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::coherence::builtin"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::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!("visit_implementation_of_copy: impl_did={0:?}",
                                                    impl_did) as &dyn Value))])
            });
    } else { ; }
};debug!("visit_implementation_of_copy: impl_did={:?}", impl_did);
95
96    let self_type = impl_header.trait_ref.instantiate_identity().self_ty();
97    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/coherence/builtin.rs:97",
                        "rustc_hir_analysis::coherence::builtin",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/coherence/builtin.rs"),
                        ::tracing_core::__macro_support::Option::Some(97u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::coherence::builtin"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::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!("visit_implementation_of_copy: self_type={0:?} (bound)",
                                                    self_type) as &dyn Value))])
            });
    } else { ; }
};debug!("visit_implementation_of_copy: self_type={:?} (bound)", self_type);
98
99    let param_env = tcx.param_env(impl_did);
100    if !!self_type.has_escaping_bound_vars() {
    ::core::panicking::panic("assertion failed: !self_type.has_escaping_bound_vars()")
};assert!(!self_type.has_escaping_bound_vars());
101
102    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/coherence/builtin.rs:102",
                        "rustc_hir_analysis::coherence::builtin",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/coherence/builtin.rs"),
                        ::tracing_core::__macro_support::Option::Some(102u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::coherence::builtin"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::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!("visit_implementation_of_copy: self_type={0:?} (free)",
                                                    self_type) as &dyn Value))])
            });
    } else { ; }
};debug!("visit_implementation_of_copy: self_type={:?} (free)", self_type);
103
104    if let ty::ImplPolarity::Negative = impl_header.polarity {
105        return Ok(());
106    }
107
108    let cause = traits::ObligationCause::misc(DUMMY_SP, impl_did);
109    match type_allowed_to_implement_copy(tcx, param_env, self_type, cause, impl_header.safety) {
110        Ok(()) => Ok(()),
111        Err(CopyImplementationError::InfringingFields(fields)) => {
112            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
113            Err(infringing_fields_error(
114                tcx,
115                fields.into_iter().map(|(field, ty, reason)| (tcx.def_span(field.did), ty, reason)),
116                LangItem::Copy,
117                impl_did,
118                span,
119            ))
120        }
121        Err(CopyImplementationError::NotAnAdt) => {
122            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
123            Err(tcx.dcx().emit_err(errors::CopyImplOnNonAdt { span }))
124        }
125        Err(CopyImplementationError::HasDestructor(did)) => {
126            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
127            let impl_ = tcx.def_span(did);
128            Err(tcx.dcx().emit_err(errors::CopyImplOnTypeWithDtor { span, impl_ }))
129        }
130        Err(CopyImplementationError::HasUnsafeFields) => {
131            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
132            Err(tcx
133                .dcx()
134                .span_delayed_bug(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot implement `Copy` for `{0}`",
                self_type))
    })format!("cannot implement `Copy` for `{}`", self_type)))
135        }
136    }
137}
138
139fn visit_implementation_of_unpin(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
140    let tcx = checker.tcx;
141    let impl_header = checker.impl_header;
142    let impl_did = checker.impl_def_id;
143    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/coherence/builtin.rs:143",
                        "rustc_hir_analysis::coherence::builtin",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/coherence/builtin.rs"),
                        ::tracing_core::__macro_support::Option::Some(143u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::coherence::builtin"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::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!("visit_implementation_of_unpin: impl_did={0:?}",
                                                    impl_did) as &dyn Value))])
            });
    } else { ; }
};debug!("visit_implementation_of_unpin: impl_did={:?}", impl_did);
144
145    let self_type = impl_header.trait_ref.instantiate_identity().self_ty();
146    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/coherence/builtin.rs:146",
                        "rustc_hir_analysis::coherence::builtin",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/coherence/builtin.rs"),
                        ::tracing_core::__macro_support::Option::Some(146u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::coherence::builtin"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::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!("visit_implementation_of_unpin: self_type={0:?}",
                                                    self_type) as &dyn Value))])
            });
    } else { ; }
};debug!("visit_implementation_of_unpin: self_type={:?}", self_type);
147
148    let span = tcx.def_span(impl_did);
149
150    if tcx.features().pin_ergonomics() {
151        match self_type.kind() {
152            // Soundness concerns: a type `T` annotated with `#[pin_v2]` is allowed to project
153            // `Pin<&mut T>` to its field `Pin<&mut U>` safely (even if `U: !Unpin`).
154            // If `T` is allowed to impl `Unpin` manually (note that `Unpin` is a safe trait,
155            // which cannot carry safety properties), then `&mut U` could be obtained from
156            // `&mut T` that dereferenced by `Pin<&mut T>`, which breaks the safety contract of
157            // `Pin<&mut U>` for `U: !Unpin`.
158            ty::Adt(adt, _) if adt.is_pin_project() => {
159                return Err(tcx.dcx().emit_err(crate::errors::ImplUnpinForPinProjectedType {
160                    span,
161                    adt_span: tcx.def_span(adt.did()),
162                    adt_name: tcx.item_name(adt.did()),
163                }));
164            }
165            ty::Adt(_, _) => {}
166            _ => {
167                return Err(tcx.dcx().span_delayed_bug(span, "impl of `Unpin` for a non-adt type"));
168            }
169        };
170    }
171    Ok(())
172}
173
174fn visit_implementation_of_const_param_ty(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
175    let tcx = checker.tcx;
176    let header = checker.impl_header;
177    let impl_did = checker.impl_def_id;
178    let self_type = header.trait_ref.instantiate_identity().self_ty();
179    if !!self_type.has_escaping_bound_vars() {
    ::core::panicking::panic("assertion failed: !self_type.has_escaping_bound_vars()")
};assert!(!self_type.has_escaping_bound_vars());
180
181    let param_env = tcx.param_env(impl_did);
182
183    if let ty::ImplPolarity::Negative | ty::ImplPolarity::Reservation = header.polarity {
184        return Ok(());
185    }
186
187    if !tcx.features().adt_const_params() {
188        match *self_type.kind() {
189            ty::Adt(adt, _) if adt.is_struct() => {
190                let struct_vis = tcx.visibility(adt.did());
191                for variant in adt.variants() {
192                    for field in &variant.fields {
193                        if !field.vis.is_at_least(struct_vis, tcx) {
194                            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
195                            return Err(tcx
196                                .dcx()
197                                .emit_err(errors::ConstParamTyFieldVisMismatch { span }));
198                        }
199                    }
200                }
201            }
202
203            _ => {}
204        }
205    }
206
207    let cause = traits::ObligationCause::misc(DUMMY_SP, impl_did);
208    match type_allowed_to_implement_const_param_ty(tcx, param_env, self_type, cause) {
209        Ok(()) => Ok(()),
210        Err(ConstParamTyImplementationError::InfrigingFields(fields)) => {
211            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
212            Err(infringing_fields_error(
213                tcx,
214                fields.into_iter().map(|(field, ty, reason)| (tcx.def_span(field.did), ty, reason)),
215                LangItem::ConstParamTy,
216                impl_did,
217                span,
218            ))
219        }
220        Err(ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed) => {
221            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
222            Err(tcx.dcx().emit_err(errors::ConstParamTyImplOnNonAdt { span }))
223        }
224        Err(ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(infringing_tys)) => {
225            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
226            Err(infringing_fields_error(
227                tcx,
228                infringing_tys.into_iter().map(|(ty, reason)| (span, ty, reason)),
229                LangItem::ConstParamTy,
230                impl_did,
231                span,
232            ))
233        }
234        Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
235            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
236            Err(tcx.dcx().emit_err(errors::ConstParamTyImplOnUnsized { span }))
237        }
238    }
239}
240
241fn visit_implementation_of_coerce_unsized(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
242    let tcx = checker.tcx;
243    let impl_did = checker.impl_def_id;
244    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/coherence/builtin.rs:244",
                        "rustc_hir_analysis::coherence::builtin",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/coherence/builtin.rs"),
                        ::tracing_core::__macro_support::Option::Some(244u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::coherence::builtin"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::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!("visit_implementation_of_coerce_unsized: impl_did={0:?}",
                                                    impl_did) as &dyn Value))])
            });
    } else { ; }
};debug!("visit_implementation_of_coerce_unsized: impl_did={:?}", impl_did);
245
246    // Just compute this for the side-effects, in particular reporting
247    // errors; other parts of the code may demand it for the info of
248    // course.
249    tcx.ensure_result().coerce_unsized_info(impl_did)
250}
251
252fn is_from_coerce_pointee_derive(tcx: TyCtxt<'_>, span: Span) -> bool {
253    span.ctxt()
254        .outer_expn_data()
255        .macro_def_id
256        .is_some_and(|def_id| tcx.is_diagnostic_item(sym::CoercePointee, def_id))
257}
258
259fn visit_implementation_of_dispatch_from_dyn(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
260    let tcx = checker.tcx;
261    let impl_did = checker.impl_def_id;
262    let trait_ref = checker.impl_header.trait_ref.instantiate_identity();
263    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/coherence/builtin.rs:263",
                        "rustc_hir_analysis::coherence::builtin",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/coherence/builtin.rs"),
                        ::tracing_core::__macro_support::Option::Some(263u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::coherence::builtin"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::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!("visit_implementation_of_dispatch_from_dyn: impl_did={0:?}",
                                                    impl_did) as &dyn Value))])
            });
    } else { ; }
};debug!("visit_implementation_of_dispatch_from_dyn: impl_did={:?}", impl_did);
264
265    let span = tcx.def_span(impl_did);
266    let trait_name = "DispatchFromDyn";
267
268    let source = trait_ref.self_ty();
269    let target = {
270        if !tcx.is_lang_item(trait_ref.def_id, LangItem::DispatchFromDyn) {
    ::core::panicking::panic("assertion failed: tcx.is_lang_item(trait_ref.def_id, LangItem::DispatchFromDyn)")
};assert!(tcx.is_lang_item(trait_ref.def_id, LangItem::DispatchFromDyn));
271
272        trait_ref.args.type_at(1)
273    };
274
275    // Check `CoercePointee` impl is WF -- if not, then there's no reason to report
276    // redundant errors for `DispatchFromDyn`. This is best effort, though.
277    let mut res = Ok(());
278    tcx.for_each_relevant_impl(
279        tcx.require_lang_item(LangItem::CoerceUnsized, span),
280        source,
281        |impl_def_id| {
282            res = res.and(tcx.ensure_result().coerce_unsized_info(impl_def_id));
283        },
284    );
285    res?;
286
287    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/coherence/builtin.rs:287",
                        "rustc_hir_analysis::coherence::builtin",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/coherence/builtin.rs"),
                        ::tracing_core::__macro_support::Option::Some(287u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::coherence::builtin"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::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!("visit_implementation_of_dispatch_from_dyn: {0:?} -> {1:?}",
                                                    source, target) as &dyn Value))])
            });
    } else { ; }
};debug!("visit_implementation_of_dispatch_from_dyn: {:?} -> {:?}", source, target);
288
289    let param_env = tcx.param_env(impl_did);
290
291    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
292    let cause = ObligationCause::misc(span, impl_did);
293
294    // Later parts of the compiler rely on all DispatchFromDyn types to be ABI-compatible with raw
295    // pointers. This is enforced here: we only allow impls for references, raw pointers, and things
296    // that are effectively repr(transparent) newtypes around types that already hav a
297    // DispatchedFromDyn impl. We cannot literally use repr(transparent) on those types since some
298    // of them support an allocator, but we ensure that for the cases where the type implements this
299    // trait, they *do* satisfy the repr(transparent) rules, and then we assume that everything else
300    // in the compiler (in particular, all the call ABI logic) will treat them as repr(transparent)
301    // even if they do not carry that attribute.
302    match (source.kind(), target.kind()) {
303        (&ty::Pat(_, pat_a), &ty::Pat(_, pat_b)) => {
304            if pat_a != pat_b {
305                return Err(tcx.dcx().emit_err(errors::CoerceSamePatKind {
306                    span,
307                    trait_name,
308                    pat_a: pat_a.to_string(),
309                    pat_b: pat_b.to_string(),
310                }));
311            }
312            Ok(())
313        }
314
315        (&ty::Ref(r_a, _, mutbl_a), ty::Ref(r_b, _, mutbl_b))
316            if r_a == *r_b && mutbl_a == *mutbl_b =>
317        {
318            Ok(())
319        }
320        (&ty::RawPtr(_, a_mutbl), &ty::RawPtr(_, b_mutbl)) if a_mutbl == b_mutbl => Ok(()),
321        (&ty::Adt(def_a, args_a), &ty::Adt(def_b, args_b))
322            if def_a.is_struct() && def_b.is_struct() =>
323        {
324            if def_a != def_b {
325                let source_path = tcx.def_path_str(def_a.did());
326                let target_path = tcx.def_path_str(def_b.did());
327                return Err(tcx.dcx().emit_err(errors::CoerceSameStruct {
328                    span,
329                    trait_name,
330                    note: true,
331                    source_path,
332                    target_path,
333                }));
334            }
335
336            if def_a.repr().c() || def_a.repr().packed() {
337                return Err(tcx.dcx().emit_err(errors::DispatchFromDynRepr { span }));
338            }
339
340            let fields = &def_a.non_enum_variant().fields;
341
342            let mut res = Ok(());
343            let coerced_fields = fields
344                .iter_enumerated()
345                .filter_map(|(i, field)| {
346                    // Ignore PhantomData fields
347                    let unnormalized_ty = tcx.type_of(field.did).instantiate_identity();
348                    if tcx
349                        .try_normalize_erasing_regions(
350                            ty::TypingEnv::non_body_analysis(tcx, def_a.did()),
351                            unnormalized_ty,
352                        )
353                        .unwrap_or(unnormalized_ty)
354                        .is_phantom_data()
355                    {
356                        return None;
357                    }
358
359                    let ty_a = field.ty(tcx, args_a);
360                    let ty_b = field.ty(tcx, args_b);
361
362                    // FIXME: We could do normalization here, but is it really worth it?
363                    if ty_a == ty_b {
364                        // Allow 1-ZSTs that don't mention type params.
365                        //
366                        // Allowing type params here would allow us to possibly transmute
367                        // between ZSTs, which may be used to create library unsoundness.
368                        if let Ok(layout) =
369                            tcx.layout_of(infcx.typing_env(param_env).as_query_input(ty_a))
370                            && layout.is_1zst()
371                            && !ty_a.has_non_region_param()
372                        {
373                            // ignore 1-ZST fields
374                            return None;
375                        }
376
377                        res = Err(tcx.dcx().emit_err(errors::DispatchFromDynZST {
378                            span,
379                            name: field.ident(tcx),
380                            ty: ty_a,
381                        }));
382
383                        None
384                    } else {
385                        Some((i, ty_a, ty_b, tcx.def_span(field.did)))
386                    }
387                })
388                .collect::<Vec<_>>();
389            res?;
390
391            if coerced_fields.is_empty() {
392                return Err(tcx.dcx().emit_err(errors::CoerceNoField {
393                    span,
394                    trait_name,
395                    note: true,
396                }));
397            } else if let &[(_, ty_a, ty_b, field_span)] = &coerced_fields[..] {
398                let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
399                ocx.register_obligation(Obligation::new(
400                    tcx,
401                    cause.clone(),
402                    param_env,
403                    ty::TraitRef::new(tcx, trait_ref.def_id, [ty_a, ty_b]),
404                ));
405                let errors = ocx.evaluate_obligations_error_on_ambiguity();
406                if !errors.is_empty() {
407                    if is_from_coerce_pointee_derive(tcx, span) {
408                        return Err(tcx.dcx().emit_err(errors::CoerceFieldValidity {
409                            span,
410                            trait_name,
411                            ty: trait_ref.self_ty(),
412                            field_span,
413                            field_ty: ty_a,
414                        }));
415                    } else {
416                        return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
417                    }
418                }
419
420                // Finally, resolve all regions.
421                ocx.resolve_regions_and_report_errors(impl_did, param_env, [])?;
422
423                Ok(())
424            } else {
425                return Err(tcx.dcx().emit_err(errors::CoerceMulti {
426                    span,
427                    trait_name,
428                    number: coerced_fields.len(),
429                    fields: coerced_fields.iter().map(|(_, _, _, s)| *s).collect::<Vec<_>>().into(),
430                }));
431            }
432        }
433        _ => Err(tcx.dcx().emit_err(errors::CoerceUnsizedNonStruct { span, trait_name })),
434    }
435}
436
437pub(crate) fn coerce_unsized_info<'tcx>(
438    tcx: TyCtxt<'tcx>,
439    impl_did: LocalDefId,
440) -> Result<CoerceUnsizedInfo, ErrorGuaranteed> {
441    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/coherence/builtin.rs:441",
                        "rustc_hir_analysis::coherence::builtin",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/coherence/builtin.rs"),
                        ::tracing_core::__macro_support::Option::Some(441u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::coherence::builtin"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::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!("compute_coerce_unsized_info(impl_did={0:?})",
                                                    impl_did) as &dyn Value))])
            });
    } else { ; }
};debug!("compute_coerce_unsized_info(impl_did={:?})", impl_did);
442    let span = tcx.def_span(impl_did);
443    let trait_name = "CoerceUnsized";
444
445    let coerce_unsized_trait = tcx.require_lang_item(LangItem::CoerceUnsized, span);
446    let unsize_trait = tcx.require_lang_item(LangItem::Unsize, span);
447
448    let source = tcx.type_of(impl_did).instantiate_identity();
449    let trait_ref = tcx.impl_trait_ref(impl_did).instantiate_identity();
450
451    match (&trait_ref.def_id, &coerce_unsized_trait) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(trait_ref.def_id, coerce_unsized_trait);
452    let target = trait_ref.args.type_at(1);
453    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/coherence/builtin.rs:453",
                        "rustc_hir_analysis::coherence::builtin",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/coherence/builtin.rs"),
                        ::tracing_core::__macro_support::Option::Some(453u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::coherence::builtin"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::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!("visit_implementation_of_coerce_unsized: {0:?} -> {1:?} (bound)",
                                                    source, target) as &dyn Value))])
            });
    } else { ; }
};debug!("visit_implementation_of_coerce_unsized: {:?} -> {:?} (bound)", source, target);
454
455    let param_env = tcx.param_env(impl_did);
456    if !!source.has_escaping_bound_vars() {
    ::core::panicking::panic("assertion failed: !source.has_escaping_bound_vars()")
};assert!(!source.has_escaping_bound_vars());
457
458    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/coherence/builtin.rs:458",
                        "rustc_hir_analysis::coherence::builtin",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/coherence/builtin.rs"),
                        ::tracing_core::__macro_support::Option::Some(458u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::coherence::builtin"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::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!("visit_implementation_of_coerce_unsized: {0:?} -> {1:?} (free)",
                                                    source, target) as &dyn Value))])
            });
    } else { ; }
};debug!("visit_implementation_of_coerce_unsized: {:?} -> {:?} (free)", source, target);
459
460    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
461    let cause = ObligationCause::misc(span, impl_did);
462    let check_mutbl = |mt_a: ty::TypeAndMut<'tcx>,
463                       mt_b: ty::TypeAndMut<'tcx>,
464                       mk_ptr: &dyn Fn(Ty<'tcx>) -> Ty<'tcx>| {
465        if mt_a.mutbl < mt_b.mutbl {
466            infcx
467                .err_ctxt()
468                .report_mismatched_types(
469                    &cause,
470                    param_env,
471                    mk_ptr(mt_b.ty),
472                    target,
473                    ty::error::TypeError::Mutability,
474                )
475                .emit();
476        }
477        (mt_a.ty, mt_b.ty, unsize_trait, None, span)
478    };
479    let (source, target, trait_def_id, kind, field_span) = match (source.kind(), target.kind()) {
480        (&ty::Pat(ty_a, pat_a), &ty::Pat(ty_b, pat_b)) => {
481            if pat_a != pat_b {
482                return Err(tcx.dcx().emit_err(errors::CoerceSamePatKind {
483                    span,
484                    trait_name,
485                    pat_a: pat_a.to_string(),
486                    pat_b: pat_b.to_string(),
487                }));
488            }
489            (ty_a, ty_b, coerce_unsized_trait, None, span)
490        }
491
492        (&ty::Ref(r_a, ty_a, mutbl_a), &ty::Ref(r_b, ty_b, mutbl_b)) => {
493            infcx.sub_regions(SubregionOrigin::RelateObjectBound(span), r_b, r_a);
494            let mt_a = ty::TypeAndMut { ty: ty_a, mutbl: mutbl_a };
495            let mt_b = ty::TypeAndMut { ty: ty_b, mutbl: mutbl_b };
496            check_mutbl(mt_a, mt_b, &|ty| Ty::new_imm_ref(tcx, r_b, ty))
497        }
498
499        (&ty::Ref(_, ty_a, mutbl_a), &ty::RawPtr(ty_b, mutbl_b))
500        | (&ty::RawPtr(ty_a, mutbl_a), &ty::RawPtr(ty_b, mutbl_b)) => {
501            let mt_a = ty::TypeAndMut { ty: ty_a, mutbl: mutbl_a };
502            let mt_b = ty::TypeAndMut { ty: ty_b, mutbl: mutbl_b };
503            check_mutbl(mt_a, mt_b, &|ty| Ty::new_imm_ptr(tcx, ty))
504        }
505
506        (&ty::Adt(def_a, args_a), &ty::Adt(def_b, args_b))
507            if def_a.is_struct() && def_b.is_struct() =>
508        {
509            if def_a != def_b {
510                let source_path = tcx.def_path_str(def_a.did());
511                let target_path = tcx.def_path_str(def_b.did());
512                return Err(tcx.dcx().emit_err(errors::CoerceSameStruct {
513                    span,
514                    trait_name,
515                    note: true,
516                    source_path,
517                    target_path,
518                }));
519            }
520
521            // Here we are considering a case of converting
522            // `S<P0...Pn>` to `S<Q0...Qn>`. As an example, let's imagine a struct `Foo<T, U>`,
523            // which acts like a pointer to `U`, but carries along some extra data of type `T`:
524            //
525            //     struct Foo<T, U> {
526            //         extra: T,
527            //         ptr: *mut U,
528            //     }
529            //
530            // We might have an impl that allows (e.g.) `Foo<T, [i32; 3]>` to be unsized
531            // to `Foo<T, [i32]>`. That impl would look like:
532            //
533            //   impl<T, U: Unsize<V>, V> CoerceUnsized<Foo<T, V>> for Foo<T, U> {}
534            //
535            // Here `U = [i32; 3]` and `V = [i32]`. At runtime,
536            // when this coercion occurs, we would be changing the
537            // field `ptr` from a thin pointer of type `*mut [i32;
538            // 3]` to a wide pointer of type `*mut [i32]` (with
539            // extra data `3`). **The purpose of this check is to
540            // make sure that we know how to do this conversion.**
541            //
542            // To check if this impl is legal, we would walk down
543            // the fields of `Foo` and consider their types with
544            // both generic parameters. We are looking to find that
545            // exactly one (non-phantom) field has changed its
546            // type, which we will expect to be the pointer that
547            // is becoming fat (we could probably generalize this
548            // to multiple thin pointers of the same type becoming
549            // fat, but we don't). In this case:
550            //
551            // - `extra` has type `T` before and type `T` after
552            // - `ptr` has type `*mut U` before and type `*mut V` after
553            //
554            // Since just one field changed, we would then check
555            // that `*mut U: CoerceUnsized<*mut V>` is implemented
556            // (in other words, that we know how to do this
557            // conversion). This will work out because `U:
558            // Unsize<V>`, and we have a builtin rule that `*mut
559            // U` can be coerced to `*mut V` if `U: Unsize<V>`.
560            let fields = &def_a.non_enum_variant().fields;
561            let diff_fields = fields
562                .iter_enumerated()
563                .filter_map(|(i, f)| {
564                    let (a, b) = (f.ty(tcx, args_a), f.ty(tcx, args_b));
565
566                    // Ignore PhantomData fields
567                    let unnormalized_ty = tcx.type_of(f.did).instantiate_identity();
568                    if tcx
569                        .try_normalize_erasing_regions(
570                            ty::TypingEnv::non_body_analysis(tcx, def_a.did()),
571                            unnormalized_ty,
572                        )
573                        .unwrap_or(unnormalized_ty)
574                        .is_phantom_data()
575                    {
576                        return None;
577                    }
578
579                    // Ignore fields that aren't changed; it may
580                    // be that we could get away with subtyping or
581                    // something more accepting, but we use
582                    // equality because we want to be able to
583                    // perform this check without computing
584                    // variance or constraining opaque types' hidden types.
585                    // (This is because we may have to evaluate constraint
586                    // expressions in the course of execution.)
587                    // See e.g., #41936.
588                    if a == b {
589                        return None;
590                    }
591
592                    // Collect up all fields that were significantly changed
593                    // i.e., those that contain T in coerce_unsized T -> U
594                    Some((i, a, b, tcx.def_span(f.did)))
595                })
596                .collect::<Vec<_>>();
597
598            if diff_fields.is_empty() {
599                return Err(tcx.dcx().emit_err(errors::CoerceNoField {
600                    span,
601                    trait_name,
602                    note: true,
603                }));
604            } else if diff_fields.len() > 1 {
605                let item = tcx.hir_expect_item(impl_did);
606                let span = if let ItemKind::Impl(hir::Impl { of_trait: Some(of_trait), .. }) =
607                    &item.kind
608                {
609                    of_trait.trait_ref.path.span
610                } else {
611                    tcx.def_span(impl_did)
612                };
613
614                return Err(tcx.dcx().emit_err(errors::CoerceMulti {
615                    span,
616                    trait_name,
617                    number: diff_fields.len(),
618                    fields: diff_fields.iter().map(|(_, _, _, s)| *s).collect::<Vec<_>>().into(),
619                }));
620            }
621
622            let (i, a, b, field_span) = diff_fields[0];
623            let kind = ty::adjustment::CustomCoerceUnsized::Struct(i);
624            (a, b, coerce_unsized_trait, Some(kind), field_span)
625        }
626
627        _ => {
628            return Err(tcx.dcx().emit_err(errors::CoerceUnsizedNonStruct { span, trait_name }));
629        }
630    };
631
632    // Register an obligation for `A: Trait<B>`.
633    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
634    let cause = traits::ObligationCause::misc(span, impl_did);
635    let obligation = Obligation::new(
636        tcx,
637        cause,
638        param_env,
639        ty::TraitRef::new(tcx, trait_def_id, [source, target]),
640    );
641    ocx.register_obligation(obligation);
642    let errors = ocx.evaluate_obligations_error_on_ambiguity();
643
644    if !errors.is_empty() {
645        if is_from_coerce_pointee_derive(tcx, span) {
646            return Err(tcx.dcx().emit_err(errors::CoerceFieldValidity {
647                span,
648                trait_name,
649                ty: trait_ref.self_ty(),
650                field_span,
651                field_ty: source,
652            }));
653        } else {
654            return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
655        }
656    }
657
658    // Finally, resolve all regions.
659    ocx.resolve_regions_and_report_errors(impl_did, param_env, [])?;
660
661    Ok(CoerceUnsizedInfo { custom_kind: kind })
662}
663
664fn infringing_fields_error<'tcx>(
665    tcx: TyCtxt<'tcx>,
666    infringing_tys: impl Iterator<Item = (Span, Ty<'tcx>, InfringingFieldsReason<'tcx>)>,
667    lang_item: LangItem,
668    impl_did: LocalDefId,
669    impl_span: Span,
670) -> ErrorGuaranteed {
671    let trait_did = tcx.require_lang_item(lang_item, impl_span);
672
673    let trait_name = tcx.def_path_str(trait_did);
674
675    // We'll try to suggest constraining type parameters to fulfill the requirements of
676    // their `Copy` implementation.
677    let mut errors: BTreeMap<_, Vec<_>> = Default::default();
678    let mut bounds = ::alloc::vec::Vec::new()vec![];
679
680    let mut seen_tys = FxHashSet::default();
681
682    let mut label_spans = Vec::new();
683
684    for (span, ty, reason) in infringing_tys {
685        // Only report an error once per type.
686        if !seen_tys.insert(ty) {
687            continue;
688        }
689
690        label_spans.push(span);
691
692        match reason {
693            InfringingFieldsReason::Fulfill(fulfillment_errors) => {
694                for error in fulfillment_errors {
695                    let error_predicate = error.obligation.predicate;
696                    // Only note if it's not the root obligation, otherwise it's trivial and
697                    // should be self-explanatory (i.e. a field literally doesn't implement Copy).
698
699                    // FIXME: This error could be more descriptive, especially if the error_predicate
700                    // contains a foreign type or if it's a deeply nested type...
701                    if error_predicate != error.root_obligation.predicate {
702                        errors
703                            .entry((ty.to_string(), error_predicate.to_string()))
704                            .or_default()
705                            .push(error.obligation.cause.span);
706                    }
707                    if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitPredicate {
708                        trait_ref,
709                        polarity: ty::PredicatePolarity::Positive,
710                        ..
711                    })) = error_predicate.kind().skip_binder()
712                    {
713                        let ty = trait_ref.self_ty();
714                        if let ty::Param(_) = ty.kind() {
715                            bounds.push((
716                                ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("{0}", ty)) })format!("{ty}"),
717                                trait_ref.print_trait_sugared().to_string(),
718                                Some(trait_ref.def_id),
719                            ));
720                        }
721                    }
722                }
723            }
724            InfringingFieldsReason::Regions(region_errors) => {
725                for error in region_errors {
726                    let ty = ty.to_string();
727                    match error {
728                        RegionResolutionError::ConcreteFailure(origin, a, b) => {
729                            let predicate = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", b, a))
    })format!("{b}: {a}");
730                            errors
731                                .entry((ty.clone(), predicate.clone()))
732                                .or_default()
733                                .push(origin.span());
734                            if let ty::RegionKind::ReEarlyParam(ebr) = b.kind()
735                                && ebr.is_named()
736                            {
737                                bounds.push((b.to_string(), a.to_string(), None));
738                            }
739                        }
740                        RegionResolutionError::GenericBoundFailure(origin, a, b) => {
741                            let predicate = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", a, b))
    })format!("{a}: {b}");
742                            errors
743                                .entry((ty.clone(), predicate.clone()))
744                                .or_default()
745                                .push(origin.span());
746                            if let infer::region_constraints::GenericKind::Param(_) = a {
747                                bounds.push((a.to_string(), b.to_string(), None));
748                            }
749                        }
750                        _ => continue,
751                    }
752                }
753            }
754        }
755    }
756    let mut notes = Vec::new();
757    for ((ty, error_predicate), spans) in errors {
758        let span: MultiSpan = spans.into();
759        notes.push(errors::ImplForTyRequires {
760            span,
761            error_predicate,
762            trait_name: trait_name.clone(),
763            ty,
764        });
765    }
766
767    let mut err = tcx.dcx().create_err(errors::TraitCannotImplForTy {
768        span: impl_span,
769        trait_name,
770        label_spans,
771        notes,
772    });
773
774    suggest_constraining_type_params(
775        tcx,
776        tcx.hir_get_generics(impl_did).expect("impls always have generics"),
777        &mut err,
778        bounds
779            .iter()
780            .map(|(param, constraint, def_id)| (param.as_str(), constraint.as_str(), *def_id)),
781        None,
782    );
783
784    err.emit()
785}
786
787fn visit_implementation_of_coerce_pointee_validity(
788    checker: &Checker<'_>,
789) -> Result<(), ErrorGuaranteed> {
790    let tcx = checker.tcx;
791    let self_ty = tcx.impl_trait_ref(checker.impl_def_id).instantiate_identity().self_ty();
792    let span = tcx.def_span(checker.impl_def_id);
793    if !tcx.is_builtin_derived(checker.impl_def_id.into()) {
794        return Err(tcx.dcx().emit_err(errors::CoercePointeeNoUserValidityAssertion { span }));
795    }
796    let ty::Adt(def, _args) = self_ty.kind() else {
797        return Err(tcx.dcx().emit_err(errors::CoercePointeeNotConcreteType { span }));
798    };
799    let did = def.did();
800    // Now get a more precise span of the `struct`.
801    let span = tcx.def_span(did);
802    if !def.is_struct() {
803        return Err(tcx
804            .dcx()
805            .emit_err(errors::CoercePointeeNotStruct { span, kind: def.descr().into() }));
806    }
807    if !def.repr().transparent() {
808        return Err(tcx.dcx().emit_err(errors::CoercePointeeNotTransparent { span }));
809    }
810    if def.all_fields().next().is_none() {
811        return Err(tcx.dcx().emit_err(errors::CoercePointeeNoField { span }));
812    }
813    Ok(())
814}