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(SubregionOrigin::RelateObjectBound(span), r_b, r_a);
500            let mt_a = ty::TypeAndMut { ty: ty_a, mutbl: mutbl_a };
501            let mt_b = ty::TypeAndMut { ty: ty_b, mutbl: mutbl_b };
502            check_mutbl(mt_a, mt_b, &|ty| Ty::new_imm_ref(tcx, r_b, ty))
503        }
504
505        (&ty::Ref(_, ty_a, mutbl_a), &ty::RawPtr(ty_b, mutbl_b))
506        | (&ty::RawPtr(ty_a, mutbl_a), &ty::RawPtr(ty_b, mutbl_b)) => {
507            let mt_a = ty::TypeAndMut { ty: ty_a, mutbl: mutbl_a };
508            let mt_b = ty::TypeAndMut { ty: ty_b, mutbl: mutbl_b };
509            check_mutbl(mt_a, mt_b, &|ty| Ty::new_imm_ptr(tcx, ty))
510        }
511
512        (&ty::Adt(def_a, args_a), &ty::Adt(def_b, args_b))
513            if def_a.is_struct() && def_b.is_struct() =>
514        {
515            if def_a != def_b {
516                let source_path = tcx.def_path_str(def_a.did());
517                let target_path = tcx.def_path_str(def_b.did());
518                return Err(tcx.dcx().emit_err(errors::CoerceSameStruct {
519                    span,
520                    trait_name,
521                    note: true,
522                    source_path,
523                    target_path,
524                }));
525            }
526
527            // Here we are considering a case of converting
528            // `S<P0...Pn>` to `S<Q0...Qn>`. As an example, let's imagine a struct `Foo<T, U>`,
529            // which acts like a pointer to `U`, but carries along some extra data of type `T`:
530            //
531            //     struct Foo<T, U> {
532            //         extra: T,
533            //         ptr: *mut U,
534            //     }
535            //
536            // We might have an impl that allows (e.g.) `Foo<T, [i32; 3]>` to be unsized
537            // to `Foo<T, [i32]>`. That impl would look like:
538            //
539            //   impl<T, U: Unsize<V>, V> CoerceUnsized<Foo<T, V>> for Foo<T, U> {}
540            //
541            // Here `U = [i32; 3]` and `V = [i32]`. At runtime,
542            // when this coercion occurs, we would be changing the
543            // field `ptr` from a thin pointer of type `*mut [i32;
544            // 3]` to a wide pointer of type `*mut [i32]` (with
545            // extra data `3`). **The purpose of this check is to
546            // make sure that we know how to do this conversion.**
547            //
548            // To check if this impl is legal, we would walk down
549            // the fields of `Foo` and consider their types with
550            // both generic parameters. We are looking to find that
551            // exactly one (non-phantom) field has changed its
552            // type, which we will expect to be the pointer that
553            // is becoming fat (we could probably generalize this
554            // to multiple thin pointers of the same type becoming
555            // fat, but we don't). In this case:
556            //
557            // - `extra` has type `T` before and type `T` after
558            // - `ptr` has type `*mut U` before and type `*mut V` after
559            //
560            // Since just one field changed, we would then check
561            // that `*mut U: CoerceUnsized<*mut V>` is implemented
562            // (in other words, that we know how to do this
563            // conversion). This will work out because `U:
564            // Unsize<V>`, and we have a builtin rule that `*mut
565            // U` can be coerced to `*mut V` if `U: Unsize<V>`.
566            let fields = &def_a.non_enum_variant().fields;
567            let diff_fields = fields
568                .iter_enumerated()
569                .filter_map(|(i, f)| {
570                    let (a, b) = (f.ty(tcx, args_a), f.ty(tcx, args_b));
571
572                    // Ignore PhantomData fields
573                    let unnormalized_ty = tcx.type_of(f.did).instantiate_identity();
574                    if tcx
575                        .try_normalize_erasing_regions(
576                            ty::TypingEnv::non_body_analysis(tcx, def_a.did()),
577                            unnormalized_ty,
578                        )
579                        .unwrap_or(unnormalized_ty.skip_norm_wip())
580                        .is_phantom_data()
581                    {
582                        return None;
583                    }
584
585                    // Ignore fields that aren't changed; it may
586                    // be that we could get away with subtyping or
587                    // something more accepting, but we use
588                    // equality because we want to be able to
589                    // perform this check without computing
590                    // variance or constraining opaque types' hidden types.
591                    // (This is because we may have to evaluate constraint
592                    // expressions in the course of execution.)
593                    // See e.g., #41936.
594                    if a == b {
595                        return None;
596                    }
597
598                    // Collect up all fields that were significantly changed
599                    // i.e., those that contain T in coerce_unsized T -> U
600                    Some((i, a, b, tcx.def_span(f.did)))
601                })
602                .collect::<Vec<_>>();
603
604            if diff_fields.is_empty() {
605                return Err(tcx.dcx().emit_err(errors::CoerceNoField {
606                    span,
607                    trait_name,
608                    note: true,
609                }));
610            } else if diff_fields.len() > 1 {
611                let item = tcx.hir_expect_item(impl_did);
612                let span = if let ItemKind::Impl(hir::Impl { of_trait: Some(of_trait), .. }) =
613                    &item.kind
614                {
615                    of_trait.trait_ref.path.span
616                } else {
617                    tcx.def_span(impl_did)
618                };
619
620                return Err(tcx.dcx().emit_err(errors::CoerceMulti {
621                    span,
622                    trait_name,
623                    number: diff_fields.len(),
624                    fields: diff_fields.iter().map(|(_, _, _, s)| *s).collect::<Vec<_>>().into(),
625                }));
626            }
627
628            let (i, a, b, field_span) = diff_fields[0];
629            let kind = ty::adjustment::CustomCoerceUnsized::Struct(i);
630            (a, b, coerce_unsized_trait, Some(kind), field_span)
631        }
632
633        _ => {
634            return Err(tcx.dcx().emit_err(errors::CoerceUnsizedNonStruct { span, trait_name }));
635        }
636    };
637
638    // Register an obligation for `A: Trait<B>`.
639    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
640    let cause = traits::ObligationCause::misc(span, impl_did);
641    let obligation = Obligation::new(
642        tcx,
643        cause,
644        param_env,
645        ty::TraitRef::new(tcx, trait_def_id, [source, target]),
646    );
647    ocx.register_obligation(obligation);
648    let errors = ocx.evaluate_obligations_error_on_ambiguity();
649
650    if !errors.is_empty() {
651        if is_from_coerce_pointee_derive(tcx, span) {
652            return Err(tcx.dcx().emit_err(errors::CoerceFieldValidity {
653                span,
654                trait_name,
655                ty: trait_ref.self_ty(),
656                field_span,
657                field_ty: source,
658            }));
659        } else {
660            return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
661        }
662    }
663
664    // Finally, resolve all regions.
665    ocx.resolve_regions_and_report_errors(impl_did, param_env, [])?;
666
667    Ok(CoerceUnsizedInfo { custom_kind: kind })
668}
669
670fn infringing_fields_error<'tcx>(
671    tcx: TyCtxt<'tcx>,
672    infringing_tys: impl Iterator<Item = (Span, Ty<'tcx>, InfringingFieldsReason<'tcx>)>,
673    lang_item: LangItem,
674    impl_did: LocalDefId,
675    impl_span: Span,
676) -> ErrorGuaranteed {
677    let trait_did = tcx.require_lang_item(lang_item, impl_span);
678
679    let trait_name = tcx.def_path_str(trait_did);
680
681    // We'll try to suggest constraining type parameters to fulfill the requirements of
682    // their `Copy` implementation.
683    let mut errors: BTreeMap<_, Vec<_>> = Default::default();
684    let mut bounds = ::alloc::vec::Vec::new()vec![];
685
686    let mut seen_tys = FxHashSet::default();
687
688    let mut label_spans = Vec::new();
689
690    for (span, ty, reason) in infringing_tys {
691        // Only report an error once per type.
692        if !seen_tys.insert(ty) {
693            continue;
694        }
695
696        label_spans.push(span);
697
698        match reason {
699            InfringingFieldsReason::Fulfill(fulfillment_errors) => {
700                for error in fulfillment_errors {
701                    let error_predicate = error.obligation.predicate;
702                    // Only note if it's not the root obligation, otherwise it's trivial and
703                    // should be self-explanatory (i.e. a field literally doesn't implement Copy).
704
705                    // FIXME: This error could be more descriptive, especially if the error_predicate
706                    // contains a foreign type or if it's a deeply nested type...
707                    if error_predicate != error.root_obligation.predicate {
708                        errors
709                            .entry((ty.to_string(), error_predicate.to_string()))
710                            .or_default()
711                            .push(error.obligation.cause.span);
712                    }
713                    if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitPredicate {
714                        trait_ref,
715                        polarity: ty::PredicatePolarity::Positive,
716                        ..
717                    })) = error_predicate.kind().skip_binder()
718                    {
719                        let ty = trait_ref.self_ty();
720                        if let ty::Param(_) = ty.kind() {
721                            bounds.push((
722                                ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("{0}", ty)) })format!("{ty}"),
723                                trait_ref.print_trait_sugared().to_string(),
724                                Some(trait_ref.def_id),
725                            ));
726                        }
727                    }
728                }
729            }
730            InfringingFieldsReason::Regions(region_errors) => {
731                for error in region_errors {
732                    let ty = ty.to_string();
733                    match error {
734                        RegionResolutionError::ConcreteFailure(origin, a, b) => {
735                            let predicate = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", b, a))
    })format!("{b}: {a}");
736                            errors
737                                .entry((ty.clone(), predicate.clone()))
738                                .or_default()
739                                .push(origin.span());
740                            if let ty::RegionKind::ReEarlyParam(ebr) = b.kind()
741                                && ebr.is_named()
742                            {
743                                bounds.push((b.to_string(), a.to_string(), None));
744                            }
745                        }
746                        RegionResolutionError::GenericBoundFailure(origin, a, b) => {
747                            let predicate = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", a, b))
    })format!("{a}: {b}");
748                            errors
749                                .entry((ty.clone(), predicate.clone()))
750                                .or_default()
751                                .push(origin.span());
752                            if let infer::region_constraints::GenericKind::Param(_) = a {
753                                bounds.push((a.to_string(), b.to_string(), None));
754                            }
755                        }
756                        _ => continue,
757                    }
758                }
759            }
760        }
761    }
762    let mut notes = Vec::new();
763    for ((ty, error_predicate), spans) in errors {
764        let span: MultiSpan = spans.into();
765        notes.push(errors::ImplForTyRequires {
766            span,
767            error_predicate,
768            trait_name: trait_name.clone(),
769            ty,
770        });
771    }
772
773    let mut err = tcx.dcx().create_err(errors::TraitCannotImplForTy {
774        span: impl_span,
775        trait_name,
776        label_spans,
777        notes,
778    });
779
780    suggest_constraining_type_params(
781        tcx,
782        tcx.hir_get_generics(impl_did).expect("impls always have generics"),
783        &mut err,
784        bounds
785            .iter()
786            .map(|(param, constraint, def_id)| (param.as_str(), constraint.as_str(), *def_id)),
787        None,
788    );
789
790    err.emit()
791}
792
793fn visit_implementation_of_coerce_pointee_validity(
794    checker: &Checker<'_>,
795) -> Result<(), ErrorGuaranteed> {
796    let tcx = checker.tcx;
797    let self_ty =
798        tcx.impl_trait_ref(checker.impl_def_id).instantiate_identity().skip_norm_wip().self_ty();
799    let span = tcx.def_span(checker.impl_def_id);
800    if !tcx.is_builtin_derived(checker.impl_def_id.into()) {
801        return Err(tcx.dcx().emit_err(errors::CoercePointeeNoUserValidityAssertion { span }));
802    }
803    let ty::Adt(def, _args) = self_ty.kind() else {
804        return Err(tcx.dcx().emit_err(errors::CoercePointeeNotConcreteType { span }));
805    };
806    let did = def.did();
807    // Now get a more precise span of the `struct`.
808    let span = tcx.def_span(did);
809    if !def.is_struct() {
810        return Err(tcx
811            .dcx()
812            .emit_err(errors::CoercePointeeNotStruct { span, kind: def.descr().into() }));
813    }
814    if !def.repr().transparent() {
815        return Err(tcx.dcx().emit_err(errors::CoercePointeeNotTransparent { span }));
816    }
817    if def.all_fields().next().is_none() {
818        return Err(tcx.dcx().emit_err(errors::CoercePointeeNoField { span }));
819    }
820    Ok(())
821}