Skip to main content

rustc_hir_analysis/coherence/
builtin.rs

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