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().skip_norm_wip().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().skip_norm_wip().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().skip_norm_wip().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().skip_norm_wip().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 struct_vis.greater_than(field.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::NonExhaustive(attr_span)) => {
225            let defn_span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
226            Err(tcx
227                .dcx()
228                .emit_err(errors::ConstParamTyImplOnNonExhaustive { defn_span, attr_span }))
229        }
230        Err(ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(infringing_tys)) => {
231            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
232            Err(infringing_fields_error(
233                tcx,
234                infringing_tys.into_iter().map(|(ty, reason)| (span, ty, reason)),
235                LangItem::ConstParamTy,
236                impl_did,
237                span,
238            ))
239        }
240        Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
241            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
242            Err(tcx.dcx().emit_err(errors::ConstParamTyImplOnUnsized { span }))
243        }
244    }
245}
246
247fn visit_implementation_of_coerce_unsized(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
248    let tcx = checker.tcx;
249    let impl_did = checker.impl_def_id;
250    {
    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:250",
                        "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(250u32),
                        ::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);
251
252    // Just compute this for the side-effects, in particular reporting
253    // errors; other parts of the code may demand it for the info of
254    // course.
255    tcx.ensure_result().coerce_unsized_info(impl_did)
256}
257
258fn is_from_coerce_pointee_derive(tcx: TyCtxt<'_>, span: Span) -> bool {
259    span.ctxt()
260        .outer_expn_data()
261        .macro_def_id
262        .is_some_and(|def_id| tcx.is_diagnostic_item(sym::CoercePointee, def_id))
263}
264
265fn visit_implementation_of_dispatch_from_dyn(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
266    let tcx = checker.tcx;
267    let impl_did = checker.impl_def_id;
268    let trait_ref = checker.impl_header.trait_ref.instantiate_identity().skip_norm_wip();
269    {
    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:269",
                        "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(269u32),
                        ::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);
270
271    let span = tcx.def_span(impl_did);
272    let trait_name = "DispatchFromDyn";
273
274    let source = trait_ref.self_ty();
275    let target = {
276        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));
277
278        trait_ref.args.type_at(1)
279    };
280
281    // Check `CoercePointee` impl is WF -- if not, then there's no reason to report
282    // redundant errors for `DispatchFromDyn`. This is best effort, though.
283    let mut res = Ok(());
284    tcx.for_each_relevant_impl(
285        tcx.require_lang_item(LangItem::CoerceUnsized, span),
286        source,
287        |impl_def_id| {
288            res = res.and(tcx.ensure_result().coerce_unsized_info(impl_def_id));
289        },
290    );
291    res?;
292
293    {
    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:293",
                        "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(293u32),
                        ::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);
294
295    let param_env = tcx.param_env(impl_did);
296
297    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
298    let cause = ObligationCause::misc(span, impl_did);
299
300    // Later parts of the compiler rely on all DispatchFromDyn types to be ABI-compatible with raw
301    // pointers. This is enforced here: we only allow impls for references, raw pointers, and things
302    // that are effectively repr(transparent) newtypes around types that already hav a
303    // DispatchedFromDyn impl. We cannot literally use repr(transparent) on those types since some
304    // of them support an allocator, but we ensure that for the cases where the type implements this
305    // trait, they *do* satisfy the repr(transparent) rules, and then we assume that everything else
306    // in the compiler (in particular, all the call ABI logic) will treat them as repr(transparent)
307    // even if they do not carry that attribute.
308    match (source.kind(), target.kind()) {
309        (&ty::Pat(_, pat_a), &ty::Pat(_, pat_b)) => {
310            if pat_a != pat_b {
311                return Err(tcx.dcx().emit_err(errors::CoerceSamePatKind {
312                    span,
313                    trait_name,
314                    pat_a: pat_a.to_string(),
315                    pat_b: pat_b.to_string(),
316                }));
317            }
318            Ok(())
319        }
320
321        (&ty::Ref(r_a, _, mutbl_a), ty::Ref(r_b, _, mutbl_b))
322            if r_a == *r_b && mutbl_a == *mutbl_b =>
323        {
324            Ok(())
325        }
326        (&ty::RawPtr(_, a_mutbl), &ty::RawPtr(_, b_mutbl)) if a_mutbl == b_mutbl => Ok(()),
327        (&ty::Adt(def_a, args_a), &ty::Adt(def_b, args_b))
328            if def_a.is_struct() && def_b.is_struct() =>
329        {
330            if def_a != def_b {
331                let source_path = tcx.def_path_str(def_a.did());
332                let target_path = tcx.def_path_str(def_b.did());
333                return Err(tcx.dcx().emit_err(errors::CoerceSameStruct {
334                    span,
335                    trait_name,
336                    note: true,
337                    source_path,
338                    target_path,
339                }));
340            }
341
342            if def_a.repr().c() || def_a.repr().packed() {
343                return Err(tcx.dcx().emit_err(errors::DispatchFromDynRepr { span }));
344            }
345
346            let fields = &def_a.non_enum_variant().fields;
347
348            let mut res = Ok(());
349            let coerced_fields = fields
350                .iter_enumerated()
351                .filter_map(|(i, field)| {
352                    // Ignore PhantomData fields
353                    let unnormalized_ty = tcx.type_of(field.did).instantiate_identity();
354                    if tcx
355                        .try_normalize_erasing_regions(
356                            ty::TypingEnv::non_body_analysis(tcx, def_a.did()),
357                            unnormalized_ty,
358                        )
359                        .unwrap_or(unnormalized_ty.skip_norm_wip())
360                        .is_phantom_data()
361                    {
362                        return None;
363                    }
364
365                    let ty_a = field.ty(tcx, args_a);
366                    let ty_b = field.ty(tcx, args_b);
367
368                    // FIXME: We could do normalization here, but is it really worth it?
369                    if ty_a == ty_b {
370                        // Allow 1-ZSTs that don't mention type params.
371                        //
372                        // Allowing type params here would allow us to possibly transmute
373                        // between ZSTs, which may be used to create library unsoundness.
374                        if let Ok(layout) =
375                            tcx.layout_of(infcx.typing_env(param_env).as_query_input(ty_a))
376                            && layout.is_1zst()
377                            && !ty_a.has_non_region_param()
378                        {
379                            // ignore 1-ZST fields
380                            return None;
381                        }
382
383                        res = Err(tcx.dcx().emit_err(errors::DispatchFromDynZST {
384                            span,
385                            name: field.ident(tcx),
386                            ty: ty_a,
387                        }));
388
389                        None
390                    } else {
391                        Some((i, ty_a, ty_b, tcx.def_span(field.did)))
392                    }
393                })
394                .collect::<Vec<_>>();
395            res?;
396
397            if coerced_fields.is_empty() {
398                return Err(tcx.dcx().emit_err(errors::CoerceNoField {
399                    span,
400                    trait_name,
401                    note: true,
402                }));
403            } else if let &[(_, ty_a, ty_b, field_span)] = &coerced_fields[..] {
404                let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
405                ocx.register_obligation(Obligation::new(
406                    tcx,
407                    cause.clone(),
408                    param_env,
409                    ty::TraitRef::new(tcx, trait_ref.def_id, [ty_a, ty_b]),
410                ));
411                let errors = ocx.evaluate_obligations_error_on_ambiguity();
412                if !errors.is_empty() {
413                    if is_from_coerce_pointee_derive(tcx, span) {
414                        return Err(tcx.dcx().emit_err(errors::CoerceFieldValidity {
415                            span,
416                            trait_name,
417                            ty: trait_ref.self_ty(),
418                            field_span,
419                            field_ty: ty_a,
420                        }));
421                    } else {
422                        return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
423                    }
424                }
425
426                // Finally, resolve all regions.
427                ocx.resolve_regions_and_report_errors(impl_did, param_env, [])?;
428
429                Ok(())
430            } else {
431                return Err(tcx.dcx().emit_err(errors::CoerceMulti {
432                    span,
433                    trait_name,
434                    number: coerced_fields.len(),
435                    fields: coerced_fields.iter().map(|(_, _, _, s)| *s).collect::<Vec<_>>().into(),
436                }));
437            }
438        }
439        _ => Err(tcx.dcx().emit_err(errors::CoerceUnsizedNonStruct { span, trait_name })),
440    }
441}
442
443pub(crate) fn coerce_unsized_info<'tcx>(
444    tcx: TyCtxt<'tcx>,
445    impl_did: LocalDefId,
446) -> Result<CoerceUnsizedInfo, ErrorGuaranteed> {
447    {
    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:447",
                        "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(447u32),
                        ::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);
448    let span = tcx.def_span(impl_did);
449    let trait_name = "CoerceUnsized";
450
451    let coerce_unsized_trait = tcx.require_lang_item(LangItem::CoerceUnsized, span);
452    let unsize_trait = tcx.require_lang_item(LangItem::Unsize, span);
453
454    let source = tcx.type_of(impl_did).instantiate_identity().skip_norm_wip();
455    let trait_ref = tcx.impl_trait_ref(impl_did).instantiate_identity().skip_norm_wip();
456
457    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);
458    let target = trait_ref.args.type_at(1);
459    {
    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:459",
                        "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(459u32),
                        ::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);
460
461    let param_env = tcx.param_env(impl_did);
462    if !!source.has_escaping_bound_vars() {
    ::core::panicking::panic("assertion failed: !source.has_escaping_bound_vars()")
};assert!(!source.has_escaping_bound_vars());
463
464    {
    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:464",
                        "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(464u32),
                        ::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);
465
466    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
467    let cause = ObligationCause::misc(span, impl_did);
468    let check_mutbl = |mt_a: ty::TypeAndMut<'tcx>,
469                       mt_b: ty::TypeAndMut<'tcx>,
470                       mk_ptr: &dyn Fn(Ty<'tcx>) -> Ty<'tcx>| {
471        if mt_a.mutbl < mt_b.mutbl {
472            infcx
473                .err_ctxt()
474                .report_mismatched_types(
475                    &cause,
476                    param_env,
477                    mk_ptr(mt_b.ty),
478                    target,
479                    ty::error::TypeError::Mutability,
480                )
481                .emit();
482        }
483        (mt_a.ty, mt_b.ty, unsize_trait, None, span)
484    };
485    let (source, target, trait_def_id, kind, field_span) = match (source.kind(), target.kind()) {
486        (&ty::Pat(ty_a, pat_a), &ty::Pat(ty_b, pat_b)) => {
487            if pat_a != pat_b {
488                return Err(tcx.dcx().emit_err(errors::CoerceSamePatKind {
489                    span,
490                    trait_name,
491                    pat_a: pat_a.to_string(),
492                    pat_b: pat_b.to_string(),
493                }));
494            }
495            (ty_a, ty_b, coerce_unsized_trait, None, span)
496        }
497
498        (&ty::Ref(r_a, ty_a, mutbl_a), &ty::Ref(r_b, ty_b, mutbl_b)) => {
499            infcx.sub_regions(
500                SubregionOrigin::RelateObjectBound(span),
501                r_b,
502                r_a,
503                ty::VisibleForLeakCheck::Yes,
504            );
505            let mt_a = ty::TypeAndMut { ty: ty_a, mutbl: mutbl_a };
506            let mt_b = ty::TypeAndMut { ty: ty_b, mutbl: mutbl_b };
507            check_mutbl(mt_a, mt_b, &|ty| Ty::new_imm_ref(tcx, r_b, ty))
508        }
509
510        (&ty::Ref(_, ty_a, mutbl_a), &ty::RawPtr(ty_b, mutbl_b))
511        | (&ty::RawPtr(ty_a, mutbl_a), &ty::RawPtr(ty_b, mutbl_b)) => {
512            let mt_a = ty::TypeAndMut { ty: ty_a, mutbl: mutbl_a };
513            let mt_b = ty::TypeAndMut { ty: ty_b, mutbl: mutbl_b };
514            check_mutbl(mt_a, mt_b, &|ty| Ty::new_imm_ptr(tcx, ty))
515        }
516
517        (&ty::Adt(def_a, args_a), &ty::Adt(def_b, args_b))
518            if def_a.is_struct() && def_b.is_struct() =>
519        {
520            if def_a != def_b {
521                let source_path = tcx.def_path_str(def_a.did());
522                let target_path = tcx.def_path_str(def_b.did());
523                return Err(tcx.dcx().emit_err(errors::CoerceSameStruct {
524                    span,
525                    trait_name,
526                    note: true,
527                    source_path,
528                    target_path,
529                }));
530            }
531
532            // Here we are considering a case of converting
533            // `S<P0...Pn>` to `S<Q0...Qn>`. As an example, let's imagine a struct `Foo<T, U>`,
534            // which acts like a pointer to `U`, but carries along some extra data of type `T`:
535            //
536            //     struct Foo<T, U> {
537            //         extra: T,
538            //         ptr: *mut U,
539            //     }
540            //
541            // We might have an impl that allows (e.g.) `Foo<T, [i32; 3]>` to be unsized
542            // to `Foo<T, [i32]>`. That impl would look like:
543            //
544            //   impl<T, U: Unsize<V>, V> CoerceUnsized<Foo<T, V>> for Foo<T, U> {}
545            //
546            // Here `U = [i32; 3]` and `V = [i32]`. At runtime,
547            // when this coercion occurs, we would be changing the
548            // field `ptr` from a thin pointer of type `*mut [i32;
549            // 3]` to a wide pointer of type `*mut [i32]` (with
550            // extra data `3`). **The purpose of this check is to
551            // make sure that we know how to do this conversion.**
552            //
553            // To check if this impl is legal, we would walk down
554            // the fields of `Foo` and consider their types with
555            // both generic parameters. We are looking to find that
556            // exactly one (non-phantom) field has changed its
557            // type, which we will expect to be the pointer that
558            // is becoming fat (we could probably generalize this
559            // to multiple thin pointers of the same type becoming
560            // fat, but we don't). In this case:
561            //
562            // - `extra` has type `T` before and type `T` after
563            // - `ptr` has type `*mut U` before and type `*mut V` after
564            //
565            // Since just one field changed, we would then check
566            // that `*mut U: CoerceUnsized<*mut V>` is implemented
567            // (in other words, that we know how to do this
568            // conversion). This will work out because `U:
569            // Unsize<V>`, and we have a builtin rule that `*mut
570            // U` can be coerced to `*mut V` if `U: Unsize<V>`.
571            let fields = &def_a.non_enum_variant().fields;
572            let diff_fields = fields
573                .iter_enumerated()
574                .filter_map(|(i, f)| {
575                    let (a, b) = (f.ty(tcx, args_a), f.ty(tcx, args_b));
576
577                    // Ignore PhantomData fields
578                    let unnormalized_ty = tcx.type_of(f.did).instantiate_identity();
579                    if tcx
580                        .try_normalize_erasing_regions(
581                            ty::TypingEnv::non_body_analysis(tcx, def_a.did()),
582                            unnormalized_ty,
583                        )
584                        .unwrap_or(unnormalized_ty.skip_norm_wip())
585                        .is_phantom_data()
586                    {
587                        return None;
588                    }
589
590                    // Ignore fields that aren't changed; it may
591                    // be that we could get away with subtyping or
592                    // something more accepting, but we use
593                    // equality because we want to be able to
594                    // perform this check without computing
595                    // variance or constraining opaque types' hidden types.
596                    // (This is because we may have to evaluate constraint
597                    // expressions in the course of execution.)
598                    // See e.g., #41936.
599                    if a == b {
600                        return None;
601                    }
602
603                    // Collect up all fields that were significantly changed
604                    // i.e., those that contain T in coerce_unsized T -> U
605                    Some((i, a, b, tcx.def_span(f.did)))
606                })
607                .collect::<Vec<_>>();
608
609            if diff_fields.is_empty() {
610                return Err(tcx.dcx().emit_err(errors::CoerceNoField {
611                    span,
612                    trait_name,
613                    note: true,
614                }));
615            } else if diff_fields.len() > 1 {
616                let item = tcx.hir_expect_item(impl_did);
617                let span = if let ItemKind::Impl(hir::Impl { of_trait: Some(of_trait), .. }) =
618                    &item.kind
619                {
620                    of_trait.trait_ref.path.span
621                } else {
622                    tcx.def_span(impl_did)
623                };
624
625                return Err(tcx.dcx().emit_err(errors::CoerceMulti {
626                    span,
627                    trait_name,
628                    number: diff_fields.len(),
629                    fields: diff_fields.iter().map(|(_, _, _, s)| *s).collect::<Vec<_>>().into(),
630                }));
631            }
632
633            let (i, a, b, field_span) = diff_fields[0];
634            let kind = ty::adjustment::CustomCoerceUnsized::Struct(i);
635            (a, b, coerce_unsized_trait, Some(kind), field_span)
636        }
637
638        _ => {
639            return Err(tcx.dcx().emit_err(errors::CoerceUnsizedNonStruct { span, trait_name }));
640        }
641    };
642
643    // Register an obligation for `A: Trait<B>`.
644    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
645    let cause = traits::ObligationCause::misc(span, impl_did);
646    let obligation = Obligation::new(
647        tcx,
648        cause,
649        param_env,
650        ty::TraitRef::new(tcx, trait_def_id, [source, target]),
651    );
652    ocx.register_obligation(obligation);
653    let errors = ocx.evaluate_obligations_error_on_ambiguity();
654
655    if !errors.is_empty() {
656        if is_from_coerce_pointee_derive(tcx, span) {
657            return Err(tcx.dcx().emit_err(errors::CoerceFieldValidity {
658                span,
659                trait_name,
660                ty: trait_ref.self_ty(),
661                field_span,
662                field_ty: source,
663            }));
664        } else {
665            return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
666        }
667    }
668
669    // Finally, resolve all regions.
670    ocx.resolve_regions_and_report_errors(impl_did, param_env, [])?;
671
672    Ok(CoerceUnsizedInfo { custom_kind: kind })
673}
674
675fn infringing_fields_error<'tcx>(
676    tcx: TyCtxt<'tcx>,
677    infringing_tys: impl Iterator<Item = (Span, Ty<'tcx>, InfringingFieldsReason<'tcx>)>,
678    lang_item: LangItem,
679    impl_did: LocalDefId,
680    impl_span: Span,
681) -> ErrorGuaranteed {
682    let trait_did = tcx.require_lang_item(lang_item, impl_span);
683
684    let trait_name = tcx.def_path_str(trait_did);
685
686    // We'll try to suggest constraining type parameters to fulfill the requirements of
687    // their `Copy` implementation.
688    let mut errors: BTreeMap<_, Vec<_>> = Default::default();
689    let mut bounds = ::alloc::vec::Vec::new()vec![];
690
691    let mut seen_tys = FxHashSet::default();
692
693    let mut label_spans = Vec::new();
694
695    for (span, ty, reason) in infringing_tys {
696        // Only report an error once per type.
697        if !seen_tys.insert(ty) {
698            continue;
699        }
700
701        label_spans.push(span);
702
703        match reason {
704            InfringingFieldsReason::Fulfill(fulfillment_errors) => {
705                for error in fulfillment_errors {
706                    let error_predicate = error.obligation.predicate;
707                    // Only note if it's not the root obligation, otherwise it's trivial and
708                    // should be self-explanatory (i.e. a field literally doesn't implement Copy).
709
710                    // FIXME: This error could be more descriptive, especially if the error_predicate
711                    // contains a foreign type or if it's a deeply nested type...
712                    if error_predicate != error.root_obligation.predicate {
713                        errors
714                            .entry((ty.to_string(), error_predicate.to_string()))
715                            .or_default()
716                            .push(error.obligation.cause.span);
717                    }
718                    if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitPredicate {
719                        trait_ref,
720                        polarity: ty::PredicatePolarity::Positive,
721                        ..
722                    })) = error_predicate.kind().skip_binder()
723                    {
724                        let ty = trait_ref.self_ty();
725                        if let ty::Param(_) = ty.kind() {
726                            bounds.push((
727                                ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("{0}", ty)) })format!("{ty}"),
728                                trait_ref.print_trait_sugared().to_string(),
729                                Some(trait_ref.def_id),
730                            ));
731                        }
732                    }
733                }
734            }
735            InfringingFieldsReason::Regions(region_errors) => {
736                for error in region_errors {
737                    let ty = ty.to_string();
738                    match error {
739                        RegionResolutionError::ConcreteFailure(origin, a, b) => {
740                            let predicate = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", b, a))
    })format!("{b}: {a}");
741                            errors
742                                .entry((ty.clone(), predicate.clone()))
743                                .or_default()
744                                .push(origin.span());
745                            if let ty::RegionKind::ReEarlyParam(ebr) = b.kind()
746                                && ebr.is_named()
747                            {
748                                bounds.push((b.to_string(), a.to_string(), None));
749                            }
750                        }
751                        RegionResolutionError::GenericBoundFailure(origin, a, b) => {
752                            let predicate = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", a, b))
    })format!("{a}: {b}");
753                            errors
754                                .entry((ty.clone(), predicate.clone()))
755                                .or_default()
756                                .push(origin.span());
757                            if let infer::region_constraints::GenericKind::Param(_) = a {
758                                bounds.push((a.to_string(), b.to_string(), None));
759                            }
760                        }
761                        _ => continue,
762                    }
763                }
764            }
765        }
766    }
767    let mut notes = Vec::new();
768    for ((ty, error_predicate), spans) in errors {
769        let span: MultiSpan = spans.into();
770        notes.push(errors::ImplForTyRequires {
771            span,
772            error_predicate,
773            trait_name: trait_name.clone(),
774            ty,
775        });
776    }
777
778    let mut err = tcx.dcx().create_err(errors::TraitCannotImplForTy {
779        span: impl_span,
780        trait_name,
781        label_spans,
782        notes,
783    });
784
785    suggest_constraining_type_params(
786        tcx,
787        tcx.hir_get_generics(impl_did).expect("impls always have generics"),
788        &mut err,
789        bounds
790            .iter()
791            .map(|(param, constraint, def_id)| (param.as_str(), constraint.as_str(), *def_id)),
792        None,
793    );
794
795    err.emit()
796}
797
798fn visit_implementation_of_coerce_pointee_validity(
799    checker: &Checker<'_>,
800) -> Result<(), ErrorGuaranteed> {
801    let tcx = checker.tcx;
802    let self_ty =
803        tcx.impl_trait_ref(checker.impl_def_id).instantiate_identity().skip_norm_wip().self_ty();
804    let span = tcx.def_span(checker.impl_def_id);
805    if !tcx.is_builtin_derived(checker.impl_def_id.into()) {
806        return Err(tcx.dcx().emit_err(errors::CoercePointeeNoUserValidityAssertion { span }));
807    }
808    let ty::Adt(def, _args) = self_ty.kind() else {
809        return Err(tcx.dcx().emit_err(errors::CoercePointeeNotConcreteType { span }));
810    };
811    let did = def.did();
812    // Now get a more precise span of the `struct`.
813    let span = tcx.def_span(did);
814    if !def.is_struct() {
815        return Err(tcx
816            .dcx()
817            .emit_err(errors::CoercePointeeNotStruct { span, kind: def.descr().into() }));
818    }
819    if !def.repr().transparent() {
820        return Err(tcx.dcx().emit_err(errors::CoercePointeeNotTransparent { span }));
821    }
822    if def.all_fields().next().is_none() {
823        return Err(tcx.dcx().emit_err(errors::CoercePointeeNoField { span }));
824    }
825    Ok(())
826}