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