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::Diag;
16use rustc_errors::codes::*;
17use rustc_hir::def_id::{DefId, LocalDefId};
18use rustc_infer::traits::Obligation;
19use rustc_lint_defs::builtin::COHERENCE_LEAK_CHECK;
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_span::{DUMMY_SP, ErrorGuaranteed, Span, bug, sym};
28use specialization_graph::GraphExt;
29use tracing::{debug, instrument};
30
31use crate::diagnostics::NegativePositiveConflict;
32use crate::error_reporting::traits::to_pretty_impl_header;
33use crate::infer::{InferCtxt, TyCtxtInferExt};
34use crate::traits::select::IntercrateAmbiguityCause;
35use crate::traits::{
36    FutureCompatOverlapErrorKind, ObligationCause, ObligationCtxt, coherence,
37    predicates_for_generics,
38};
39
40/// Information pertinent to an overlapping impl error.
41#[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)]
42pub struct OverlapError<'tcx> {
43    pub with_impl: DefId,
44    pub trait_ref: ty::TraitRef<'tcx>,
45    pub self_ty: Option<Ty<'tcx>>,
46    pub intercrate_ambiguity_causes: FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
47    pub involves_placeholder: bool,
48    pub overflowing_predicates: Vec<ty::Predicate<'tcx>>,
49}
50
51/// Given the generic parameters for the requested impl, translate it to the generic parameters
52/// appropriate for the actual item definition (whether it be in that impl,
53/// a parent impl, or the trait).
54///
55/// When we have selected one impl, but are actually using item definitions from
56/// a parent impl providing a default, we need a way to translate between the
57/// type parameters of the two impls. Here the `source_impl` is the one we've
58/// selected, and `source_args` is its generic parameters.
59/// And `target_node` is the impl/trait we're actually going to get the
60/// definition from. The resulting instantiation will map from `target_node`'s
61/// generics to `source_impl`'s generics as instantiated by `source_args`.
62///
63/// For example, consider the following scenario:
64///
65/// ```ignore (illustrative)
66/// trait Foo { ... }
67/// impl<T, U> Foo for (T, U) { ... }  // target impl
68/// impl<V> Foo for (V, V) { ... }     // source impl
69/// ```
70///
71/// Suppose we have selected "source impl" with `V` instantiated with `u32`.
72/// This function will produce an instantiation with `T` and `U` both mapping to `u32`.
73///
74/// where-clauses add some trickiness here, because they can be used to "define"
75/// an argument indirectly:
76///
77/// ```ignore (illustrative)
78/// impl<'a, I, T: 'a> Iterator for Cloned<I>
79///    where I: Iterator<Item = &'a T>, T: Clone
80/// ```
81///
82/// In a case like this, the instantiation for `T` is determined indirectly,
83/// through associated type projection. We deal with such cases by using
84/// *fulfillment* to relate the two impls, requiring that all projections are
85/// resolved.
86pub fn translate_args<'tcx>(
87    infcx: &InferCtxt<'tcx>,
88    param_env: ty::ParamEnv<'tcx>,
89    source_impl: DefId,
90    source_args: GenericArgsRef<'tcx>,
91    target_node: specialization_graph::Node,
92) -> GenericArgsRef<'tcx> {
93    translate_args_with_cause(
94        infcx,
95        param_env,
96        source_impl,
97        source_args,
98        target_node,
99        &ObligationCause::dummy(),
100    )
101}
102
103/// Like [translate_args], but obligations from the parent implementation
104/// are registered with the provided `ObligationCause`.
105///
106/// This is for reporting *region* errors from those bounds. Type errors should
107/// not happen because the specialization graph already checks for those, and
108/// will result in an ICE.
109pub fn translate_args_with_cause<'tcx>(
110    infcx: &InferCtxt<'tcx>,
111    param_env: ty::ParamEnv<'tcx>,
112    source_impl: DefId,
113    source_args: GenericArgsRef<'tcx>,
114    target_node: specialization_graph::Node,
115    cause: &ObligationCause<'tcx>,
116) -> GenericArgsRef<'tcx> {
117    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/specialize/mod.rs:117",
                        "rustc_trait_selection::traits::specialize",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(117u32),
                        ::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!(
118        "translate_args({:?}, {:?}, {:?}, {:?})",
119        param_env, source_impl, source_args, target_node
120    );
121    let source_trait_ref =
122        infcx.tcx.impl_trait_ref(source_impl).instantiate(infcx.tcx, source_args).skip_norm_wip();
123
124    // translate the Self and Param parts of the generic parameters, since those
125    // vary across impls
126    let target_args = match target_node {
127        specialization_graph::Node::Impl(target_impl) => {
128            // no need to translate if we're targeting the impl we started with
129            if source_impl == target_impl {
130                return source_args;
131            }
132
133            fulfill_implication(infcx, param_env, source_trait_ref, source_impl, target_impl, cause)
134                .unwrap_or_else(|_| {
135                    ::rustc_span::macros::bug_impl(None,
    format_args!("When translating generic parameters from {0:?} to {1:?}, the expected specialization failed to hold",
        source_impl, target_impl), Location::caller())bug!(
136                        "When translating generic parameters from {source_impl:?} to \
137                        {target_impl:?}, the expected specialization failed to hold"
138                    )
139                })
140        }
141        specialization_graph::Node::Trait(..) => source_trait_ref.args,
142    };
143
144    // directly inherent the method generics, since those do not vary across impls
145    source_args.rebase_onto(infcx.tcx, source_impl, target_args)
146}
147
148/// Attempt to fulfill all obligations of `target_impl` after unification with
149/// `source_trait_ref`. If successful, returns the generic parameters for *all* the
150/// generics of `target_impl`, including both those needed to unify with
151/// `source_trait_ref` and those whose identity is determined via a where
152/// clause in the impl.
153fn fulfill_implication<'tcx>(
154    infcx: &InferCtxt<'tcx>,
155    param_env: ty::ParamEnv<'tcx>,
156    source_trait_ref: ty::TraitRef<'tcx>,
157    source_impl: DefId,
158    target_impl: DefId,
159    cause: &ObligationCause<'tcx>,
160) -> Result<GenericArgsRef<'tcx>, NoSolution> {
161    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/specialize/mod.rs:161",
                        "rustc_trait_selection::traits::specialize",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(161u32),
                        ::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!(
162        "fulfill_implication({:?}, trait_ref={:?} |- {:?} applies)",
163        param_env, source_trait_ref, target_impl
164    );
165
166    let ocx = ObligationCtxt::new(infcx);
167    let source_trait_ref = ocx.normalize(cause, param_env, Unnormalized::new_wip(source_trait_ref));
168
169    if !ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
170        infcx.dcx().span_delayed_bug(
171            infcx.tcx.def_span(source_impl),
172            ::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}"),
173        );
174        return Err(NoSolution);
175    }
176
177    let target_args = infcx.fresh_args_for_item(DUMMY_SP, target_impl);
178    let target_trait_ref = ocx.normalize(
179        cause,
180        param_env,
181        infcx.tcx.impl_trait_ref(target_impl).instantiate(infcx.tcx, target_args),
182    );
183
184    // do the impls unify? If not, no specialization.
185    ocx.eq(cause, param_env, source_trait_ref, target_trait_ref)?;
186
187    // Now check that the source trait ref satisfies all the where clauses of the target impl.
188    // This is not just for correctness; we also need this to constrain any params that may
189    // only be referenced via projection predicates.
190    let clauses = infcx.tcx.clauses_of(target_impl).instantiate(infcx.tcx, target_args);
191    let obligations = predicates_for_generics(
192        |_, _| cause.clone(),
193        |clause| ocx.normalize(cause, param_env, clause),
194        param_env,
195        clauses,
196    );
197    ocx.register_obligations(obligations);
198
199    let errors = ocx.evaluate_obligations_error_on_ambiguity();
200    if !errors.no_errors() {
201        // no dice!
202        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/specialize/mod.rs:202",
                        "rustc_trait_selection::traits::specialize",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(202u32),
                        ::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) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
203            "fulfill_implication: for impls on {:?} and {:?}, \
204                 could not fulfill: {:?} given {:?}",
205            source_trait_ref, target_trait_ref, errors, param_env
206        );
207        return Err(NoSolution);
208    }
209
210    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/specialize/mod.rs:210",
                        "rustc_trait_selection::traits::specialize",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(210u32),
                        ::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!(
211        "fulfill_implication: an impl for {:?} specializes {:?}",
212        source_trait_ref, target_trait_ref
213    );
214
215    // Now resolve the *generic parameters* we built for the target earlier, replacing
216    // the inference variables inside with whatever we got from fulfillment.
217    Ok(infcx.deeply_resolve_ignoring_regions(target_args))
218}
219
220pub(super) fn specialization_enabled_in(tcx: TyCtxt<'_>, _: LocalCrate) -> bool {
221    tcx.features().specialization() || tcx.features().min_specialization()
222}
223
224/// Is `specializing_impl_def_id` a specialization of `parent_impl_def_id`?
225///
226/// For every type that could apply to `specializing_impl_def_id`, we prove that
227/// the `parent_impl_def_id` also applies (i.e. it has a valid impl header and
228/// its where-clauses hold).
229///
230/// For the purposes of const traits, we also check that the specializing
231/// impl is not more restrictive than the parent impl. That is, if the
232/// `parent_impl_def_id` is a const impl (conditionally based off of some `[const]`
233/// bounds), then `specializing_impl_def_id` must also be const for the same
234/// set of types.
235{}
#[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("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(235u32),
                                    ::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 /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/specialize/mod.rs:284",
                                    "rustc_trait_selection::traits::specialize",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(284u32),
                                    ::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 /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/specialize/mod.rs:330",
                                        "rustc_trait_selection::traits::specialize",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
                                        ::tracing_core::__macro_support::Option::Some(330u32),
                                        ::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) 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 /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/specialize/mod.rs:363",
                                            "rustc_trait_selection::traits::specialize",
                                            ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(363u32),
                                            ::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) 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 /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/specialize/mod.rs:372",
                                    "rustc_trait_selection::traits::specialize",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/specialize/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(372u32),
                                    ::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")]
236pub(super) fn specializes(
237    tcx: TyCtxt<'_>,
238    (specializing_impl_def_id, parent_impl_def_id): (DefId, DefId),
239) -> bool {
240    // We check that the specializing impl comes from a crate that has specialization enabled,
241    // or if the specializing impl is marked with `allow_internal_unstable`.
242    //
243    // We don't really care if the specialized impl (the parent) is in a crate that has
244    // specialization enabled, since it's not being specialized, and it's already been checked
245    // for coherence.
246    if !tcx.specialization_enabled_in(specializing_impl_def_id.krate) {
247        let span = tcx.def_span(specializing_impl_def_id);
248        if !span.allows_unstable(sym::specialization)
249            && !span.allows_unstable(sym::min_specialization)
250        {
251            return false;
252        }
253    }
254
255    let specializing_impl_trait_header = tcx.impl_trait_header(specializing_impl_def_id);
256
257    // We determine whether there's a subset relationship by:
258    //
259    // - replacing bound vars with placeholders in impl1,
260    // - assuming the where clauses for impl1,
261    // - instantiating impl2 with fresh inference variables,
262    // - unifying,
263    // - attempting to prove the where clauses for impl2
264    //
265    // The last three steps are encapsulated in `fulfill_implication`.
266    //
267    // See RFC 1210 for more details and justification.
268
269    // Currently we do not allow e.g., a negative impl to specialize a positive one
270    if specializing_impl_trait_header.polarity != tcx.impl_polarity(parent_impl_def_id) {
271        return false;
272    }
273
274    // create a parameter environment corresponding to an identity instantiation of the specializing impl,
275    // i.e. the most generic instantiation of the specializing impl.
276    let param_env = tcx.param_env(specializing_impl_def_id);
277
278    // Create an infcx, taking the predicates of the specializing impl as assumptions:
279    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
280
281    let specializing_impl_trait_ref =
282        specializing_impl_trait_header.trait_ref.instantiate_identity();
283    let cause = &ObligationCause::dummy();
284    debug!(
285        "fulfill_implication({:?}, trait_ref={:?} |- {:?} applies)",
286        param_env, specializing_impl_trait_ref, parent_impl_def_id
287    );
288
289    // Attempt to prove that the parent impl applies, given all of the above.
290
291    let ocx = ObligationCtxt::new(&infcx);
292    let specializing_impl_trait_ref = ocx.normalize(cause, param_env, specializing_impl_trait_ref);
293
294    if !ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
295        infcx.dcx().span_delayed_bug(
296            infcx.tcx.def_span(specializing_impl_def_id),
297            format!("failed to fully normalize {specializing_impl_trait_ref}"),
298        );
299        return false;
300    }
301
302    let parent_args = infcx.fresh_args_for_item(DUMMY_SP, parent_impl_def_id);
303    let parent_impl_trait_ref = ocx.normalize(
304        cause,
305        param_env,
306        infcx.tcx.impl_trait_ref(parent_impl_def_id).instantiate(infcx.tcx, parent_args),
307    );
308
309    // do the impls unify? If not, no specialization.
310    let Ok(()) = ocx.eq(cause, param_env, specializing_impl_trait_ref, parent_impl_trait_ref)
311    else {
312        return false;
313    };
314
315    // Now check that the source trait ref satisfies all the where clauses of the target impl.
316    // This is not just for correctness; we also need this to constrain any params that may
317    // only be referenced via projection predicates.
318    let clauses = infcx.tcx.clauses_of(parent_impl_def_id).instantiate(infcx.tcx, parent_args);
319    let obligations = predicates_for_generics(
320        |_, _| cause.clone(),
321        |clause| ocx.normalize(cause, param_env, clause),
322        param_env,
323        clauses,
324    );
325    ocx.register_obligations(obligations);
326
327    let errors = ocx.evaluate_obligations_error_on_ambiguity();
328    if !errors.no_errors() {
329        // no dice!
330        debug!(
331            "fulfill_implication: for impls on {:?} and {:?}, \
332                 could not fulfill: {:?} given {:?}",
333            specializing_impl_trait_ref, parent_impl_trait_ref, errors, param_env
334        );
335        return false;
336    }
337
338    // If the parent impl is const, then the specializing impl must be const,
339    // and it must not be *more restrictive* than the parent impl (that is,
340    // it cannot be const in fewer cases than the parent impl).
341    if tcx.is_conditionally_const(parent_impl_def_id) {
342        if !tcx.is_conditionally_const(specializing_impl_def_id) {
343            return false;
344        }
345
346        let const_conditions =
347            infcx.tcx.const_conditions(parent_impl_def_id).instantiate(infcx.tcx, parent_args);
348        let const_conditions = const_conditions
349            .into_iter()
350            .map(|(trait_ref, span)| (ocx.normalize(cause, param_env, trait_ref), span));
351        ocx.register_obligations(const_conditions.into_iter().map(|(trait_ref, _)| {
352            Obligation::new(
353                infcx.tcx,
354                cause.clone(),
355                param_env,
356                trait_ref.to_host_effect_clause(infcx.tcx, ty::BoundConstness::Maybe),
357            )
358        }));
359
360        let errors = ocx.evaluate_obligations_error_on_ambiguity();
361        if !errors.no_errors() {
362            // no dice!
363            debug!(
364                "fulfill_implication: for impls on {:?} and {:?}, \
365                 could not fulfill: {:?} given {:?}",
366                specializing_impl_trait_ref, parent_impl_trait_ref, errors, param_env
367            );
368            return false;
369        }
370    }
371
372    debug!(
373        "fulfill_implication: an impl for {:?} specializes {:?}",
374        specializing_impl_trait_ref, parent_impl_trait_ref
375    );
376
377    true
378}
379
380/// Query provider for `specialization_graph_of`.
381pub(super) fn specialization_graph_provider(
382    tcx: TyCtxt<'_>,
383    trait_id: DefId,
384) -> Result<&'_ specialization_graph::Graph, ErrorGuaranteed> {
385    let mut sg = specialization_graph::Graph::new();
386    let overlap_mode = specialization_graph::OverlapMode::get(tcx, trait_id);
387
388    // Skip foreign non-blanket impls whose simplified-self bucket holds no
389    // local impl. This is sound because:
390    // - foreign impls are never overlap-checked, only recorded; `Ancestors`
391    //   reads their parent lazily from metadata instead (the same value).
392    // - a local non-blanket impl is only compared against blanket impls and
393    //   impls in its own bucket (see `filtered_children`), and instantiation
394    //   preserves the simplified type, so kept buckets are complete at every
395    //   level of the tree.
396    // - a local blanket impl, including alias self types which simplify to
397    //   `None`, is compared against every child, so then all buckets are kept;
398    //   pruning them would change error recovery (see impl-unpin.rs, `tait`
399    //   revision).
400    let all_impls = tcx.trait_impls_of(trait_id);
401    let mut trait_impls: Vec<DefId> = all_impls.blanket_impls().to_vec();
402    let has_local_blanket_impl =
403        all_impls.blanket_impls().iter().any(|impl_def_id| impl_def_id.is_local());
404    for (&simplified_self, bucket) in all_impls.non_blanket_impls() {
405        if has_local_blanket_impl || bucket.iter().any(|impl_def_id| impl_def_id.is_local()) {
406            trait_impls.extend(bucket.iter().copied());
407        } else if truecfg!(debug_assertions) {
408            // Assert metadata-derived key matches what the overlap checker recomputes.
409            for &impl_def_id in bucket {
410                let self_ty = tcx.impl_trait_ref(impl_def_id).skip_binder().self_ty();
411                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!(
412                    fast_reject::simplify_type(tcx, self_ty, TreatParams::InstantiateWithInfer),
413                    Some(simplified_self),
414                    "trait_impls_of bucket key disagrees with overlap-check \
415                     simplification for foreign impl {impl_def_id:?}",
416                );
417            }
418        }
419    }
420
421    // The coherence checking implementation seems to rely on impls being
422    // iterated over (roughly) in definition order, so we are sorting by
423    // negated `CrateNum` (so remote definitions are visited first) and then
424    // by a flattened version of the `DefIndex`.
425    trait_impls
426        .sort_unstable_by_key(|def_id| (-(def_id.krate.as_u32() as i64), def_id.index.index()));
427
428    let mut errored = Ok(());
429
430    for impl_def_id in trait_impls {
431        if let Some(impl_def_id) = impl_def_id.as_local() {
432            // This is where impl overlap checking happens:
433            let insert_result = sg.insert(tcx, impl_def_id.to_def_id(), overlap_mode);
434            // Report error if there was one.
435            let (overlap, used_to_be_allowed) = match insert_result {
436                Err(overlap) => (Some(overlap), None),
437                Ok(Some(overlap)) => (Some(overlap.error), Some(overlap.kind)),
438                Ok(None) => (None, None),
439            };
440
441            if let Some(overlap) = overlap {
442                errored = errored.and(report_overlap_conflict(
443                    tcx,
444                    overlap,
445                    impl_def_id,
446                    used_to_be_allowed,
447                ));
448            }
449        } else {
450            let parent = tcx.impl_parent(impl_def_id).unwrap_or(trait_id);
451            sg.record_impl_from_cstore(tcx, parent, impl_def_id)
452        }
453    }
454    errored?;
455
456    Ok(tcx.arena.alloc(sg))
457}
458
459// This function is only used when
460// encountering errors and inlining
461// it negatively impacts perf.
462#[cold]
463#[inline(never)]
464fn report_overlap_conflict<'tcx>(
465    tcx: TyCtxt<'tcx>,
466    overlap: OverlapError<'tcx>,
467    impl_def_id: LocalDefId,
468    used_to_be_allowed: Option<FutureCompatOverlapErrorKind>,
469) -> Result<(), ErrorGuaranteed> {
470    let impl_polarity = tcx.impl_polarity(impl_def_id.to_def_id());
471    let other_polarity = tcx.impl_polarity(overlap.with_impl);
472    match (impl_polarity, other_polarity) {
473        (ty::ImplPolarity::Negative, ty::ImplPolarity::Positive) => {
474            Err(report_negative_positive_conflict(
475                tcx,
476                &overlap,
477                impl_def_id,
478                impl_def_id.to_def_id(),
479                overlap.with_impl,
480            ))
481        }
482
483        (ty::ImplPolarity::Positive, ty::ImplPolarity::Negative) => {
484            Err(report_negative_positive_conflict(
485                tcx,
486                &overlap,
487                impl_def_id,
488                overlap.with_impl,
489                impl_def_id.to_def_id(),
490            ))
491        }
492
493        _ => report_conflicting_impls(tcx, overlap, impl_def_id, used_to_be_allowed),
494    }
495}
496
497fn report_negative_positive_conflict<'tcx>(
498    tcx: TyCtxt<'tcx>,
499    overlap: &OverlapError<'tcx>,
500    local_impl_def_id: LocalDefId,
501    negative_impl_def_id: DefId,
502    positive_impl_def_id: DefId,
503) -> ErrorGuaranteed {
504    let mut diag = tcx.dcx().create_err(NegativePositiveConflict {
505        impl_span: tcx.def_span(local_impl_def_id),
506        trait_desc: overlap.trait_ref,
507        self_ty: overlap.self_ty,
508        negative_impl_span: tcx.span_of_impl(negative_impl_def_id),
509        positive_impl_span: tcx.span_of_impl(positive_impl_def_id),
510    });
511
512    for cause in &overlap.intercrate_ambiguity_causes {
513        cause.add_intercrate_ambiguity_hint(&mut diag);
514    }
515
516    diag.emit_err()
517}
518
519fn report_conflicting_impls<'tcx>(
520    tcx: TyCtxt<'tcx>,
521    overlap: OverlapError<'tcx>,
522    impl_def_id: LocalDefId,
523    used_to_be_allowed: Option<FutureCompatOverlapErrorKind>,
524) -> Result<(), ErrorGuaranteed> {
525    let impl_span = tcx.def_span(impl_def_id);
526
527    // Work to be done after we've built the Diag. We have to define it now
528    // because the lint emit methods don't return back the Diag that's passed
529    // in.
530    fn decorate<'tcx>(
531        tcx: TyCtxt<'tcx>,
532        overlap: &OverlapError<'tcx>,
533        impl_span: Span,
534        err: &mut Diag<'_>,
535    ) {
536        match tcx.span_of_impl(overlap.with_impl) {
537            Ok(span) => {
538                err.span_label(span, "first implementation here");
539
540                err.span_label(
541                    impl_span,
542                    ::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!(
543                        "conflicting implementation{}",
544                        overlap.self_ty.map_or_else(String::new, |ty| format!(" for `{ty}`"))
545                    ),
546                );
547            }
548            Err(cname) => {
549                let msg = match to_pretty_impl_header(tcx, overlap.with_impl) {
550                    Some(s) => {
551                        ::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}")
552                    }
553                    None => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("conflicting implementation in crate `{0}`",
                cname))
    })format!("conflicting implementation in crate `{cname}`"),
554                };
555                err.note(msg);
556            }
557        }
558
559        for cause in &overlap.intercrate_ambiguity_causes {
560            cause.add_intercrate_ambiguity_hint(err);
561        }
562
563        if overlap.involves_placeholder {
564            coherence::add_placeholder_note(err);
565        }
566
567        if !overlap.overflowing_predicates.is_empty() {
568            coherence::suggest_increasing_recursion_limit(
569                tcx,
570                err,
571                &overlap.overflowing_predicates,
572            );
573        }
574    }
575
576    let msg = || {
577        ::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!(
578            "conflicting implementations of trait `{}`{}",
579            overlap.trait_ref.print_trait_sugared(),
580            overlap.self_ty.map_or_else(String::new, |ty| format!(" for type `{ty}`")),
581        )
582    };
583
584    // Don't report overlap errors if the header references error
585    if let Err(err) = (overlap.trait_ref, overlap.self_ty).error_reported() {
586        return Err(err);
587    }
588
589    match used_to_be_allowed {
590        None => {
591            let reported = if overlap.with_impl.is_local()
592                || tcx.ensure_result().orphan_check_impl(impl_def_id).is_ok()
593            {
594                let mut err = tcx.dcx().struct_span_err(impl_span, msg());
595                err.code(E0119);
596                decorate(tcx, &overlap, impl_span, &mut err);
597                err.emit_err()
598            } else {
599                tcx.dcx().span_delayed_bug(impl_span, "impl should have failed the orphan check")
600            };
601            Err(reported)
602        }
603        Some(kind) => {
604            let lint = match kind {
605                FutureCompatOverlapErrorKind::LeakCheck => COHERENCE_LEAK_CHECK,
606            };
607            tcx.emit_node_span_lint(
608                lint,
609                tcx.local_def_id_to_hir_id(impl_def_id),
610                impl_span,
611                rustc_errors::DiagDecorator(|err| {
612                    err.primary_message(msg());
613                    decorate(tcx, &overlap, impl_span, err);
614                }),
615            );
616            Ok(())
617        }
618    }
619}