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::attrs::lang_items::LangItem;
11use rustc_hir::def_id::{DefId, LocalDefId};
12use rustc_infer::infer::{self, InferCtxt, RegionResolutionError, SubregionOrigin, TyCtxtInferExt};
13use rustc_infer::traits::{Obligation, TraitErrors};
14use rustc_middle::ty::adjustment::CoerceUnsizedInfo;
15use rustc_middle::ty::print::PrintTraitRefExt as _;
16use rustc_middle::ty::{
17    self, Ty, TyCtxt, TypeVisitableExt, TypingMode, Unnormalized, suggest_constraining_type_params,
18};
19use rustc_span::{DUMMY_SP, Ident, Span, Symbol, 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::diagnostics;
29
30mod coerce_shared;
31
32pub(super) fn check_trait<'tcx>(
33    tcx: TyCtxt<'tcx>,
34    trait_def_id: DefId,
35    impl_def_id: LocalDefId,
36    impl_header: ty::ImplTraitHeader<'tcx>,
37) -> Result<(), ErrorGuaranteed> {
38    let checker = Checker { tcx, impl_def_id, impl_header };
39    match tcx.as_lang_item(trait_def_id) {
40        Some(LangItem::Drop) => visit_implementation_of_drop(&checker),
41        Some(LangItem::AsyncDrop) => visit_implementation_of_drop(&checker),
42        Some(LangItem::Copy) => visit_implementation_of_copy(&checker),
43        Some(LangItem::Unpin) => visit_implementation_of_unpin(&checker),
44        Some(LangItem::ConstParamTy) => visit_implementation_of_const_param_ty(&checker),
45        Some(LangItem::CoerceUnsized) => visit_implementation_of_coerce_unsized(&checker),
46        Some(LangItem::Reborrow) => visit_implementation_of_reborrow(&checker),
47        Some(LangItem::CoerceShared) => visit_implementation_of_coerce_shared(&checker),
48        Some(LangItem::DispatchFromDyn) => visit_implementation_of_dispatch_from_dyn(&checker),
49        Some(LangItem::CoercePointeeValidated) => {
50            visit_implementation_of_coerce_pointee_validity(&checker)
51        }
52        _ => Ok(()),
53    }
54}
55
56struct Checker<'tcx> {
57    tcx: TyCtxt<'tcx>,
58    impl_def_id: LocalDefId,
59    impl_header: ty::ImplTraitHeader<'tcx>,
60}
61
62fn visit_implementation_of_drop(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
63    let tcx = checker.tcx;
64    let impl_did = checker.impl_def_id;
65    // Destructors only work on local ADT types.
66    match checker.impl_header.trait_ref.instantiate_identity().skip_norm_wip().self_ty().kind() {
67        ty::Adt(def, _) if def.did().is_local() => return Ok(()),
68        ty::Error(_) => return Ok(()),
69        _ => {}
70    }
71
72    let impl_ = tcx.hir_expect_item(impl_did).expect_impl();
73
74    Err(tcx.dcx().emit_err(diagnostics::DropImplOnWrongItem {
75        span: impl_.self_ty.span,
76        trait_: tcx.item_name(checker.impl_header.trait_ref.skip_binder().def_id),
77    }))
78}
79
80fn visit_implementation_of_copy(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
81    let tcx = checker.tcx;
82    let impl_header = checker.impl_header;
83    let impl_did = checker.impl_def_id;
84    {
    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:84",
                        "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(84u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("visit_implementation_of_copy: impl_did={0:?}",
                                                    impl_did) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("visit_implementation_of_copy: impl_did={:?}", impl_did);
85
86    let self_type = impl_header.trait_ref.instantiate_identity().skip_norm_wip().self_ty();
87    {
    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:87",
                        "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(87u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("visit_implementation_of_copy: self_type={0:?} (bound)",
                                                    self_type) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("visit_implementation_of_copy: self_type={:?} (bound)", self_type);
88
89    let param_env = tcx.param_env(impl_did);
90    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());
91
92    {
    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:92",
                        "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(92u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("visit_implementation_of_copy: self_type={0:?} (free)",
                                                    self_type) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("visit_implementation_of_copy: self_type={:?} (free)", self_type);
93
94    if let ty::ImplPolarity::Negative = impl_header.polarity {
95        return Ok(());
96    }
97
98    let cause = traits::ObligationCause::misc(DUMMY_SP, impl_did);
99    match type_allowed_to_implement_copy(tcx, param_env, self_type, cause, impl_header.safety) {
100        Ok(()) => Ok(()),
101        Err(CopyImplementationError::InfringingFields(fields)) => {
102            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
103            Err(infringing_fields_error(
104                tcx,
105                fields.into_iter().map(|(field, ty, reason)| (tcx.def_span(field.did), ty, reason)),
106                LangItem::Copy,
107                impl_did,
108                span,
109            ))
110        }
111        Err(CopyImplementationError::NotAnAdt) => {
112            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
113            Err(tcx.dcx().emit_err(diagnostics::CopyImplOnNonAdt { span }))
114        }
115        Err(CopyImplementationError::HasDestructor(did)) => {
116            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
117            let impl_ = tcx.def_span(did);
118            Err(tcx.dcx().emit_err(diagnostics::CopyImplOnTypeWithDtor { span, impl_ }))
119        }
120        Err(CopyImplementationError::HasUnsafeFields) => {
121            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
122            Err(tcx
123                .dcx()
124                .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)))
125        }
126    }
127}
128
129fn visit_implementation_of_unpin(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
130    let tcx = checker.tcx;
131    let impl_header = checker.impl_header;
132    let impl_did = checker.impl_def_id;
133    {
    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:133",
                        "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(133u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("visit_implementation_of_unpin: impl_did={0:?}",
                                                    impl_did) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("visit_implementation_of_unpin: impl_did={:?}", impl_did);
134
135    let self_type = impl_header.trait_ref.instantiate_identity().skip_norm_wip().self_ty();
136    {
    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:136",
                        "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(136u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("visit_implementation_of_unpin: self_type={0:?}",
                                                    self_type) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("visit_implementation_of_unpin: self_type={:?}", self_type);
137
138    let span = tcx.def_span(impl_did);
139
140    if tcx.features().pin_ergonomics() {
141        match self_type.kind() {
142            // Soundness concerns: a type `T` annotated with `#[pin_v2]` is allowed to project
143            // `Pin<&mut T>` to its field `Pin<&mut U>` safely (even if `U: !Unpin`).
144            // If `T` is allowed to impl `Unpin` manually (note that `Unpin` is a safe trait,
145            // which cannot carry safety properties), then `&mut U` could be obtained from
146            // `&mut T` that dereferenced by `Pin<&mut T>`, which breaks the safety contract of
147            // `Pin<&mut U>` for `U: !Unpin`.
148            ty::Adt(adt, _) if adt.is_pin_project() => {
149                return Err(tcx.dcx().emit_err(crate::diagnostics::ImplUnpinForPinProjectedType {
150                    span,
151                    adt_span: tcx.def_span(adt.did()),
152                    adt_name: tcx.item_name(adt.did()),
153                }));
154            }
155            ty::Adt(_, _) => {}
156            _ => {
157                return Err(tcx.dcx().span_delayed_bug(span, "impl of `Unpin` for a non-adt type"));
158            }
159        };
160    }
161    Ok(())
162}
163
164fn visit_implementation_of_const_param_ty(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
165    let tcx = checker.tcx;
166    let header = checker.impl_header;
167    let impl_did = checker.impl_def_id;
168    let self_type = header.trait_ref.instantiate_identity().skip_norm_wip().self_ty();
169    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());
170
171    let param_env = tcx.param_env(impl_did);
172
173    if let ty::ImplPolarity::Negative | ty::ImplPolarity::Reservation = header.polarity {
174        return Ok(());
175    }
176
177    if tcx.features().const_param_ty_unchecked() {
178        return Ok(());
179    }
180
181    if !tcx.features().adt_const_params() {
182        match *self_type.kind() {
183            ty::Adt(adt, _) if adt.is_struct() => {
184                let struct_vis = tcx.visibility(adt.did());
185                for variant in adt.variants() {
186                    for field in &variant.fields {
187                        if struct_vis.greater_than(field.vis, tcx) {
188                            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
189                            return Err(tcx
190                                .dcx()
191                                .emit_err(diagnostics::ConstParamTyFieldVisMismatch { span }));
192                        }
193                    }
194                }
195            }
196
197            _ => {}
198        }
199    }
200
201    let cause = traits::ObligationCause::misc(DUMMY_SP, impl_did);
202    match type_allowed_to_implement_const_param_ty(tcx, param_env, self_type, cause) {
203        Ok(()) => Ok(()),
204        Err(ConstParamTyImplementationError::InfrigingFields(fields)) => {
205            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
206            Err(infringing_fields_error(
207                tcx,
208                fields.into_iter().map(|(field, ty, reason)| (tcx.def_span(field.did), ty, reason)),
209                LangItem::ConstParamTy,
210                impl_did,
211                span,
212            ))
213        }
214        Err(ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed) => {
215            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
216            Err(tcx.dcx().emit_err(diagnostics::ConstParamTyImplOnNonAdt { span }))
217        }
218        Err(ConstParamTyImplementationError::NonExhaustive(attr_span)) => {
219            let defn_span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
220            Err(tcx
221                .dcx()
222                .emit_err(diagnostics::ConstParamTyImplOnNonExhaustive { defn_span, attr_span }))
223        }
224        Err(ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(infringing_tys)) => {
225            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
226            Err(infringing_fields_error(
227                tcx,
228                infringing_tys.into_iter().map(|(ty, reason)| (span, ty, reason)),
229                LangItem::ConstParamTy,
230                impl_did,
231                span,
232            ))
233        }
234        Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
235            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
236            Err(tcx.dcx().emit_err(diagnostics::ConstParamTyImplOnUnsized { span }))
237        }
238    }
239}
240
241fn visit_implementation_of_coerce_unsized(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
242    let tcx = checker.tcx;
243    let impl_did = checker.impl_def_id;
244    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/coherence/builtin.rs:244",
                        "rustc_hir_analysis::coherence::builtin",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/coherence/builtin.rs"),
                        ::tracing_core::__macro_support::Option::Some(244u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::coherence::builtin"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("visit_implementation_of_coerce_unsized: impl_did={0:?}",
                                                    impl_did) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("visit_implementation_of_coerce_unsized: impl_did={:?}", impl_did);
245
246    // Just compute this for the side-effects, in particular reporting
247    // errors; other parts of the code may demand it for the info of
248    // course.
249    tcx.ensure_result().coerce_unsized_info(impl_did)
250}
251
252fn visit_implementation_of_reborrow(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
253    let tcx = checker.tcx;
254    let impl_did = checker.impl_def_id;
255    {
    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:255",
                        "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(255u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("visit_implementation_of_reborrow: impl_did={0:?}",
                                                    impl_did) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("visit_implementation_of_reborrow: impl_did={:?}", impl_did);
256
257    // Just compute this for the side-effects, in particular reporting
258    // errors; other parts of the code may demand it for the info of
259    // course.
260    reborrow_info(tcx, impl_did)
261}
262
263fn visit_implementation_of_coerce_shared(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
264    let tcx = checker.tcx;
265    let impl_did = checker.impl_def_id;
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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("visit_implementation_of_coerce_shared: impl_did={0:?}",
                                                    impl_did) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("visit_implementation_of_coerce_shared: impl_did={:?}", impl_did);
267
268    // Just compute this for the side-effects, in particular reporting
269    // errors; other parts of the code may demand it for the info of
270    // course.
271    coerce_shared::coerce_shared_info(tcx, impl_did)
272}
273
274fn is_from_coerce_pointee_derive(tcx: TyCtxt<'_>, span: Span) -> bool {
275    span.ctxt()
276        .outer_expn_data()
277        .macro_def_id
278        .is_some_and(|def_id| tcx.is_diagnostic_item(sym::CoercePointee, def_id))
279}
280
281fn visit_implementation_of_dispatch_from_dyn(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
282    let tcx = checker.tcx;
283    let impl_did = checker.impl_def_id;
284    let trait_ref = checker.impl_header.trait_ref.instantiate_identity().skip_norm_wip();
285    {
    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:285",
                        "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(285u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("visit_implementation_of_dispatch_from_dyn: impl_did={0:?}",
                                                    impl_did) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("visit_implementation_of_dispatch_from_dyn: impl_did={:?}", impl_did);
286
287    let span = tcx.def_span(impl_did);
288    let trait_name = "DispatchFromDyn";
289
290    let source = trait_ref.self_ty();
291    let target = {
292        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));
293
294        trait_ref.args.type_at(1)
295    };
296
297    // Check `CoercePointee` impl is WF -- if not, then there's no reason to report
298    // redundant errors for `DispatchFromDyn`. This is best effort, though.
299    let mut res = Ok(());
300    tcx.for_each_relevant_impl(
301        tcx.require_lang_item(LangItem::CoerceUnsized, span),
302        source,
303        |impl_def_id| {
304            res = res.and(tcx.ensure_result().coerce_unsized_info(impl_def_id));
305        },
306    );
307    res?;
308
309    {
    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:309",
                        "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(309u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("visit_implementation_of_dispatch_from_dyn: {0:?} -> {1:?}",
                                                    source, target) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("visit_implementation_of_dispatch_from_dyn: {:?} -> {:?}", source, target);
310
311    let param_env = tcx.param_env(impl_did);
312
313    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
314    let cause = ObligationCause::misc(span, impl_did);
315
316    // Later parts of the compiler rely on all DispatchFromDyn types to be ABI-compatible with raw
317    // pointers. This is enforced here: we only allow impls for references, raw pointers, and things
318    // that are effectively repr(transparent) newtypes around types that already hav a
319    // DispatchedFromDyn impl. We cannot literally use repr(transparent) on those types since some
320    // of them support an allocator, but we ensure that for the cases where the type implements this
321    // trait, they *do* satisfy the repr(transparent) rules, and then we assume that everything else
322    // in the compiler (in particular, all the call ABI logic) will treat them as repr(transparent)
323    // even if they do not carry that attribute.
324    match (source.kind(), target.kind()) {
325        (&ty::Pat(_, pat_a), &ty::Pat(_, pat_b)) => {
326            if pat_a != pat_b {
327                return Err(tcx.dcx().emit_err(diagnostics::CoerceSamePatKind {
328                    span,
329                    trait_name,
330                    pat_a: pat_a.to_string(),
331                    pat_b: pat_b.to_string(),
332                }));
333            }
334            Ok(())
335        }
336
337        (&ty::Ref(r_a, _, mutbl_a), ty::Ref(r_b, _, mutbl_b))
338            if r_a == *r_b && mutbl_a == *mutbl_b =>
339        {
340            Ok(())
341        }
342        (&ty::RawPtr(_, a_mutbl), &ty::RawPtr(_, b_mutbl)) if a_mutbl == b_mutbl => Ok(()),
343        (&ty::Adt(def_a, args_a), &ty::Adt(def_b, args_b))
344            if def_a.is_struct() && def_b.is_struct() =>
345        {
346            if def_a != def_b {
347                let source_path = tcx.def_path_str(def_a.did());
348                let target_path = tcx.def_path_str(def_b.did());
349                return Err(tcx.dcx().emit_err(diagnostics::CoerceSameStruct {
350                    span,
351                    trait_name,
352                    note: true,
353                    source_path,
354                    target_path,
355                }));
356            }
357
358            if def_a.repr().c() || def_a.repr().packed() {
359                return Err(tcx.dcx().emit_err(diagnostics::DispatchFromDynRepr { span }));
360            }
361
362            let fields = &def_a.non_enum_variant().fields;
363
364            let mut res = Ok(());
365            let coerced_fields = fields
366                .iter_enumerated()
367                .filter_map(|(i, field)| {
368                    // Ignore PhantomData fields
369                    let unnormalized_ty = tcx.type_of(field.did).instantiate_identity();
370                    if tcx
371                        .try_normalize_erasing_regions(
372                            ty::TypingEnv::non_body_analysis(tcx, def_a.did()),
373                            unnormalized_ty,
374                        )
375                        .unwrap_or(unnormalized_ty.skip_norm_wip())
376                        .is_phantom_data()
377                    {
378                        return None;
379                    }
380
381                    let ty_a = field.ty(tcx, args_a).skip_norm_wip();
382                    let ty_b = field.ty(tcx, args_b).skip_norm_wip();
383
384                    // FIXME: We could do normalization here, but is it really worth it?
385                    if ty_a == ty_b {
386                        // Allow 1-ZSTs that don't mention type params.
387                        //
388                        // Allowing type params here would allow us to possibly transmute
389                        // between ZSTs, which may be used to create library unsoundness.
390                        if let Ok(layout) =
391                            tcx.layout_of(infcx.typing_env(param_env).as_query_input(ty_a))
392                            && layout.is_1zst()
393                            && !ty_a.has_non_region_param()
394                        {
395                            // ignore 1-ZST fields
396                            return None;
397                        }
398
399                        res = Err(tcx.dcx().emit_err(diagnostics::DispatchFromDynZST {
400                            span,
401                            name: field.ident(tcx),
402                            ty: ty_a,
403                        }));
404
405                        None
406                    } else {
407                        Some((i, ty_a, ty_b, tcx.def_span(field.did)))
408                    }
409                })
410                .collect::<Vec<_>>();
411            res?;
412
413            if coerced_fields.is_empty() {
414                return Err(tcx.dcx().emit_err(diagnostics::CoerceNoField {
415                    span,
416                    trait_name,
417                    note: true,
418                }));
419            } else if let &[(_, ty_a, ty_b, field_span)] = &coerced_fields[..] {
420                let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
421                ocx.register_obligation(Obligation::new(
422                    tcx,
423                    cause.clone(),
424                    param_env,
425                    ty::TraitRef::new(tcx, trait_ref.def_id, [ty_a, ty_b]),
426                ));
427                let errors = ocx.evaluate_obligations_error_on_ambiguity();
428                if let TraitErrors::HasErrors(errors) = errors {
429                    if is_from_coerce_pointee_derive(tcx, span) {
430                        return Err(tcx.dcx().emit_err(diagnostics::CoerceFieldValidity {
431                            span,
432                            trait_name,
433                            ty: trait_ref.self_ty(),
434                            field_span,
435                            field_ty: ty_a,
436                        }));
437                    } else {
438                        return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
439                    }
440                }
441
442                // Finally, resolve all regions.
443                ocx.resolve_regions_and_report_errors(impl_did, param_env, [])?;
444
445                Ok(())
446            } else {
447                return Err(tcx.dcx().emit_err(diagnostics::CoerceMulti {
448                    span,
449                    trait_name,
450                    number: coerced_fields.len(),
451                    fields: coerced_fields.iter().map(|(_, _, _, s)| *s).collect::<Vec<_>>().into(),
452                }));
453            }
454        }
455        _ => Err(tcx.dcx().emit_err(diagnostics::CoerceUnsizedNonStruct { span, trait_name })),
456    }
457}
458
459pub(crate) fn reborrow_info<'tcx>(
460    tcx: TyCtxt<'tcx>,
461    impl_did: LocalDefId,
462) -> Result<(), ErrorGuaranteed> {
463    {
    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:463",
                        "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(463u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("compute_reborrow_info(impl_did={0:?})",
                                                    impl_did) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("compute_reborrow_info(impl_did={:?})", impl_did);
464    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
465    let span = tcx.def_span(impl_did);
466    let trait_name = "Reborrow";
467
468    let reborrow_trait = tcx.require_lang_item(LangItem::Reborrow, span);
469
470    let source = tcx.type_of(impl_did).instantiate_identity().skip_norm_wip();
471    let trait_ref = tcx.impl_trait_ref(impl_did).instantiate_identity().skip_norm_wip();
472
473    if trait_impl_lifetime_params_count(tcx, impl_did) != 1 {
474        return Err(tcx
475            .dcx()
476            .emit_err(diagnostics::CoerceSharedNotSingleLifetimeParam { span, trait_name }));
477    }
478
479    {
    match (&trait_ref.def_id, &reborrow_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, reborrow_trait);
480    let param_env = tcx.param_env(impl_did);
481    if !!source.has_escaping_bound_vars() {
    ::core::panicking::panic("assertion failed: !source.has_escaping_bound_vars()")
};assert!(!source.has_escaping_bound_vars());
482
483    let (def, args) = match source.kind() {
484        &ty::Adt(def, args) if def.is_struct() => (def, args),
485        _ => {
486            // Note: reusing error here as it takes trait_name as argument.
487            return Err(tcx
488                .dcx()
489                .emit_err(diagnostics::CoerceUnsizedNonStruct { span, trait_name }));
490        }
491    };
492
493    let lifetimes_count = generic_lifetime_params_count(args);
494    let data_fields = collect_reborrow_data_fields(tcx, def, args);
495
496    if lifetimes_count != 1 {
497        let item = tcx.hir_expect_item(impl_did);
498        let _span = if let ItemKind::Impl(hir::Impl { of_trait: Some(of_trait), .. }) = &item.kind {
499            of_trait.trait_ref.path.span
500        } else {
501            tcx.def_span(impl_did)
502        };
503
504        return Err(tcx.dcx().emit_err(diagnostics::CoerceSharedMulti { span, trait_name }));
505    }
506
507    if data_fields.is_empty() {
508        return Ok(());
509    }
510
511    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
512    // We've found some data fields. They must all be either be Copy or Reborrow.
513    for mut field in data_fields {
514        field.ty = ocx
515            .deeply_normalize(
516                &traits::ObligationCause::misc(field.span, impl_did),
517                param_env,
518                Unnormalized::new_wip(field.ty),
519            )
520            .map_err(|errors| infcx.err_ctxt().report_fulfillment_errors(errors))?;
521        if field_type_is_reborrow(
522            tcx,
523            &infcx,
524            reborrow_trait,
525            impl_did,
526            param_env,
527            field.ty,
528            field.span,
529        ) {
530            // Field implements Reborrow, check remaining fields.
531            continue;
532        }
533
534        // Field does not implement Reborrow: it must be Copy.
535        assert_field_type_is_copy(tcx, &infcx, impl_did, param_env, field.ty, field.span)?;
536    }
537
538    Ok(())
539}
540
541fn trait_impl_lifetime_params_count(tcx: TyCtxt<'_>, did: LocalDefId) -> usize {
542    tcx.generics_of(did)
543        .own_params
544        .iter()
545        .filter(|p| #[allow(non_exhaustive_omitted_patterns)] match p.kind {
    ty::GenericParamDefKind::Lifetime => true,
    _ => false,
}matches!(p.kind, ty::GenericParamDefKind::Lifetime))
546        .count()
547}
548
549fn generic_lifetime_params_count(args: &[ty::GenericArg<'_>]) -> usize {
550    args.iter().filter(|arg| arg.as_region().is_some()).count()
551}
552
553#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ReborrowDataField<'tcx> {
    #[inline]
    fn clone(&self) -> ReborrowDataField<'tcx> {
        let _: ::core::clone::AssertParamIsClone<Ident>;
        let _: ::core::clone::AssertParamIsClone<Symbol>;
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Span>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for ReborrowDataField<'tcx> { }Copy)]
554struct ReborrowDataField<'tcx> {
555    ident: Ident,
556    name: Symbol,
557    ty: Ty<'tcx>,
558    span: Span,
559}
560
561fn collect_reborrow_data_fields<'tcx>(
562    tcx: TyCtxt<'tcx>,
563    def: ty::AdtDef<'tcx>,
564    args: ty::GenericArgsRef<'tcx>,
565) -> Vec<ReborrowDataField<'tcx>> {
566    def.non_enum_variant()
567        .fields
568        .iter()
569        .filter_map(|field| {
570            let ty = field.ty(tcx, args).skip_norm_wip();
571            (!ty.is_phantom_data()).then_some(ReborrowDataField {
572                ident: field.ident(tcx),
573                name: field.name,
574                ty,
575                span: tcx.def_span(field.did),
576            })
577        })
578        .collect()
579}
580
581fn field_type_is_reborrow<'tcx>(
582    tcx: TyCtxt<'tcx>,
583    infcx: &InferCtxt<'tcx>,
584    reborrow_trait: DefId,
585    impl_did: LocalDefId,
586    param_env: ty::ParamEnv<'tcx>,
587    ty: Ty<'tcx>,
588    span: Span,
589) -> bool {
590    if ty.ref_mutability() == Some(ty::Mutability::Mut) {
591        // Mutable references are Reborrow but not really.
592        return true;
593    }
594
595    let ocx = ObligationCtxt::new(infcx);
596    let cause = traits::ObligationCause::misc(span, impl_did);
597    ocx.register_obligation(Obligation::new(
598        tcx,
599        cause,
600        param_env,
601        ty::TraitRef::new(tcx, reborrow_trait, [ty]),
602    ));
603    ocx.evaluate_obligations_error_on_ambiguity().no_errors()
604}
605
606fn field_type_is_copy<'tcx>(
607    tcx: TyCtxt<'tcx>,
608    infcx: &InferCtxt<'tcx>,
609    impl_did: LocalDefId,
610    param_env: ty::ParamEnv<'tcx>,
611    ty: Ty<'tcx>,
612    span: Span,
613) -> bool {
614    let copy_trait = tcx.require_lang_item(LangItem::Copy, span);
615    let ocx = ObligationCtxt::new(infcx);
616    let cause = traits::ObligationCause::misc(span, impl_did);
617    ocx.register_obligation(Obligation::new(
618        tcx,
619        cause,
620        param_env,
621        ty::TraitRef::new(tcx, copy_trait, [ty]),
622    ));
623    ocx.evaluate_obligations_error_on_ambiguity().no_errors()
624}
625
626fn assert_field_type_is_copy<'tcx>(
627    tcx: TyCtxt<'tcx>,
628    infcx: &InferCtxt<'tcx>,
629    impl_did: LocalDefId,
630    param_env: ty::ParamEnv<'tcx>,
631    ty: Ty<'tcx>,
632    span: Span,
633) -> Result<(), ErrorGuaranteed> {
634    let copy_trait = tcx.require_lang_item(LangItem::Copy, span);
635    let ocx = ObligationCtxt::new_with_diagnostics(infcx);
636    let cause = traits::ObligationCause::misc(span, impl_did);
637    let obligation =
638        Obligation::new(tcx, cause, param_env, ty::TraitRef::new(tcx, copy_trait, [ty]));
639    ocx.register_obligation(obligation);
640    let errors = ocx.evaluate_obligations_error_on_ambiguity();
641
642    if let TraitErrors::HasErrors(errors) = errors {
643        Err(infcx.err_ctxt().report_fulfillment_errors(errors))
644    } else {
645        Ok(())
646    }
647}
648
649pub(crate) fn coerce_unsized_info<'tcx>(
650    tcx: TyCtxt<'tcx>,
651    impl_did: LocalDefId,
652) -> Result<CoerceUnsizedInfo, ErrorGuaranteed> {
653    {
    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:653",
                        "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(653u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("compute_coerce_unsized_info(impl_did={0:?})",
                                                    impl_did) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("compute_coerce_unsized_info(impl_did={:?})", impl_did);
654    let span = tcx.def_span(impl_did);
655    let trait_name = "CoerceUnsized";
656
657    let coerce_unsized_trait = tcx.require_lang_item(LangItem::CoerceUnsized, span);
658    let unsize_trait = tcx.require_lang_item(LangItem::Unsize, span);
659
660    let source = tcx.type_of(impl_did).instantiate_identity().skip_norm_wip();
661    let trait_ref = tcx.impl_trait_ref(impl_did).instantiate_identity().skip_norm_wip();
662
663    {
    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);
664    let target = trait_ref.args.type_at(1);
665    {
    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:665",
                        "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(665u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("visit_implementation_of_coerce_unsized: {0:?} -> {1:?} (bound)",
                                                    source, target) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("visit_implementation_of_coerce_unsized: {:?} -> {:?} (bound)", source, target);
666
667    let param_env = tcx.param_env(impl_did);
668    if !!source.has_escaping_bound_vars() {
    ::core::panicking::panic("assertion failed: !source.has_escaping_bound_vars()")
};assert!(!source.has_escaping_bound_vars());
669
670    {
    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:670",
                        "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(670u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("visit_implementation_of_coerce_unsized: {0:?} -> {1:?} (free)",
                                                    source, target) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("visit_implementation_of_coerce_unsized: {:?} -> {:?} (free)", source, target);
671
672    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
673    let cause = ObligationCause::misc(span, impl_did);
674    let check_mutbl = |mt_a: ty::TypeAndMut<'tcx>,
675                       mt_b: ty::TypeAndMut<'tcx>,
676                       mk_ptr: &dyn Fn(Ty<'tcx>) -> Ty<'tcx>| {
677        if mt_a.mutbl < mt_b.mutbl {
678            infcx
679                .err_ctxt()
680                .report_mismatched_types(
681                    &cause,
682                    param_env,
683                    mk_ptr(mt_b.ty),
684                    target,
685                    ty::error::TypeError::Mutability,
686                )
687                .emit();
688        }
689        (mt_a.ty, mt_b.ty, unsize_trait, None, span)
690    };
691    let (source, target, trait_def_id, kind, field_span) = match (source.kind(), target.kind()) {
692        (&ty::Pat(ty_a, pat_a), &ty::Pat(ty_b, pat_b)) => {
693            if pat_a != pat_b {
694                return Err(tcx.dcx().emit_err(diagnostics::CoerceSamePatKind {
695                    span,
696                    trait_name,
697                    pat_a: pat_a.to_string(),
698                    pat_b: pat_b.to_string(),
699                }));
700            }
701            (ty_a, ty_b, coerce_unsized_trait, None, span)
702        }
703
704        (&ty::Ref(r_a, ty_a, mutbl_a), &ty::Ref(r_b, ty_b, mutbl_b)) => {
705            infcx.sub_regions(
706                SubregionOrigin::RelateObjectBound(span),
707                r_b,
708                r_a,
709                ty::VisibleForLeakCheck::Yes,
710            );
711            let mt_a = ty::TypeAndMut { ty: ty_a, mutbl: mutbl_a };
712            let mt_b = ty::TypeAndMut { ty: ty_b, mutbl: mutbl_b };
713            check_mutbl(mt_a, mt_b, &|ty| Ty::new_imm_ref(tcx, r_b, ty))
714        }
715
716        (&ty::Ref(_, ty_a, mutbl_a), &ty::RawPtr(ty_b, mutbl_b))
717        | (&ty::RawPtr(ty_a, mutbl_a), &ty::RawPtr(ty_b, mutbl_b)) => {
718            let mt_a = ty::TypeAndMut { ty: ty_a, mutbl: mutbl_a };
719            let mt_b = ty::TypeAndMut { ty: ty_b, mutbl: mutbl_b };
720            check_mutbl(mt_a, mt_b, &|ty| Ty::new_imm_ptr(tcx, ty))
721        }
722
723        (&ty::Adt(def_a, args_a), &ty::Adt(def_b, args_b))
724            if def_a.is_struct() && def_b.is_struct() =>
725        {
726            if def_a != def_b {
727                let source_path = tcx.def_path_str(def_a.did());
728                let target_path = tcx.def_path_str(def_b.did());
729                return Err(tcx.dcx().emit_err(diagnostics::CoerceSameStruct {
730                    span,
731                    trait_name,
732                    note: true,
733                    source_path,
734                    target_path,
735                }));
736            }
737
738            // Here we are considering a case of converting
739            // `S<P0...Pn>` to `S<Q0...Qn>`. As an example, let's imagine a struct `Foo<T, U>`,
740            // which acts like a pointer to `U`, but carries along some extra data of type `T`:
741            //
742            //     struct Foo<T, U> {
743            //         extra: T,
744            //         ptr: *mut U,
745            //     }
746            //
747            // We might have an impl that allows (e.g.) `Foo<T, [i32; 3]>` to be unsized
748            // to `Foo<T, [i32]>`. That impl would look like:
749            //
750            //   impl<T, U: Unsize<V>, V> CoerceUnsized<Foo<T, V>> for Foo<T, U> {}
751            //
752            // Here `U = [i32; 3]` and `V = [i32]`. At runtime,
753            // when this coercion occurs, we would be changing the
754            // field `ptr` from a thin pointer of type `*mut [i32;
755            // 3]` to a wide pointer of type `*mut [i32]` (with
756            // extra data `3`). **The purpose of this check is to
757            // make sure that we know how to do this conversion.**
758            //
759            // To check if this impl is legal, we would walk down
760            // the fields of `Foo` and consider their types with
761            // both generic parameters. We are looking to find that
762            // exactly one (non-phantom) field has changed its
763            // type, which we will expect to be the pointer that
764            // is becoming fat (we could probably generalize this
765            // to multiple thin pointers of the same type becoming
766            // fat, but we don't). In this case:
767            //
768            // - `extra` has type `T` before and type `T` after
769            // - `ptr` has type `*mut U` before and type `*mut V` after
770            //
771            // Since just one field changed, we would then check
772            // that `*mut U: CoerceUnsized<*mut V>` is implemented
773            // (in other words, that we know how to do this
774            // conversion). This will work out because `U:
775            // Unsize<V>`, and we have a builtin rule that `*mut
776            // U` can be coerced to `*mut V` if `U: Unsize<V>`.
777            let fields = &def_a.non_enum_variant().fields;
778            let diff_fields = fields
779                .iter_enumerated()
780                .filter_map(|(i, f)| {
781                    let (a, b) =
782                        (f.ty(tcx, args_a).skip_norm_wip(), f.ty(tcx, args_b).skip_norm_wip());
783
784                    // Ignore PhantomData fields
785                    let unnormalized_ty = tcx.type_of(f.did).instantiate_identity();
786                    if tcx
787                        .try_normalize_erasing_regions(
788                            ty::TypingEnv::non_body_analysis(tcx, def_a.did()),
789                            unnormalized_ty,
790                        )
791                        .unwrap_or(unnormalized_ty.skip_norm_wip())
792                        .is_phantom_data()
793                    {
794                        return None;
795                    }
796
797                    // Ignore fields that aren't changed; it may
798                    // be that we could get away with subtyping or
799                    // something more accepting, but we use
800                    // equality because we want to be able to
801                    // perform this check without computing
802                    // variance or constraining opaque types' hidden types.
803                    // (This is because we may have to evaluate constraint
804                    // expressions in the course of execution.)
805                    // See e.g., #41936.
806                    if a == b {
807                        return None;
808                    }
809
810                    // Collect up all fields that were significantly changed
811                    // i.e., those that contain T in coerce_unsized T -> U
812                    Some((i, a, b, tcx.def_span(f.did)))
813                })
814                .collect::<Vec<_>>();
815
816            if diff_fields.is_empty() {
817                return Err(tcx.dcx().emit_err(diagnostics::CoerceNoField {
818                    span,
819                    trait_name,
820                    note: true,
821                }));
822            } else if diff_fields.len() > 1 {
823                let item = tcx.hir_expect_item(impl_did);
824                let span = if let ItemKind::Impl(hir::Impl { of_trait: Some(of_trait), .. }) =
825                    &item.kind
826                {
827                    of_trait.trait_ref.path.span
828                } else {
829                    tcx.def_span(impl_did)
830                };
831
832                return Err(tcx.dcx().emit_err(diagnostics::CoerceMulti {
833                    span,
834                    trait_name,
835                    number: diff_fields.len(),
836                    fields: diff_fields.iter().map(|(_, _, _, s)| *s).collect::<Vec<_>>().into(),
837                }));
838            }
839
840            let (i, a, b, field_span) = diff_fields[0];
841            let kind = ty::adjustment::CustomCoerceUnsized::Struct(i);
842            (a, b, coerce_unsized_trait, Some(kind), field_span)
843        }
844
845        _ => {
846            return Err(tcx
847                .dcx()
848                .emit_err(diagnostics::CoerceUnsizedNonStruct { span, trait_name }));
849        }
850    };
851
852    // Register an obligation for `A: Trait<B>`.
853    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
854    let cause = traits::ObligationCause::misc(span, impl_did);
855    let obligation = Obligation::new(
856        tcx,
857        cause,
858        param_env,
859        ty::TraitRef::new(tcx, trait_def_id, [source, target]),
860    );
861    ocx.register_obligation(obligation);
862    let errors = ocx.evaluate_obligations_error_on_ambiguity();
863
864    if let TraitErrors::HasErrors(errors) = errors {
865        if is_from_coerce_pointee_derive(tcx, span) {
866            return Err(tcx.dcx().emit_err(diagnostics::CoerceFieldValidity {
867                span,
868                trait_name,
869                ty: trait_ref.self_ty(),
870                field_span,
871                field_ty: source,
872            }));
873        } else {
874            return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
875        }
876    }
877
878    // Finally, resolve all regions.
879    ocx.resolve_regions_and_report_errors(impl_did, param_env, [])?;
880
881    Ok(CoerceUnsizedInfo { custom_kind: kind })
882}
883
884fn infringing_fields_error<'tcx>(
885    tcx: TyCtxt<'tcx>,
886    infringing_tys: impl Iterator<Item = (Span, Ty<'tcx>, InfringingFieldsReason<'tcx>)>,
887    lang_item: LangItem,
888    impl_did: LocalDefId,
889    impl_span: Span,
890) -> ErrorGuaranteed {
891    let trait_did = tcx.require_lang_item(lang_item, impl_span);
892
893    let trait_name = tcx.def_path_str(trait_did);
894
895    // We'll try to suggest constraining type parameters to fulfill the requirements of
896    // their `Copy` implementation.
897    let mut errors: BTreeMap<_, Vec<_>> = Default::default();
898    let mut bounds = ::alloc::vec::Vec::new()vec![];
899
900    let mut seen_tys = FxHashSet::default();
901
902    let mut label_spans = Vec::new();
903
904    for (span, ty, reason) in infringing_tys {
905        // Only report an error once per type.
906        if !seen_tys.insert(ty) {
907            continue;
908        }
909
910        label_spans.push(span);
911
912        match reason {
913            InfringingFieldsReason::Fulfill(fulfillment_errors) => {
914                for error in fulfillment_errors {
915                    let error_predicate = error.obligation.predicate;
916                    // Only note if it's not the root obligation, otherwise it's trivial and
917                    // should be self-explanatory (i.e. a field literally doesn't implement Copy).
918
919                    // FIXME: This error could be more descriptive, especially if the error_predicate
920                    // contains a foreign type or if it's a deeply nested type...
921                    if error_predicate != error.root_obligation.predicate {
922                        errors
923                            .entry((ty.to_string(), error_predicate.to_string()))
924                            .or_default()
925                            .push(error.obligation.cause.span);
926                    }
927                    if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitClause {
928                        trait_ref,
929                        polarity: ty::ClausePolarity::Positive,
930                        ..
931                    })) = error_predicate.kind().skip_binder()
932                    {
933                        let ty = trait_ref.self_ty();
934                        if let ty::Param(_) = ty.kind() {
935                            bounds.push((
936                                ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("{0}", ty)) })format!("{ty}"),
937                                trait_ref.print_trait_sugared().to_string(),
938                                Some(trait_ref.def_id),
939                            ));
940                        }
941                    }
942                }
943            }
944            InfringingFieldsReason::Regions(region_errors) => {
945                for error in region_errors {
946                    let ty = ty.to_string();
947                    match error {
948                        RegionResolutionError::ConcreteFailure(origin, a, b) => {
949                            let predicate = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", b, a))
    })format!("{b}: {a}");
950                            errors
951                                .entry((ty.clone(), predicate.clone()))
952                                .or_default()
953                                .push(origin.span());
954                            if let ty::RegionKind::ReEarlyParam(ebr) = b.kind()
955                                && ebr.is_named()
956                            {
957                                bounds.push((b.to_string(), a.to_string(), None));
958                            }
959                        }
960                        RegionResolutionError::GenericBoundFailure(origin, a, b) => {
961                            let predicate = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", a, b))
    })format!("{a}: {b}");
962                            errors
963                                .entry((ty.clone(), predicate.clone()))
964                                .or_default()
965                                .push(origin.span());
966                            if let infer::region_constraints::GenericKind::Param(_) = a {
967                                bounds.push((a.to_string(), b.to_string(), None));
968                            }
969                        }
970                        _ => continue,
971                    }
972                }
973            }
974        }
975    }
976    let mut notes = Vec::new();
977    for ((ty, error_predicate), spans) in errors {
978        let span: MultiSpan = spans.into();
979        notes.push(diagnostics::ImplForTyRequires {
980            span,
981            error_predicate,
982            trait_name: trait_name.clone(),
983            ty,
984        });
985    }
986
987    let mut err = tcx.dcx().create_err(diagnostics::TraitCannotImplForTy {
988        span: impl_span,
989        trait_name,
990        label_spans,
991        notes,
992    });
993
994    suggest_constraining_type_params(
995        tcx,
996        tcx.hir_get_generics(impl_did).expect("impls always have generics"),
997        &mut err,
998        bounds
999            .iter()
1000            .map(|(param, constraint, def_id)| (param.as_str(), constraint.as_str(), *def_id)),
1001        None,
1002    );
1003
1004    err.emit()
1005}
1006
1007fn visit_implementation_of_coerce_pointee_validity(
1008    checker: &Checker<'_>,
1009) -> Result<(), ErrorGuaranteed> {
1010    let tcx = checker.tcx;
1011    let self_ty =
1012        tcx.impl_trait_ref(checker.impl_def_id).instantiate_identity().skip_norm_wip().self_ty();
1013    let span = tcx.def_span(checker.impl_def_id);
1014    if !tcx.is_builtin_derived(checker.impl_def_id.into()) {
1015        return Err(tcx.dcx().emit_err(diagnostics::CoercePointeeNoUserValidityAssertion { span }));
1016    }
1017    let ty::Adt(def, _args) = self_ty.kind() else {
1018        return Err(tcx.dcx().emit_err(diagnostics::CoercePointeeNotConcreteType { span }));
1019    };
1020    let did = def.did();
1021    // Now get a more precise span of the `struct`.
1022    let span = tcx.def_span(did);
1023    if !def.is_struct() {
1024        return Err(tcx
1025            .dcx()
1026            .emit_err(diagnostics::CoercePointeeNotStruct { span, kind: def.descr().into() }));
1027    }
1028    if !def.repr().transparent() {
1029        return Err(tcx.dcx().emit_err(diagnostics::CoercePointeeNotTransparent { span }));
1030    }
1031    if def.all_fields().next().is_none() {
1032        return Err(tcx.dcx().emit_err(diagnostics::CoercePointeeNoField { span }));
1033    }
1034    Ok(())
1035}