Skip to main content

rustc_hir_analysis/coherence/
builtin.rs

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