Skip to main content

rustc_trait_selection/traits/specialize/
mod.rs

1//! Logic and data structures related to impl specialization, explained in
2//! greater detail below.
3//!
4//! At the moment, this implementation support only the simple "chain" rule:
5//! If any two impls overlap, one must be a strict subset of the other.
6//!
7//! See the [rustc dev guide] for a bit more detail on how specialization
8//! fits together with the rest of the trait machinery.
9//!
10//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/specialization.html
11
12pub mod specialization_graph;
13
14use rustc_data_structures::fx::FxIndexSet;
15use rustc_errors::codes::*;
16use rustc_errors::{Diag, EmissionGuarantee};
17use rustc_hir::def_id::{DefId, LocalDefId};
18use rustc_infer::traits::Obligation;
19use rustc_middle::bug;
20use rustc_middle::query::LocalCrate;
21use rustc_middle::traits::query::NoSolution;
22use rustc_middle::ty::fast_reject::{self, TreatParams};
23use rustc_middle::ty::print::PrintTraitRefExt as _;
24use rustc_middle::ty::{
25    self, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt, TypingMode, Unnormalized,
26};
27use rustc_session::lint::builtin::COHERENCE_LEAK_CHECK;
28use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, sym};
29use specialization_graph::GraphExt;
30use tracing::{debug, instrument};
31
32use crate::diagnostics::NegativePositiveConflict;
33use crate::error_reporting::traits::to_pretty_impl_header;
34use crate::infer::{InferCtxt, TyCtxtInferExt};
35use crate::traits::select::IntercrateAmbiguityCause;
36use crate::traits::{
37    FutureCompatOverlapErrorKind, ObligationCause, ObligationCtxt, coherence,
38    predicates_for_generics,
39};
40
41/// Information pertinent to an overlapping impl error.
42#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for OverlapError<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["with_impl", "trait_ref", "self_ty",
                        "intercrate_ambiguity_causes", "involves_placeholder",
                        "overflowing_predicates"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.with_impl, &self.trait_ref, &self.self_ty,
                        &self.intercrate_ambiguity_causes,
                        &self.involves_placeholder, &&self.overflowing_predicates];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "OverlapError",
            names, values)
    }
}Debug)]
43pub struct OverlapError<'tcx> {
44    pub with_impl: DefId,
45    pub trait_ref: ty::TraitRef<'tcx>,
46    pub self_ty: Option<Ty<'tcx>>,
47    pub intercrate_ambiguity_causes: FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
48    pub involves_placeholder: bool,
49    pub overflowing_predicates: Vec<ty::Predicate<'tcx>>,
50}
51
52/// Given the generic parameters for the requested impl, translate it to the generic parameters
53/// appropriate for the actual item definition (whether it be in that impl,
54/// a parent impl, or the trait).
55///
56/// When we have selected one impl, but are actually using item definitions from
57/// a parent impl providing a default, we need a way to translate between the
58/// type parameters of the two impls. Here the `source_impl` is the one we've
59/// selected, and `source_args` is its generic parameters.
60/// And `target_node` is the impl/trait we're actually going to get the
61/// definition from. The resulting instantiation will map from `target_node`'s
62/// generics to `source_impl`'s generics as instantiated by `source_args`.
63///
64/// For example, consider the following scenario:
65///
66/// ```ignore (illustrative)
67/// trait Foo { ... }
68/// impl<T, U> Foo for (T, U) { ... }  // target impl
69/// impl<V> Foo for (V, V) { ... }     // source impl
70/// ```
71///
72/// Suppose we have selected "source impl" with `V` instantiated with `u32`.
73/// This function will produce an instantiation with `T` and `U` both mapping to `u32`.
74///
75/// where-clauses add some trickiness here, because they can be used to "define"
76/// an argument indirectly:
77///
78/// ```ignore (illustrative)
79/// impl<'a, I, T: 'a> Iterator for Cloned<I>
80///    where I: Iterator<Item = &'a T>, T: Clone
81/// ```
82///
83/// In a case like this, the instantiation for `T` is determined indirectly,
84/// through associated type projection. We deal with such cases by using
85/// *fulfillment* to relate the two impls, requiring that all projections are
86/// resolved.
87pub fn translate_args<'tcx>(
88    infcx: &InferCtxt<'tcx>,
89    param_env: ty::ParamEnv<'tcx>,
90    source_impl: DefId,
91    source_args: GenericArgsRef<'tcx>,
92    target_node: specialization_graph::Node,
93) -> GenericArgsRef<'tcx> {
94    translate_args_with_cause(
95        infcx,
96        param_env,
97        source_impl,
98        source_args,
99        target_node,
100        &ObligationCause::dummy(),
101    )
102}
103
104/// Like [translate_args], but obligations from the parent implementation
105/// are registered with the provided `ObligationCause`.
106///
107/// This is for reporting *region* errors from those bounds. Type errors should
108/// not happen because the specialization graph already checks for those, and
109/// will result in an ICE.
110pub fn translate_args_with_cause<'tcx>(
111    infcx: &InferCtxt<'tcx>,
112    param_env: ty::ParamEnv<'tcx>,
113    source_impl: DefId,
114    source_args: GenericArgsRef<'tcx>,
115    target_node: specialization_graph::Node,
116    cause: &ObligationCause<'tcx>,
117) -> GenericArgsRef<'tcx> {
118    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/specialize/mod.rs:118",
                        "rustc_trait_selection::traits::specialize",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(118u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::specialize"),
                        ::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!("translate_args({0:?}, {1:?}, {2:?}, {3:?})",
                                                    param_env, source_impl, source_args, target_node) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
119        "translate_args({:?}, {:?}, {:?}, {:?})",
120        param_env, source_impl, source_args, target_node
121    );
122    let source_trait_ref =
123        infcx.tcx.impl_trait_ref(source_impl).instantiate(infcx.tcx, source_args).skip_norm_wip();
124
125    // translate the Self and Param parts of the generic parameters, since those
126    // vary across impls
127    let target_args = match target_node {
128        specialization_graph::Node::Impl(target_impl) => {
129            // no need to translate if we're targeting the impl we started with
130            if source_impl == target_impl {
131                return source_args;
132            }
133
134            fulfill_implication(infcx, param_env, source_trait_ref, source_impl, target_impl, cause)
135                .unwrap_or_else(|_| {
136                    ::rustc_middle::util::bug::bug_fmt(format_args!("When translating generic parameters from {0:?} to {1:?}, the expected specialization failed to hold",
        source_impl, target_impl))bug!(
137                        "When translating generic parameters from {source_impl:?} to \
138                        {target_impl:?}, the expected specialization failed to hold"
139                    )
140                })
141        }
142        specialization_graph::Node::Trait(..) => source_trait_ref.args,
143    };
144
145    // directly inherent the method generics, since those do not vary across impls
146    source_args.rebase_onto(infcx.tcx, source_impl, target_args)
147}
148
149/// Attempt to fulfill all obligations of `target_impl` after unification with
150/// `source_trait_ref`. If successful, returns the generic parameters for *all* the
151/// generics of `target_impl`, including both those needed to unify with
152/// `source_trait_ref` and those whose identity is determined via a where
153/// clause in the impl.
154fn fulfill_implication<'tcx>(
155    infcx: &InferCtxt<'tcx>,
156    param_env: ty::ParamEnv<'tcx>,
157    source_trait_ref: ty::TraitRef<'tcx>,
158    source_impl: DefId,
159    target_impl: DefId,
160    cause: &ObligationCause<'tcx>,
161) -> Result<GenericArgsRef<'tcx>, NoSolution> {
162    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/specialize/mod.rs:162",
                        "rustc_trait_selection::traits::specialize",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(162u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::specialize"),
                        ::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!("fulfill_implication({0:?}, trait_ref={1:?} |- {2:?} applies)",
                                                    param_env, source_trait_ref, target_impl) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
163        "fulfill_implication({:?}, trait_ref={:?} |- {:?} applies)",
164        param_env, source_trait_ref, target_impl
165    );
166
167    let ocx = ObligationCtxt::new(infcx);
168    let source_trait_ref = ocx.normalize(cause, param_env, Unnormalized::new_wip(source_trait_ref));
169
170    if !ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
171        infcx.dcx().span_delayed_bug(
172            infcx.tcx.def_span(source_impl),
173            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to fully normalize {0}",
                source_trait_ref))
    })format!("failed to fully normalize {source_trait_ref}"),
174        );
175        return Err(NoSolution);
176    }
177
178    let target_args = infcx.fresh_args_for_item(DUMMY_SP, target_impl);
179    let target_trait_ref = ocx.normalize(
180        cause,
181        param_env,
182        infcx.tcx.impl_trait_ref(target_impl).instantiate(infcx.tcx, target_args),
183    );
184
185    // do the impls unify? If not, no specialization.
186    ocx.eq(cause, param_env, source_trait_ref, target_trait_ref)?;
187
188    // Now check that the source trait ref satisfies all the where clauses of the target impl.
189    // This is not just for correctness; we also need this to constrain any params that may
190    // only be referenced via projection predicates.
191    let clauses = infcx.tcx.clauses_of(target_impl).instantiate(infcx.tcx, target_args);
192    let obligations = predicates_for_generics(
193        |_, _| cause.clone(),
194        |clause| ocx.normalize(cause, param_env, clause),
195        param_env,
196        clauses,
197    );
198    ocx.register_obligations(obligations);
199
200    let errors = ocx.evaluate_obligations_error_on_ambiguity();
201    if !errors.no_errors() {
202        // no dice!
203        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/specialize/mod.rs:203",
                        "rustc_trait_selection::traits::specialize",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(203u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::specialize"),
                        ::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!("fulfill_implication: for impls on {0:?} and {1:?}, could not fulfill: {2:?} given {3:?}",
                                                    source_trait_ref, target_trait_ref, errors,
                                                    param_env.caller_bounds()) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
204            "fulfill_implication: for impls on {:?} and {:?}, \
205                 could not fulfill: {:?} given {:?}",
206            source_trait_ref,
207            target_trait_ref,
208            errors,
209            param_env.caller_bounds()
210        );
211        return Err(NoSolution);
212    }
213
214    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/specialize/mod.rs:214",
                        "rustc_trait_selection::traits::specialize",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(214u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::specialize"),
                        ::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!("fulfill_implication: an impl for {0:?} specializes {1:?}",
                                                    source_trait_ref, target_trait_ref) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
215        "fulfill_implication: an impl for {:?} specializes {:?}",
216        source_trait_ref, target_trait_ref
217    );
218
219    // Now resolve the *generic parameters* we built for the target earlier, replacing
220    // the inference variables inside with whatever we got from fulfillment.
221    Ok(infcx.resolve_vars_if_possible(target_args))
222}
223
224pub(super) fn specialization_enabled_in(tcx: TyCtxt<'_>, _: LocalCrate) -> bool {
225    tcx.features().specialization() || tcx.features().min_specialization()
226}
227
228/// Is `specializing_impl_def_id` a specialization of `parent_impl_def_id`?
229///
230/// For every type that could apply to `specializing_impl_def_id`, we prove that
231/// the `parent_impl_def_id` also applies (i.e. it has a valid impl header and
232/// its where-clauses hold).
233///
234/// For the purposes of const traits, we also check that the specializing
235/// impl is not more restrictive than the parent impl. That is, if the
236/// `parent_impl_def_id` is a const impl (conditionally based off of some `[const]`
237/// bounds), then `specializing_impl_def_id` must also be const for the same
238/// set of types.
239#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("specializes",
                                    "rustc_trait_selection::traits::specialize",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(239u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::specialize"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("specializing_impl_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("specializing_impl_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("parent_impl_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("parent_impl_def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&specializing_impl_def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_impl_def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: bool = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !tcx.specialization_enabled_in(specializing_impl_def_id.krate)
                {
                let span = tcx.def_span(specializing_impl_def_id);
                if !span.allows_unstable(sym::specialization) &&
                        !span.allows_unstable(sym::min_specialization) {
                    return false;
                }
            }
            let specializing_impl_trait_header =
                tcx.impl_trait_header(specializing_impl_def_id);
            if specializing_impl_trait_header.polarity !=
                    tcx.impl_polarity(parent_impl_def_id) {
                return false;
            }
            let param_env = tcx.param_env(specializing_impl_def_id);
            let infcx =
                tcx.infer_ctxt().build(TypingMode::non_body_analysis());
            let specializing_impl_trait_ref =
                specializing_impl_trait_header.trait_ref.instantiate_identity();
            let cause = &ObligationCause::dummy();
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/specialize/mod.rs:288",
                                    "rustc_trait_selection::traits::specialize",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(288u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::specialize"),
                                    ::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!("fulfill_implication({0:?}, trait_ref={1:?} |- {2:?} applies)",
                                                                param_env, specializing_impl_trait_ref, parent_impl_def_id)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let ocx = ObligationCtxt::new(&infcx);
            let specializing_impl_trait_ref =
                ocx.normalize(cause, param_env, specializing_impl_trait_ref);
            if !ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
                infcx.dcx().span_delayed_bug(infcx.tcx.def_span(specializing_impl_def_id),
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("failed to fully normalize {0}",
                                    specializing_impl_trait_ref))
                        }));
                return false;
            }
            let parent_args =
                infcx.fresh_args_for_item(DUMMY_SP, parent_impl_def_id);
            let parent_impl_trait_ref =
                ocx.normalize(cause, param_env,
                    infcx.tcx.impl_trait_ref(parent_impl_def_id).instantiate(infcx.tcx,
                        parent_args));
            let Ok(()) =
                ocx.eq(cause, param_env, specializing_impl_trait_ref,
                    parent_impl_trait_ref) else { return false; };
            let clauses =
                infcx.tcx.clauses_of(parent_impl_def_id).instantiate(infcx.tcx,
                    parent_args);
            let obligations =
                predicates_for_generics(|_, _| cause.clone(),
                    |clause| ocx.normalize(cause, param_env, clause), param_env,
                    clauses);
            ocx.register_obligations(obligations);
            let errors = ocx.evaluate_obligations_error_on_ambiguity();
            if !errors.no_errors() {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/specialize/mod.rs:334",
                                        "rustc_trait_selection::traits::specialize",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
                                        ::tracing_core::__macro_support::Option::Some(334u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::specialize"),
                                        ::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!("fulfill_implication: for impls on {0:?} and {1:?}, could not fulfill: {2:?} given {3:?}",
                                                                    specializing_impl_trait_ref, parent_impl_trait_ref, errors,
                                                                    param_env.caller_bounds()) as
                                                            &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                return false;
            }
            if tcx.is_conditionally_const(parent_impl_def_id) {
                if !tcx.is_conditionally_const(specializing_impl_def_id) {
                    return false;
                }
                let const_conditions =
                    infcx.tcx.const_conditions(parent_impl_def_id).instantiate(infcx.tcx,
                        parent_args);
                let const_conditions =
                    const_conditions.into_iter().map(|(trait_ref, span)|
                            (ocx.normalize(cause, param_env, trait_ref), span));
                ocx.register_obligations(const_conditions.into_iter().map(|(trait_ref,
                                _)|
                            {
                                Obligation::new(infcx.tcx, cause.clone(), param_env,
                                    trait_ref.to_host_effect_clause(infcx.tcx,
                                        ty::BoundConstness::Maybe))
                            }));
                let errors = ocx.evaluate_obligations_error_on_ambiguity();
                if !errors.no_errors() {
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/specialize/mod.rs:370",
                                            "rustc_trait_selection::traits::specialize",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(370u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::specialize"),
                                            ::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!("fulfill_implication: for impls on {0:?} and {1:?}, could not fulfill: {2:?} given {3:?}",
                                                                        specializing_impl_trait_ref, parent_impl_trait_ref, errors,
                                                                        param_env.caller_bounds()) as
                                                                &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    return false;
                }
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/specialize/mod.rs:382",
                                    "rustc_trait_selection::traits::specialize",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(382u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::specialize"),
                                    ::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!("fulfill_implication: an impl for {0:?} specializes {1:?}",
                                                                specializing_impl_trait_ref, parent_impl_trait_ref) as
                                                        &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            true
        }
    }
}#[instrument(skip(tcx), level = "debug")]
240pub(super) fn specializes(
241    tcx: TyCtxt<'_>,
242    (specializing_impl_def_id, parent_impl_def_id): (DefId, DefId),
243) -> bool {
244    // We check that the specializing impl comes from a crate that has specialization enabled,
245    // or if the specializing impl is marked with `allow_internal_unstable`.
246    //
247    // We don't really care if the specialized impl (the parent) is in a crate that has
248    // specialization enabled, since it's not being specialized, and it's already been checked
249    // for coherence.
250    if !tcx.specialization_enabled_in(specializing_impl_def_id.krate) {
251        let span = tcx.def_span(specializing_impl_def_id);
252        if !span.allows_unstable(sym::specialization)
253            && !span.allows_unstable(sym::min_specialization)
254        {
255            return false;
256        }
257    }
258
259    let specializing_impl_trait_header = tcx.impl_trait_header(specializing_impl_def_id);
260
261    // We determine whether there's a subset relationship by:
262    //
263    // - replacing bound vars with placeholders in impl1,
264    // - assuming the where clauses for impl1,
265    // - instantiating impl2 with fresh inference variables,
266    // - unifying,
267    // - attempting to prove the where clauses for impl2
268    //
269    // The last three steps are encapsulated in `fulfill_implication`.
270    //
271    // See RFC 1210 for more details and justification.
272
273    // Currently we do not allow e.g., a negative impl to specialize a positive one
274    if specializing_impl_trait_header.polarity != tcx.impl_polarity(parent_impl_def_id) {
275        return false;
276    }
277
278    // create a parameter environment corresponding to an identity instantiation of the specializing impl,
279    // i.e. the most generic instantiation of the specializing impl.
280    let param_env = tcx.param_env(specializing_impl_def_id);
281
282    // Create an infcx, taking the predicates of the specializing impl as assumptions:
283    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
284
285    let specializing_impl_trait_ref =
286        specializing_impl_trait_header.trait_ref.instantiate_identity();
287    let cause = &ObligationCause::dummy();
288    debug!(
289        "fulfill_implication({:?}, trait_ref={:?} |- {:?} applies)",
290        param_env, specializing_impl_trait_ref, parent_impl_def_id
291    );
292
293    // Attempt to prove that the parent impl applies, given all of the above.
294
295    let ocx = ObligationCtxt::new(&infcx);
296    let specializing_impl_trait_ref = ocx.normalize(cause, param_env, specializing_impl_trait_ref);
297
298    if !ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
299        infcx.dcx().span_delayed_bug(
300            infcx.tcx.def_span(specializing_impl_def_id),
301            format!("failed to fully normalize {specializing_impl_trait_ref}"),
302        );
303        return false;
304    }
305
306    let parent_args = infcx.fresh_args_for_item(DUMMY_SP, parent_impl_def_id);
307    let parent_impl_trait_ref = ocx.normalize(
308        cause,
309        param_env,
310        infcx.tcx.impl_trait_ref(parent_impl_def_id).instantiate(infcx.tcx, parent_args),
311    );
312
313    // do the impls unify? If not, no specialization.
314    let Ok(()) = ocx.eq(cause, param_env, specializing_impl_trait_ref, parent_impl_trait_ref)
315    else {
316        return false;
317    };
318
319    // Now check that the source trait ref satisfies all the where clauses of the target impl.
320    // This is not just for correctness; we also need this to constrain any params that may
321    // only be referenced via projection predicates.
322    let clauses = infcx.tcx.clauses_of(parent_impl_def_id).instantiate(infcx.tcx, parent_args);
323    let obligations = predicates_for_generics(
324        |_, _| cause.clone(),
325        |clause| ocx.normalize(cause, param_env, clause),
326        param_env,
327        clauses,
328    );
329    ocx.register_obligations(obligations);
330
331    let errors = ocx.evaluate_obligations_error_on_ambiguity();
332    if !errors.no_errors() {
333        // no dice!
334        debug!(
335            "fulfill_implication: for impls on {:?} and {:?}, \
336                 could not fulfill: {:?} given {:?}",
337            specializing_impl_trait_ref,
338            parent_impl_trait_ref,
339            errors,
340            param_env.caller_bounds()
341        );
342        return false;
343    }
344
345    // If the parent impl is const, then the specializing impl must be const,
346    // and it must not be *more restrictive* than the parent impl (that is,
347    // it cannot be const in fewer cases than the parent impl).
348    if tcx.is_conditionally_const(parent_impl_def_id) {
349        if !tcx.is_conditionally_const(specializing_impl_def_id) {
350            return false;
351        }
352
353        let const_conditions =
354            infcx.tcx.const_conditions(parent_impl_def_id).instantiate(infcx.tcx, parent_args);
355        let const_conditions = const_conditions
356            .into_iter()
357            .map(|(trait_ref, span)| (ocx.normalize(cause, param_env, trait_ref), span));
358        ocx.register_obligations(const_conditions.into_iter().map(|(trait_ref, _)| {
359            Obligation::new(
360                infcx.tcx,
361                cause.clone(),
362                param_env,
363                trait_ref.to_host_effect_clause(infcx.tcx, ty::BoundConstness::Maybe),
364            )
365        }));
366
367        let errors = ocx.evaluate_obligations_error_on_ambiguity();
368        if !errors.no_errors() {
369            // no dice!
370            debug!(
371                "fulfill_implication: for impls on {:?} and {:?}, \
372                 could not fulfill: {:?} given {:?}",
373                specializing_impl_trait_ref,
374                parent_impl_trait_ref,
375                errors,
376                param_env.caller_bounds()
377            );
378            return false;
379        }
380    }
381
382    debug!(
383        "fulfill_implication: an impl for {:?} specializes {:?}",
384        specializing_impl_trait_ref, parent_impl_trait_ref
385    );
386
387    true
388}
389
390/// Query provider for `specialization_graph_of`.
391pub(super) fn specialization_graph_provider(
392    tcx: TyCtxt<'_>,
393    trait_id: DefId,
394) -> Result<&'_ specialization_graph::Graph, ErrorGuaranteed> {
395    let mut sg = specialization_graph::Graph::new();
396    let overlap_mode = specialization_graph::OverlapMode::get(tcx, trait_id);
397
398    // Skip foreign non-blanket impls whose simplified-self bucket holds no
399    // local impl. This is sound because:
400    // - foreign impls are never overlap-checked, only recorded; `Ancestors`
401    //   reads their parent lazily from metadata instead (the same value).
402    // - a local non-blanket impl is only compared against blanket impls and
403    //   impls in its own bucket (see `filtered_children`), and instantiation
404    //   preserves the simplified type, so kept buckets are complete at every
405    //   level of the tree.
406    // - a local blanket impl, including alias self types which simplify to
407    //   `None`, is compared against every child, so then all buckets are kept;
408    //   pruning them would change error recovery (see impl-unpin.rs, `tait`
409    //   revision).
410    let all_impls = tcx.trait_impls_of(trait_id);
411    let mut trait_impls: Vec<DefId> = all_impls.blanket_impls().to_vec();
412    let has_local_blanket_impl =
413        all_impls.blanket_impls().iter().any(|impl_def_id| impl_def_id.is_local());
414    for (&simplified_self, bucket) in all_impls.non_blanket_impls() {
415        if has_local_blanket_impl || bucket.iter().any(|impl_def_id| impl_def_id.is_local()) {
416            trait_impls.extend(bucket.iter().copied());
417        } else if truecfg!(debug_assertions) {
418            // Assert metadata-derived key matches what the overlap checker recomputes.
419            for &impl_def_id in bucket {
420                let self_ty = tcx.impl_trait_ref(impl_def_id).skip_binder().self_ty();
421                if true {
    {
        match (&fast_reject::simplify_type(tcx, self_ty,
                        TreatParams::InstantiateWithInfer), &Some(simplified_self))
            {
            (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::Some(format_args!("trait_impls_of bucket key disagrees with overlap-check simplification for foreign impl {0:?}",
                                impl_def_id)));
                }
            }
        }
    };
};debug_assert_eq!(
422                    fast_reject::simplify_type(tcx, self_ty, TreatParams::InstantiateWithInfer),
423                    Some(simplified_self),
424                    "trait_impls_of bucket key disagrees with overlap-check \
425                     simplification for foreign impl {impl_def_id:?}",
426                );
427            }
428        }
429    }
430
431    // The coherence checking implementation seems to rely on impls being
432    // iterated over (roughly) in definition order, so we are sorting by
433    // negated `CrateNum` (so remote definitions are visited first) and then
434    // by a flattened version of the `DefIndex`.
435    trait_impls
436        .sort_unstable_by_key(|def_id| (-(def_id.krate.as_u32() as i64), def_id.index.index()));
437
438    let mut errored = Ok(());
439
440    for impl_def_id in trait_impls {
441        if let Some(impl_def_id) = impl_def_id.as_local() {
442            // This is where impl overlap checking happens:
443            let insert_result = sg.insert(tcx, impl_def_id.to_def_id(), overlap_mode);
444            // Report error if there was one.
445            let (overlap, used_to_be_allowed) = match insert_result {
446                Err(overlap) => (Some(overlap), None),
447                Ok(Some(overlap)) => (Some(overlap.error), Some(overlap.kind)),
448                Ok(None) => (None, None),
449            };
450
451            if let Some(overlap) = overlap {
452                errored = errored.and(report_overlap_conflict(
453                    tcx,
454                    overlap,
455                    impl_def_id,
456                    used_to_be_allowed,
457                ));
458            }
459        } else {
460            let parent = tcx.impl_parent(impl_def_id).unwrap_or(trait_id);
461            sg.record_impl_from_cstore(tcx, parent, impl_def_id)
462        }
463    }
464    errored?;
465
466    Ok(tcx.arena.alloc(sg))
467}
468
469// This function is only used when
470// encountering errors and inlining
471// it negatively impacts perf.
472#[cold]
473#[inline(never)]
474fn report_overlap_conflict<'tcx>(
475    tcx: TyCtxt<'tcx>,
476    overlap: OverlapError<'tcx>,
477    impl_def_id: LocalDefId,
478    used_to_be_allowed: Option<FutureCompatOverlapErrorKind>,
479) -> Result<(), ErrorGuaranteed> {
480    let impl_polarity = tcx.impl_polarity(impl_def_id.to_def_id());
481    let other_polarity = tcx.impl_polarity(overlap.with_impl);
482    match (impl_polarity, other_polarity) {
483        (ty::ImplPolarity::Negative, ty::ImplPolarity::Positive) => {
484            Err(report_negative_positive_conflict(
485                tcx,
486                &overlap,
487                impl_def_id,
488                impl_def_id.to_def_id(),
489                overlap.with_impl,
490            ))
491        }
492
493        (ty::ImplPolarity::Positive, ty::ImplPolarity::Negative) => {
494            Err(report_negative_positive_conflict(
495                tcx,
496                &overlap,
497                impl_def_id,
498                overlap.with_impl,
499                impl_def_id.to_def_id(),
500            ))
501        }
502
503        _ => report_conflicting_impls(tcx, overlap, impl_def_id, used_to_be_allowed),
504    }
505}
506
507fn report_negative_positive_conflict<'tcx>(
508    tcx: TyCtxt<'tcx>,
509    overlap: &OverlapError<'tcx>,
510    local_impl_def_id: LocalDefId,
511    negative_impl_def_id: DefId,
512    positive_impl_def_id: DefId,
513) -> ErrorGuaranteed {
514    let mut diag = tcx.dcx().create_err(NegativePositiveConflict {
515        impl_span: tcx.def_span(local_impl_def_id),
516        trait_desc: overlap.trait_ref,
517        self_ty: overlap.self_ty,
518        negative_impl_span: tcx.span_of_impl(negative_impl_def_id),
519        positive_impl_span: tcx.span_of_impl(positive_impl_def_id),
520    });
521
522    for cause in &overlap.intercrate_ambiguity_causes {
523        cause.add_intercrate_ambiguity_hint(&mut diag);
524    }
525
526    diag.emit()
527}
528
529fn report_conflicting_impls<'tcx>(
530    tcx: TyCtxt<'tcx>,
531    overlap: OverlapError<'tcx>,
532    impl_def_id: LocalDefId,
533    used_to_be_allowed: Option<FutureCompatOverlapErrorKind>,
534) -> Result<(), ErrorGuaranteed> {
535    let impl_span = tcx.def_span(impl_def_id);
536
537    // Work to be done after we've built the Diag. We have to define it now
538    // because the lint emit methods don't return back the Diag that's passed
539    // in.
540    fn decorate<'tcx, G: EmissionGuarantee>(
541        tcx: TyCtxt<'tcx>,
542        overlap: &OverlapError<'tcx>,
543        impl_span: Span,
544        err: &mut Diag<'_, G>,
545    ) {
546        match tcx.span_of_impl(overlap.with_impl) {
547            Ok(span) => {
548                err.span_label(span, "first implementation here");
549
550                err.span_label(
551                    impl_span,
552                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("conflicting implementation{0}",
                overlap.self_ty.map_or_else(String::new,
                    |ty|
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!(" for `{0}`", ty))
                            }))))
    })format!(
553                        "conflicting implementation{}",
554                        overlap.self_ty.map_or_else(String::new, |ty| format!(" for `{ty}`"))
555                    ),
556                );
557            }
558            Err(cname) => {
559                let msg = match to_pretty_impl_header(tcx, overlap.with_impl) {
560                    Some(s) => {
561                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("conflicting implementation in crate `{0}`:\n- {1}",
                cname, s))
    })format!("conflicting implementation in crate `{cname}`:\n- {s}")
562                    }
563                    None => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("conflicting implementation in crate `{0}`",
                cname))
    })format!("conflicting implementation in crate `{cname}`"),
564                };
565                err.note(msg);
566            }
567        }
568
569        for cause in &overlap.intercrate_ambiguity_causes {
570            cause.add_intercrate_ambiguity_hint(err);
571        }
572
573        if overlap.involves_placeholder {
574            coherence::add_placeholder_note(err);
575        }
576
577        if !overlap.overflowing_predicates.is_empty() {
578            coherence::suggest_increasing_recursion_limit(
579                tcx,
580                err,
581                &overlap.overflowing_predicates,
582            );
583        }
584    }
585
586    let msg = || {
587        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("conflicting implementations of trait `{0}`{1}",
                overlap.trait_ref.print_trait_sugared(),
                overlap.self_ty.map_or_else(String::new,
                    |ty|
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!(" for type `{0}`", ty))
                            }))))
    })format!(
588            "conflicting implementations of trait `{}`{}",
589            overlap.trait_ref.print_trait_sugared(),
590            overlap.self_ty.map_or_else(String::new, |ty| format!(" for type `{ty}`")),
591        )
592    };
593
594    // Don't report overlap errors if the header references error
595    if let Err(err) = (overlap.trait_ref, overlap.self_ty).error_reported() {
596        return Err(err);
597    }
598
599    match used_to_be_allowed {
600        None => {
601            let reported = if overlap.with_impl.is_local()
602                || tcx.ensure_result().orphan_check_impl(impl_def_id).is_ok()
603            {
604                let mut err = tcx.dcx().struct_span_err(impl_span, msg());
605                err.code(E0119);
606                decorate(tcx, &overlap, impl_span, &mut err);
607                err.emit()
608            } else {
609                tcx.dcx().span_delayed_bug(impl_span, "impl should have failed the orphan check")
610            };
611            Err(reported)
612        }
613        Some(kind) => {
614            let lint = match kind {
615                FutureCompatOverlapErrorKind::LeakCheck => COHERENCE_LEAK_CHECK,
616            };
617            tcx.emit_node_span_lint(
618                lint,
619                tcx.local_def_id_to_hir_id(impl_def_id),
620                impl_span,
621                rustc_errors::DiagDecorator(|err| {
622                    err.primary_message(msg());
623                    decorate(tcx, &overlap, impl_span, err);
624                }),
625            );
626            Ok(())
627        }
628    }
629}