Skip to main content

rustc_trait_selection/traits/
coherence.rs

1//! See Rustc Dev Guide chapters on [trait-resolution] and [trait-specialization] for more info on
2//! how this works.
3//!
4//! [trait-resolution]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
5//! [trait-specialization]: https://rustc-dev-guide.rust-lang.org/traits/specialization.html
6
7use std::fmt::Debug;
8
9use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
10use rustc_errors::{Diag, EmissionGuarantee};
11use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
12use rustc_hir::find_attr;
13use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, TyCtxtInferExt};
14use rustc_infer::traits::PredicateObligations;
15use rustc_macros::{TypeFoldable, TypeVisitable};
16use rustc_middle::bug;
17use rustc_middle::traits::query::NoSolution;
18use rustc_middle::traits::solve::{CandidateSource, Certainty, Goal};
19use rustc_middle::traits::specialization_graph::OverlapMode;
20use rustc_middle::ty::fast_reject::DeepRejectCtxt;
21use rustc_middle::ty::{
22    self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
23    Unnormalized,
24};
25pub use rustc_next_trait_solver::coherence::*;
26use rustc_next_trait_solver::solve::SolverDelegateEvalExt;
27use rustc_span::{DUMMY_SP, Span};
28use tracing::{debug, instrument, warn};
29
30use super::ObligationCtxt;
31use crate::error_reporting::traits::suggest_new_overflow_limit;
32use crate::infer::InferOk;
33use crate::solve::inspect::{InferCtxtProofTreeExt, InspectGoal, ProofTreeVisitor};
34use crate::solve::{SolverDelegate, deeply_normalize_for_diagnostics, inspect};
35use crate::traits::query::evaluate_obligation::InferCtxtExt;
36use crate::traits::select::IntercrateAmbiguityCause;
37use crate::traits::{
38    FulfillmentErrorCode, NormalizeExt, Obligation, ObligationCause, PredicateObligation,
39    SelectionContext, SkipLeakCheck, util,
40};
41
42/// The "header" of an impl is everything outside the body: a Self type, a trait
43/// ref (in the case of a trait impl), and a set of predicates (from the
44/// bounds / where-clauses).
45#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ImplHeader<'tcx> {
    #[inline]
    fn clone(&self) -> ImplHeader<'tcx> {
        ImplHeader {
            impl_args: ::core::clone::Clone::clone(&self.impl_args),
            self_ty: ::core::clone::Clone::clone(&self.self_ty),
            trait_ref: ::core::clone::Clone::clone(&self.trait_ref),
            predicates: ::core::clone::Clone::clone(&self.predicates),
        }
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ImplHeader<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f, "ImplHeader",
            "impl_args", &self.impl_args, "self_ty", &self.self_ty,
            "trait_ref", &self.trait_ref, "predicates", &&self.predicates)
    }
}Debug, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for ImplHeader<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        ImplHeader {
                            impl_args: __binding_0,
                            self_ty: __binding_1,
                            trait_ref: __binding_2,
                            predicates: __binding_3 } => {
                            ImplHeader {
                                impl_args: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                self_ty: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                                trait_ref: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
                                        __folder)?,
                                predicates: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_3,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    ImplHeader {
                        impl_args: __binding_0,
                        self_ty: __binding_1,
                        trait_ref: __binding_2,
                        predicates: __binding_3 } => {
                        ImplHeader {
                            impl_args: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            self_ty: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                            trait_ref: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
                                __folder),
                            predicates: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_3,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for ImplHeader<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    ImplHeader {
                        impl_args: ref __binding_0,
                        self_ty: ref __binding_1,
                        trait_ref: ref __binding_2,
                        predicates: ref __binding_3 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_3,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
46pub struct ImplHeader<'tcx> {
47    pub impl_args: ty::GenericArgsRef<'tcx>,
48    pub self_ty: Ty<'tcx>,
49    pub trait_ref: Option<ty::TraitRef<'tcx>>,
50    pub predicates: Vec<ty::Predicate<'tcx>>,
51}
52
53pub struct OverlapResult<'tcx> {
54    pub impl_header: ImplHeader<'tcx>,
55    pub intercrate_ambiguity_causes: FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
56
57    /// `true` if the overlap might've been permitted before the shift
58    /// to universes.
59    pub involves_placeholder: bool,
60
61    /// Used in the new solver to suggest increasing the recursion limit.
62    pub overflowing_predicates: Vec<ty::Predicate<'tcx>>,
63}
64
65pub fn add_placeholder_note<G: EmissionGuarantee>(err: &mut Diag<'_, G>) {
66    err.note(
67        "this behavior recently changed as a result of a bug fix; \
68         see rust-lang/rust#56105 for details",
69    );
70}
71
72pub(crate) fn suggest_increasing_recursion_limit<'tcx, G: EmissionGuarantee>(
73    tcx: TyCtxt<'tcx>,
74    err: &mut Diag<'_, G>,
75    overflowing_predicates: &[ty::Predicate<'tcx>],
76) {
77    for pred in overflowing_predicates {
78        err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("overflow evaluating the requirement `{0}`",
                pred))
    })format!("overflow evaluating the requirement `{}`", pred));
79    }
80
81    suggest_new_overflow_limit(tcx, err);
82}
83
84#[derive(#[automatically_derived]
impl ::core::fmt::Debug for TrackAmbiguityCauses {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                TrackAmbiguityCauses::Yes => "Yes",
                TrackAmbiguityCauses::No => "No",
            })
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for TrackAmbiguityCauses {
    #[inline]
    fn clone(&self) -> TrackAmbiguityCauses { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for TrackAmbiguityCauses { }Copy)]
85enum TrackAmbiguityCauses {
86    Yes,
87    No,
88}
89
90impl TrackAmbiguityCauses {
91    fn is_yes(self) -> bool {
92        match self {
93            TrackAmbiguityCauses::Yes => true,
94            TrackAmbiguityCauses::No => false,
95        }
96    }
97}
98
99/// If there are types that satisfy both impls, returns `Some`
100/// with a suitably-freshened `ImplHeader` with those types
101/// instantiated. Otherwise, returns `None`.
102#[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("overlapping_inherent_impls",
                                    "rustc_trait_selection::traits::coherence",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                    ::tracing_core::__macro_support::Option::Some(102u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::coherence"),
                                    ::tracing_core::field::FieldSet::new(&["impl1_def_id",
                                                    "impl2_def_id", "overlap_mode"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl1_def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl2_def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&overlap_mode)
                                                            as &dyn 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: Option<OverlapResult<'_>> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let self_ty1 = tcx.type_of(impl1_def_id).skip_binder();
            let self_ty2 = tcx.type_of(impl2_def_id).skip_binder();
            let may_overlap =
                DeepRejectCtxt::relate_infer_infer(tcx).types_may_unify(self_ty1,
                    self_ty2);
            if !may_overlap {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/coherence.rs:119",
                                        "rustc_trait_selection::traits::coherence",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                        ::tracing_core::__macro_support::Option::Some(119u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::coherence"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("overlapping_inherent_impls: fast_reject early-exit")
                                                            as &dyn Value))])
                            });
                    } else { ; }
                };
                return None;
            }
            overlapping_impls(tcx, impl1_def_id, impl2_def_id,
                skip_leak_check, overlap_mode, false)
        }
    }
}#[instrument(skip(tcx, skip_leak_check), level = "debug")]
103pub fn overlapping_inherent_impls(
104    tcx: TyCtxt<'_>,
105    impl1_def_id: DefId,
106    impl2_def_id: DefId,
107    skip_leak_check: SkipLeakCheck,
108    overlap_mode: OverlapMode,
109) -> Option<OverlapResult<'_>> {
110    // Before doing expensive operations like entering an inference context, do
111    // a quick check via fast_reject to tell if the impl headers could possibly
112    // unify.
113    let self_ty1 = tcx.type_of(impl1_def_id).skip_binder();
114    let self_ty2 = tcx.type_of(impl2_def_id).skip_binder();
115    let may_overlap = DeepRejectCtxt::relate_infer_infer(tcx).types_may_unify(self_ty1, self_ty2);
116
117    if !may_overlap {
118        // Some types involved are definitely different, so the impls couldn't possibly overlap.
119        debug!("overlapping_inherent_impls: fast_reject early-exit");
120        return None;
121    }
122
123    overlapping_impls(tcx, impl1_def_id, impl2_def_id, skip_leak_check, overlap_mode, false)
124}
125
126/// If there are types that satisfy both impls, returns `Some`
127/// with a suitably-freshened `ImplHeader` with those types
128/// instantiated. Otherwise, returns `None`.
129#[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("overlapping_trait_impls",
                                    "rustc_trait_selection::traits::coherence",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                    ::tracing_core::__macro_support::Option::Some(129u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::coherence"),
                                    ::tracing_core::field::FieldSet::new(&["impl1_def_id",
                                                    "impl2_def_id", "overlap_mode"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl1_def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl2_def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&overlap_mode)
                                                            as &dyn 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: Option<OverlapResult<'_>> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let impl1_args =
                tcx.impl_trait_ref(impl1_def_id).skip_binder().args;
            let impl2_args =
                tcx.impl_trait_ref(impl2_def_id).skip_binder().args;
            let may_overlap =
                DeepRejectCtxt::relate_infer_infer(tcx).args_may_unify(impl1_args,
                    impl2_args);
            if !may_overlap {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/coherence.rs:147",
                                        "rustc_trait_selection::traits::coherence",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                        ::tracing_core::__macro_support::Option::Some(147u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::coherence"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("overlapping_impls: fast_reject early-exit")
                                                            as &dyn Value))])
                            });
                    } else { ; }
                };
                return None;
            }
            overlapping_impls(tcx, impl1_def_id, impl2_def_id,
                skip_leak_check, overlap_mode, true)
        }
    }
}#[instrument(skip(tcx, skip_leak_check), level = "debug")]
130pub fn overlapping_trait_impls(
131    tcx: TyCtxt<'_>,
132    impl1_def_id: DefId,
133    impl2_def_id: DefId,
134    skip_leak_check: SkipLeakCheck,
135    overlap_mode: OverlapMode,
136) -> Option<OverlapResult<'_>> {
137    // Before doing expensive operations like entering an inference context, do
138    // a quick check via fast_reject to tell if the impl headers could possibly
139    // unify.
140    let impl1_args = tcx.impl_trait_ref(impl1_def_id).skip_binder().args;
141    let impl2_args = tcx.impl_trait_ref(impl2_def_id).skip_binder().args;
142    let may_overlap =
143        DeepRejectCtxt::relate_infer_infer(tcx).args_may_unify(impl1_args, impl2_args);
144
145    if !may_overlap {
146        // Some types involved are definitely different, so the impls couldn't possibly overlap.
147        debug!("overlapping_impls: fast_reject early-exit");
148        return None;
149    }
150
151    overlapping_impls(tcx, impl1_def_id, impl2_def_id, skip_leak_check, overlap_mode, true)
152}
153
154fn overlapping_impls(
155    tcx: TyCtxt<'_>,
156    impl1_def_id: DefId,
157    impl2_def_id: DefId,
158    skip_leak_check: SkipLeakCheck,
159    overlap_mode: OverlapMode,
160    is_of_trait: bool,
161) -> Option<OverlapResult<'_>> {
162    if tcx.next_trait_solver_in_coherence() {
163        overlap(
164            tcx,
165            TrackAmbiguityCauses::Yes,
166            skip_leak_check,
167            impl1_def_id,
168            impl2_def_id,
169            overlap_mode,
170            is_of_trait,
171        )
172    } else {
173        let _overlap_with_bad_diagnostics = overlap(
174            tcx,
175            TrackAmbiguityCauses::No,
176            skip_leak_check,
177            impl1_def_id,
178            impl2_def_id,
179            overlap_mode,
180            is_of_trait,
181        )?;
182
183        // In the case where we detect an error, run the check again, but
184        // this time tracking intercrate ambiguity causes for better
185        // diagnostics. (These take time and can lead to false errors.)
186        let overlap = overlap(
187            tcx,
188            TrackAmbiguityCauses::Yes,
189            skip_leak_check,
190            impl1_def_id,
191            impl2_def_id,
192            overlap_mode,
193            is_of_trait,
194        )
195        .unwrap();
196        Some(overlap)
197    }
198}
199
200fn fresh_impl_header<'tcx>(
201    infcx: &InferCtxt<'tcx>,
202    impl_def_id: DefId,
203    is_of_trait: bool,
204) -> ImplHeader<'tcx> {
205    let tcx = infcx.tcx;
206    let impl_args = infcx.fresh_args_for_item(DUMMY_SP, impl_def_id);
207
208    ImplHeader {
209        impl_args,
210        self_ty: tcx.type_of(impl_def_id).instantiate(tcx, impl_args).skip_norm_wip(),
211        trait_ref: is_of_trait
212            .then(|| tcx.impl_trait_ref(impl_def_id).instantiate(tcx, impl_args).skip_norm_wip()),
213        predicates: tcx
214            .predicates_of(impl_def_id)
215            .instantiate(tcx, impl_args)
216            .iter()
217            .map(|(c, _)| c.skip_norm_wip().as_predicate())
218            .collect(),
219    }
220}
221
222fn fresh_impl_header_normalized<'tcx>(
223    infcx: &InferCtxt<'tcx>,
224    param_env: ty::ParamEnv<'tcx>,
225    impl_def_id: DefId,
226    is_of_trait: bool,
227) -> ImplHeader<'tcx> {
228    let header = fresh_impl_header(infcx, impl_def_id, is_of_trait);
229
230    let InferOk { value: mut header, obligations } =
231        infcx.at(&ObligationCause::dummy(), param_env).normalize(Unnormalized::new_wip(header));
232
233    header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
234    header
235}
236
237/// Can both impl `a` and impl `b` be satisfied by a common type (including
238/// where-clauses)? If so, returns an `ImplHeader` that unifies the two impls.
239#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("overlap",
                                    "rustc_trait_selection::traits::coherence",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                    ::tracing_core::__macro_support::Option::Some(239u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::coherence"),
                                    ::tracing_core::field::FieldSet::new(&["track_ambiguity_causes",
                                                    "skip_leak_check", "impl1_def_id", "impl2_def_id",
                                                    "overlap_mode", "is_of_trait"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&track_ambiguity_causes)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&skip_leak_check)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl1_def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl2_def_id)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&overlap_mode)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&is_of_trait as
                                                            &dyn 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: Option<OverlapResult<'tcx>> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            if overlap_mode.use_negative_impl() {
                if impl_intersection_has_negative_obligation(tcx,
                            impl1_def_id, impl2_def_id, is_of_trait) ||
                        impl_intersection_has_negative_obligation(tcx, impl2_def_id,
                            impl1_def_id, is_of_trait) {
                    return None;
                }
            }
            let infcx =
                tcx.infer_ctxt().skip_leak_check(skip_leak_check.is_yes()).with_next_trait_solver(tcx.next_trait_solver_in_coherence()).build(TypingMode::Coherence);
            let selcx = &mut SelectionContext::new(&infcx);
            if track_ambiguity_causes.is_yes() {
                selcx.enable_tracking_intercrate_ambiguity_causes();
            }
            let param_env = ty::ParamEnv::empty();
            let impl1_header =
                if tcx.next_trait_solver_in_coherence() {
                    fresh_impl_header(selcx.infcx, impl1_def_id, is_of_trait)
                } else {
                    fresh_impl_header_normalized(selcx.infcx, param_env,
                        impl1_def_id, is_of_trait)
                };
            let impl2_header =
                if tcx.next_trait_solver_in_coherence() {
                    fresh_impl_header(selcx.infcx, impl2_def_id, is_of_trait)
                } else {
                    fresh_impl_header_normalized(selcx.infcx, param_env,
                        impl2_def_id, is_of_trait)
                };
            let mut obligations =
                equate_impl_headers(selcx.infcx, param_env, &impl1_header,
                        &impl2_header)?;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/coherence.rs:293",
                                    "rustc_trait_selection::traits::coherence",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                    ::tracing_core::__macro_support::Option::Some(293u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::coherence"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("overlap: unification check succeeded")
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            obligations.extend([&impl1_header.predicates,
                                    &impl2_header.predicates].into_iter().flatten().map(|&predicate|
                        Obligation::new(infcx.tcx, ObligationCause::dummy(),
                            param_env, predicate)));
            let mut overflowing_predicates = Vec::new();
            if overlap_mode.use_implicit_negative() {
                match impl_intersection_has_impossible_obligation(selcx,
                        &obligations) {
                    IntersectionHasImpossibleObligations::Yes => return None,
                    IntersectionHasImpossibleObligations::No {
                        overflowing_predicates: p } => {
                        overflowing_predicates = p
                    }
                }
            }
            if infcx.leak_check(ty::UniverseIndex::ROOT, None).is_err() {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/coherence.rs:314",
                                        "rustc_trait_selection::traits::coherence",
                                        ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                        ::tracing_core::__macro_support::Option::Some(314u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::coherence"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("overlap: leak check failed")
                                                            as &dyn Value))])
                            });
                    } else { ; }
                };
                return None;
            }
            let intercrate_ambiguity_causes =
                if !overlap_mode.use_implicit_negative() {
                    Default::default()
                } else if infcx.next_trait_solver() {
                    compute_intercrate_ambiguity_causes(&infcx, &obligations)
                } else { selcx.take_intercrate_ambiguity_causes() };
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/coherence.rs:326",
                                    "rustc_trait_selection::traits::coherence",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/coherence.rs"),
                                    ::tracing_core::__macro_support::Option::Some(326u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::coherence"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("overlap: intercrate_ambiguity_causes={0:#?}",
                                                                intercrate_ambiguity_causes) as &dyn Value))])
                        });
                } else { ; }
            };
            let involves_placeholder =
                infcx.inner.borrow_mut().unwrap_region_constraints().data().constraints.iter().any(|c|
                        c.0.involves_placeholders());
            let mut impl_header =
                infcx.resolve_vars_if_possible(impl1_header);
            if infcx.next_trait_solver() {
                impl_header =
                    deeply_normalize_for_diagnostics(&infcx, param_env,
                        impl_header);
            }
            Some(OverlapResult {
                    impl_header,
                    intercrate_ambiguity_causes,
                    involves_placeholder,
                    overflowing_predicates,
                })
        }
    }
}#[instrument(level = "debug", skip(tcx))]
240fn overlap<'tcx>(
241    tcx: TyCtxt<'tcx>,
242    track_ambiguity_causes: TrackAmbiguityCauses,
243    skip_leak_check: SkipLeakCheck,
244    impl1_def_id: DefId,
245    impl2_def_id: DefId,
246    overlap_mode: OverlapMode,
247    is_of_trait: bool,
248) -> Option<OverlapResult<'tcx>> {
249    if overlap_mode.use_negative_impl() {
250        if impl_intersection_has_negative_obligation(tcx, impl1_def_id, impl2_def_id, is_of_trait)
251            || impl_intersection_has_negative_obligation(
252                tcx,
253                impl2_def_id,
254                impl1_def_id,
255                is_of_trait,
256            )
257        {
258            return None;
259        }
260    }
261
262    let infcx = tcx
263        .infer_ctxt()
264        .skip_leak_check(skip_leak_check.is_yes())
265        .with_next_trait_solver(tcx.next_trait_solver_in_coherence())
266        .build(TypingMode::Coherence);
267    let selcx = &mut SelectionContext::new(&infcx);
268    if track_ambiguity_causes.is_yes() {
269        selcx.enable_tracking_intercrate_ambiguity_causes();
270    }
271
272    // For the purposes of this check, we don't bring any placeholder
273    // types into scope; instead, we replace the generic types with
274    // fresh type variables, and hence we do our evaluations in an
275    // empty environment.
276    let param_env = ty::ParamEnv::empty();
277
278    let impl1_header = if tcx.next_trait_solver_in_coherence() {
279        fresh_impl_header(selcx.infcx, impl1_def_id, is_of_trait)
280    } else {
281        fresh_impl_header_normalized(selcx.infcx, param_env, impl1_def_id, is_of_trait)
282    };
283    let impl2_header = if tcx.next_trait_solver_in_coherence() {
284        fresh_impl_header(selcx.infcx, impl2_def_id, is_of_trait)
285    } else {
286        fresh_impl_header_normalized(selcx.infcx, param_env, impl2_def_id, is_of_trait)
287    };
288
289    // Equate the headers to find their intersection (the general type, with infer vars,
290    // that may apply both impls).
291    let mut obligations =
292        equate_impl_headers(selcx.infcx, param_env, &impl1_header, &impl2_header)?;
293    debug!("overlap: unification check succeeded");
294
295    obligations.extend(
296        [&impl1_header.predicates, &impl2_header.predicates].into_iter().flatten().map(
297            |&predicate| Obligation::new(infcx.tcx, ObligationCause::dummy(), param_env, predicate),
298        ),
299    );
300
301    let mut overflowing_predicates = Vec::new();
302    if overlap_mode.use_implicit_negative() {
303        match impl_intersection_has_impossible_obligation(selcx, &obligations) {
304            IntersectionHasImpossibleObligations::Yes => return None,
305            IntersectionHasImpossibleObligations::No { overflowing_predicates: p } => {
306                overflowing_predicates = p
307            }
308        }
309    }
310
311    // We toggle the `leak_check` by using `skip_leak_check` when constructing the
312    // inference context, so this may be a noop.
313    if infcx.leak_check(ty::UniverseIndex::ROOT, None).is_err() {
314        debug!("overlap: leak check failed");
315        return None;
316    }
317
318    let intercrate_ambiguity_causes = if !overlap_mode.use_implicit_negative() {
319        Default::default()
320    } else if infcx.next_trait_solver() {
321        compute_intercrate_ambiguity_causes(&infcx, &obligations)
322    } else {
323        selcx.take_intercrate_ambiguity_causes()
324    };
325
326    debug!("overlap: intercrate_ambiguity_causes={:#?}", intercrate_ambiguity_causes);
327    let involves_placeholder = infcx
328        .inner
329        .borrow_mut()
330        .unwrap_region_constraints()
331        .data()
332        .constraints
333        .iter()
334        .any(|c| c.0.involves_placeholders());
335
336    let mut impl_header = infcx.resolve_vars_if_possible(impl1_header);
337
338    // Deeply normalize the impl header for diagnostics, ignoring any errors if this fails.
339    if infcx.next_trait_solver() {
340        impl_header = deeply_normalize_for_diagnostics(&infcx, param_env, impl_header);
341    }
342
343    Some(OverlapResult {
344        impl_header,
345        intercrate_ambiguity_causes,
346        involves_placeholder,
347        overflowing_predicates,
348    })
349}
350
351x;#[instrument(level = "debug", skip(infcx), ret)]
352fn equate_impl_headers<'tcx>(
353    infcx: &InferCtxt<'tcx>,
354    param_env: ty::ParamEnv<'tcx>,
355    impl1: &ImplHeader<'tcx>,
356    impl2: &ImplHeader<'tcx>,
357) -> Option<PredicateObligations<'tcx>> {
358    let result =
359        match (impl1.trait_ref, impl2.trait_ref) {
360            (Some(impl1_ref), Some(impl2_ref)) => infcx
361                .at(&ObligationCause::dummy(), param_env)
362                .eq(DefineOpaqueTypes::Yes, impl1_ref, impl2_ref),
363            (None, None) => infcx.at(&ObligationCause::dummy(), param_env).eq(
364                DefineOpaqueTypes::Yes,
365                impl1.self_ty,
366                impl2.self_ty,
367            ),
368            _ => bug!("equate_impl_headers given mismatched impl kinds"),
369        };
370
371    result.map(|infer_ok| infer_ok.obligations).ok()
372}
373
374/// The result of [fn impl_intersection_has_impossible_obligation].
375#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for IntersectionHasImpossibleObligations<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            IntersectionHasImpossibleObligations::Yes =>
                ::core::fmt::Formatter::write_str(f, "Yes"),
            IntersectionHasImpossibleObligations::No {
                overflowing_predicates: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "No",
                    "overflowing_predicates", &__self_0),
        }
    }
}Debug)]
376enum IntersectionHasImpossibleObligations<'tcx> {
377    Yes,
378    No {
379        /// With `-Znext-solver=coherence`, some obligations may
380        /// fail if only the user increased the recursion limit.
381        ///
382        /// We return those obligations here and mention them in the
383        /// error message.
384        overflowing_predicates: Vec<ty::Predicate<'tcx>>,
385    },
386}
387
388/// Check if both impls can be satisfied by a common type by considering whether
389/// any of either impl's obligations is not known to hold.
390///
391/// For example, given these two impls:
392///     `impl From<MyLocalType> for Box<dyn Error>` (in my crate)
393///     `impl<E> From<E> for Box<dyn Error> where E: Error` (in libstd)
394///
395/// After replacing both impl headers with inference vars (which happens before
396/// this function is called), we get:
397///     `Box<dyn Error>: From<MyLocalType>`
398///     `Box<dyn Error>: From<?E>`
399///
400/// This gives us `?E = MyLocalType`. We then certainly know that `MyLocalType: Error`
401/// never holds in intercrate mode since a local impl does not exist, and a
402/// downstream impl cannot be added -- therefore can consider the intersection
403/// of the two impls above to be empty.
404///
405/// Importantly, this works even if there isn't a `impl !Error for MyLocalType`.
406x;#[instrument(level = "debug", skip(selcx), ret)]
407fn impl_intersection_has_impossible_obligation<'a, 'cx, 'tcx>(
408    selcx: &mut SelectionContext<'cx, 'tcx>,
409    obligations: &'a [PredicateObligation<'tcx>],
410) -> IntersectionHasImpossibleObligations<'tcx> {
411    let infcx = selcx.infcx;
412
413    if infcx.next_trait_solver() {
414        // A fast path optimization, try evaluating all goals with
415        // a very low recursion depth and bail if any of them don't
416        // hold.
417        if !obligations.iter().all(|o| {
418            <&SolverDelegate<'tcx>>::from(infcx)
419                .root_goal_may_hold_with_depth(8, Goal::new(infcx.tcx, o.param_env, o.predicate))
420        }) {
421            return IntersectionHasImpossibleObligations::Yes;
422        }
423
424        let ocx = ObligationCtxt::new(infcx);
425        ocx.register_obligations(obligations.iter().cloned());
426        let hard_errors = ocx.try_evaluate_obligations();
427        if !hard_errors.is_empty() {
428            assert!(
429                hard_errors.iter().all(|e| e.is_true_error()),
430                "should not have detected ambiguity during first pass"
431            );
432            return IntersectionHasImpossibleObligations::Yes;
433        }
434
435        // Make a new `ObligationCtxt` and re-prove the ambiguities with a richer
436        // `FulfillmentError`. This is so that we can detect overflowing obligations
437        // without needing to run the `BestObligation` visitor on true errors.
438        let ambiguities = ocx.into_pending_obligations();
439        let ocx = ObligationCtxt::new_with_diagnostics(infcx);
440        ocx.register_obligations(ambiguities);
441        let errors_and_ambiguities = ocx.evaluate_obligations_error_on_ambiguity();
442        // We only care about the obligations that are *definitely* true errors.
443        // Ambiguities do not prove the disjointness of two impls.
444        let (errors, ambiguities): (Vec<_>, Vec<_>) =
445            errors_and_ambiguities.into_iter().partition(|error| error.is_true_error());
446        assert!(errors.is_empty(), "should not have ambiguities during second pass");
447
448        IntersectionHasImpossibleObligations::No {
449            overflowing_predicates: ambiguities
450                .into_iter()
451                .filter(|error| {
452                    matches!(error.code, FulfillmentErrorCode::Ambiguity { overflow: Some(true) })
453                })
454                .map(|e| infcx.resolve_vars_if_possible(e.obligation.predicate))
455                .collect(),
456        }
457    } else {
458        for obligation in obligations {
459            // We use `evaluate_root_obligation` to correctly track intercrate
460            // ambiguity clauses.
461            let evaluation_result = selcx.evaluate_root_obligation(obligation);
462
463            match evaluation_result {
464                Ok(result) => {
465                    if !result.may_apply() {
466                        return IntersectionHasImpossibleObligations::Yes;
467                    }
468                }
469                // If overflow occurs, we need to conservatively treat the goal as possibly holding,
470                // since there can be instantiations of this goal that don't overflow and result in
471                // success. While this isn't much of a problem in the old solver, since we treat overflow
472                // fatally, this still can be encountered: <https://github.com/rust-lang/rust/issues/105231>.
473                Err(_overflow) => {}
474            }
475        }
476
477        IntersectionHasImpossibleObligations::No { overflowing_predicates: Vec::new() }
478    }
479}
480
481/// Check if both impls can be satisfied by a common type by considering whether
482/// any of first impl's obligations is known not to hold *via a negative predicate*.
483///
484/// For example, given these two impls:
485///     `struct MyCustomBox<T: ?Sized>(Box<T>);`
486///     `impl From<&str> for MyCustomBox<dyn Error>` (in my crate)
487///     `impl<E> From<E> for MyCustomBox<dyn Error> where E: Error` (in my crate)
488///
489/// After replacing the second impl's header with inference vars, we get:
490///     `MyCustomBox<dyn Error>: From<&str>`
491///     `MyCustomBox<dyn Error>: From<?E>`
492///
493/// This gives us `?E = &str`. We then try to prove the first impl's predicates
494/// after negating, giving us `&str: !Error`. This is a negative impl provided by
495/// libstd, and therefore we can guarantee for certain that libstd will never add
496/// a positive impl for `&str: Error` (without it being a breaking change).
497fn impl_intersection_has_negative_obligation(
498    tcx: TyCtxt<'_>,
499    impl1_def_id: DefId,
500    impl2_def_id: DefId,
501    is_of_trait: bool,
502) -> bool {
503    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/coherence.rs:503",
                        "rustc_trait_selection::traits::coherence",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/coherence.rs"),
                        ::tracing_core::__macro_support::Option::Some(503u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::coherence"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("negative_impl(impl1_def_id={0:?}, impl2_def_id={1:?})",
                                                    impl1_def_id, impl2_def_id) as &dyn Value))])
            });
    } else { ; }
};debug!("negative_impl(impl1_def_id={:?}, impl2_def_id={:?})", impl1_def_id, impl2_def_id);
504
505    // N.B. We need to unify impl headers *with* `TypingMode::Coherence`,
506    // even if proving negative predicates doesn't need `TypingMode::Coherence`.
507    let ref infcx = tcx.infer_ctxt().with_next_trait_solver(true).build(TypingMode::Coherence);
508    let root_universe = infcx.universe();
509    {
    match (&root_universe, &ty::UniverseIndex::ROOT) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(root_universe, ty::UniverseIndex::ROOT);
510
511    let impl1_header = fresh_impl_header(infcx, impl1_def_id, is_of_trait);
512    let impl2_header = fresh_impl_header(infcx, impl2_def_id, is_of_trait);
513
514    // Equate the headers to find their intersection (the general type, with infer vars,
515    // that may apply both impls).
516    let Some(equate_obligations) =
517        equate_impl_headers(infcx, ty::ParamEnv::empty(), &impl1_header, &impl2_header)
518    else {
519        return false;
520    };
521
522    // FIXME(with_negative_coherence): the infcx has constraints from equating
523    // the impl headers. We should use these constraints as assumptions, not as
524    // requirements, when proving the negated where clauses below.
525    drop(equate_obligations);
526    drop(infcx.take_registered_region_obligations());
527    drop(infcx.take_registered_region_assumptions());
528    drop(infcx.take_and_reset_region_constraints());
529
530    plug_infer_with_placeholders(
531        infcx,
532        root_universe,
533        (impl1_header.impl_args, impl2_header.impl_args),
534    );
535
536    // Right above we plug inference variables with placeholders,
537    // this gets us new impl1_header_args with the inference variables actually resolved
538    // to those placeholders.
539    let impl1_header_args = infcx.resolve_vars_if_possible(impl1_header.impl_args);
540    // So there are no infer variables left now, except regions which aren't resolved by `resolve_vars_if_possible`.
541    if !!impl1_header_args.has_non_region_infer() {
    ::core::panicking::panic("assertion failed: !impl1_header_args.has_non_region_infer()")
};assert!(!impl1_header_args.has_non_region_infer());
542
543    let param_env = ty::EarlyBinder::bind(tcx, tcx.param_env(impl1_def_id))
544        .instantiate(tcx, impl1_header_args)
545        .skip_norm_wip();
546
547    util::elaborate(
548        tcx,
549        tcx.predicates_of(impl2_def_id)
550            .instantiate(tcx, impl2_header.impl_args)
551            .into_iter()
552            .map(|(c, s)| (c.skip_norm_wip(), s)),
553    )
554    .elaborate_sized()
555    .any(|(clause, _)| try_prove_negated_where_clause(infcx, clause, param_env))
556}
557
558fn plug_infer_with_placeholders<'tcx>(
559    infcx: &InferCtxt<'tcx>,
560    universe: ty::UniverseIndex,
561    value: impl TypeVisitable<TyCtxt<'tcx>>,
562) {
563    struct PlugInferWithPlaceholder<'a, 'tcx> {
564        infcx: &'a InferCtxt<'tcx>,
565        universe: ty::UniverseIndex,
566        var: ty::BoundVar,
567    }
568
569    impl<'tcx> PlugInferWithPlaceholder<'_, 'tcx> {
570        fn next_var(&mut self) -> ty::BoundVar {
571            let var = self.var;
572            self.var = self.var + 1;
573            var
574        }
575    }
576
577    impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for PlugInferWithPlaceholder<'_, 'tcx> {
578        fn visit_ty(&mut self, ty: Ty<'tcx>) {
579            let ty = self.infcx.shallow_resolve(ty);
580            if ty.is_ty_var() {
581                let Ok(InferOk { value: (), obligations }) =
582                    self.infcx.at(&ObligationCause::dummy(), ty::ParamEnv::empty()).eq(
583                        // Comparing against a type variable never registers hidden types anyway
584                        DefineOpaqueTypes::Yes,
585                        ty,
586                        Ty::new_placeholder(
587                            self.infcx.tcx,
588                            ty::PlaceholderType::new(
589                                self.universe,
590                                ty::BoundTy { var: self.next_var(), kind: ty::BoundTyKind::Anon },
591                            ),
592                        ),
593                    )
594                else {
595                    ::rustc_middle::util::bug::bug_fmt(format_args!("we always expect to be able to plug an infer var with placeholder"))bug!("we always expect to be able to plug an infer var with placeholder")
596                };
597                {
    match (&obligations.len(), &0) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(obligations.len(), 0);
598            } else {
599                ty.super_visit_with(self);
600            }
601        }
602
603        fn visit_const(&mut self, ct: ty::Const<'tcx>) {
604            let ct = self.infcx.shallow_resolve_const(ct);
605            if ct.is_ct_infer() {
606                let Ok(InferOk { value: (), obligations }) =
607                    self.infcx.at(&ObligationCause::dummy(), ty::ParamEnv::empty()).eq(
608                        // The types of the constants are the same, so there is no hidden type
609                        // registration happening anyway.
610                        DefineOpaqueTypes::Yes,
611                        ct,
612                        ty::Const::new_placeholder(
613                            self.infcx.tcx,
614                            ty::PlaceholderConst::new(
615                                self.universe,
616                                ty::BoundConst::new(self.next_var()),
617                            ),
618                        ),
619                    )
620                else {
621                    ::rustc_middle::util::bug::bug_fmt(format_args!("we always expect to be able to plug an infer var with placeholder"))bug!("we always expect to be able to plug an infer var with placeholder")
622                };
623                {
    match (&obligations.len(), &0) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(obligations.len(), 0);
624            } else {
625                ct.super_visit_with(self);
626            }
627        }
628
629        fn visit_region(&mut self, r: ty::Region<'tcx>) {
630            if let ty::ReVar(vid) = r.kind() {
631                let r = self
632                    .infcx
633                    .inner
634                    .borrow_mut()
635                    .unwrap_region_constraints()
636                    .opportunistic_resolve_var(self.infcx.tcx, vid);
637                if r.is_var() {
638                    let Ok(InferOk { value: (), obligations }) =
639                        self.infcx.at(&ObligationCause::dummy(), ty::ParamEnv::empty()).eq(
640                            // Lifetimes don't contain opaque types (or any types for that matter).
641                            DefineOpaqueTypes::Yes,
642                            r,
643                            ty::Region::new_placeholder(
644                                self.infcx.tcx,
645                                ty::PlaceholderRegion::new(
646                                    self.universe,
647                                    ty::BoundRegion {
648                                        var: self.next_var(),
649                                        kind: ty::BoundRegionKind::Anon,
650                                    },
651                                ),
652                            ),
653                        )
654                    else {
655                        ::rustc_middle::util::bug::bug_fmt(format_args!("we always expect to be able to plug an infer var with placeholder"))bug!("we always expect to be able to plug an infer var with placeholder")
656                    };
657                    {
    match (&obligations.len(), &0) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(obligations.len(), 0);
658                }
659            }
660        }
661    }
662
663    value.visit_with(&mut PlugInferWithPlaceholder { infcx, universe, var: ty::BoundVar::ZERO });
664}
665
666fn try_prove_negated_where_clause<'tcx>(
667    root_infcx: &InferCtxt<'tcx>,
668    clause: ty::Clause<'tcx>,
669    param_env: ty::ParamEnv<'tcx>,
670) -> bool {
671    let Some(negative_predicate) = clause.as_predicate().flip_polarity(root_infcx.tcx) else {
672        return false;
673    };
674
675    // N.B. We don't need to use intercrate mode here because we're trying to prove
676    // the *existence* of a negative goal, not the non-existence of a positive goal.
677    // Without this, we over-eagerly register coherence ambiguity candidates when
678    // impl candidates do exist.
679    // FIXME(#132279): `TypingMode::non_body_analysis` is a bit questionable here as it
680    // would cause us to reveal opaque types to leak their auto traits.
681    let ref infcx = root_infcx.fork_with_typing_mode(TypingMode::non_body_analysis());
682    let ocx = ObligationCtxt::new(infcx);
683    ocx.register_obligation(Obligation::new(
684        infcx.tcx,
685        ObligationCause::dummy(),
686        param_env,
687        negative_predicate,
688    ));
689    if !ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
690        return false;
691    }
692
693    // FIXME: We could use the assumed_wf_types from both impls, I think,
694    // if that wasn't implemented just for LocalDefId, and we'd need to do
695    // the normalization ourselves since this is totally fallible...
696    let errors = ocx.resolve_regions(CRATE_DEF_ID, param_env, []);
697    if !errors.is_empty() {
698        return false;
699    }
700
701    true
702}
703
704/// Compute the `intercrate_ambiguity_causes` for the new solver using
705/// "proof trees".
706///
707/// This is a bit scuffed but seems to be good enough, at least
708/// when looking at UI tests. Given that it is only used to improve
709/// diagnostics this is good enough. We can always improve it once there
710/// are test cases where it is currently not enough.
711fn compute_intercrate_ambiguity_causes<'tcx>(
712    infcx: &InferCtxt<'tcx>,
713    obligations: &[PredicateObligation<'tcx>],
714) -> FxIndexSet<IntercrateAmbiguityCause<'tcx>> {
715    let mut causes: FxIndexSet<IntercrateAmbiguityCause<'tcx>> = Default::default();
716
717    for obligation in obligations {
718        search_ambiguity_causes(infcx, obligation.as_goal(), &mut causes);
719    }
720
721    causes
722}
723
724struct AmbiguityCausesVisitor<'a, 'tcx> {
725    cache: FxHashSet<Goal<'tcx, ty::Predicate<'tcx>>>,
726    causes: &'a mut FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
727}
728
729impl<'a, 'tcx> ProofTreeVisitor<'tcx> for AmbiguityCausesVisitor<'a, 'tcx> {
730    fn span(&self) -> Span {
731        DUMMY_SP
732    }
733
734    fn visit_goal(&mut self, goal: &InspectGoal<'_, 'tcx>) {
735        if !self.cache.insert(goal.goal()) {
736            return;
737        }
738
739        let infcx = goal.infcx();
740        for cand in goal.candidates() {
741            cand.visit_nested_in_probe(self);
742        }
743        // When searching for intercrate ambiguity causes, we only need to look
744        // at ambiguous goals, as for others the coherence unknowable candidate
745        // was irrelevant.
746        match goal.result() {
747            Ok(Certainty::Yes) | Err(NoSolution) => return,
748            Ok(Certainty::Maybe(_)) => {}
749        }
750
751        // For bound predicates we simply call `infcx.enter_forall`
752        // and then prove the resulting predicate as a nested goal.
753        let Goal { param_env, predicate } = goal.goal();
754        let predicate_kind = goal.infcx().enter_forall_and_leak_universe(predicate.kind());
755        let trait_ref = match predicate_kind {
756            ty::PredicateKind::Clause(ty::ClauseKind::Trait(tr)) => tr.trait_ref,
757            ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj))
758                if proj.projection_term.kind.is_trait_projection() =>
759            {
760                proj.projection_term.trait_ref(infcx.tcx)
761            }
762            _ => return,
763        };
764
765        if trait_ref.references_error() {
766            return;
767        }
768
769        let mut candidates = goal.candidates();
770        for cand in goal.candidates() {
771            if let inspect::ProbeKind::TraitCandidate {
772                source: CandidateSource::Impl(def_id),
773                result: Ok(_),
774            } = cand.kind()
775                && let ty::ImplPolarity::Reservation = infcx.tcx.impl_polarity(def_id)
776            {
777                if let Some(message) =
778                    {
    {
        'done:
            {
            for i in
                ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &infcx.tcx) {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(RustcReservationImpl(message))
                        => {
                        break 'done Some(*message);
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(infcx.tcx, def_id, RustcReservationImpl(message) => *message)
779                {
780                    self.causes.insert(IntercrateAmbiguityCause::ReservationImpl { message });
781                }
782            }
783        }
784
785        // We also look for unknowable candidates. In case a goal is unknowable, there's
786        // always exactly 1 candidate.
787        let Some(cand) = candidates.pop() else {
788            return;
789        };
790
791        let inspect::ProbeKind::TraitCandidate {
792            source: CandidateSource::CoherenceUnknowable,
793            result: Ok(_),
794        } = cand.kind()
795        else {
796            return;
797        };
798
799        let lazily_normalize_ty = |mut ty: Ty<'tcx>| {
800            if #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Alias(..) => true,
    _ => false,
}matches!(ty.kind(), ty::Alias(..)) {
801                let ocx = ObligationCtxt::new(infcx);
802                ty = ocx
803                    .structurally_normalize_ty(
804                        &ObligationCause::dummy(),
805                        param_env,
806                        Unnormalized::new_wip(ty),
807                    )
808                    .map_err(|_| ())?;
809                if !ocx.try_evaluate_obligations().is_empty() {
810                    return Err(());
811                }
812            }
813            Ok(ty)
814        };
815
816        infcx.probe(|_| {
817            let conflict = match trait_ref_is_knowable(infcx, trait_ref, lazily_normalize_ty) {
818                Err(()) => return,
819                Ok(Ok(())) => {
820                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/coherence.rs:820",
                        "rustc_trait_selection::traits::coherence",
                        ::tracing::Level::WARN,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/coherence.rs"),
                        ::tracing_core::__macro_support::Option::Some(820u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::coherence"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::WARN <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("expected an unknowable trait ref: {0:?}",
                                                    trait_ref) as &dyn Value))])
            });
    } else { ; }
};warn!("expected an unknowable trait ref: {trait_ref:?}");
821                    return;
822                }
823                Ok(Err(conflict)) => conflict,
824            };
825
826            // It is only relevant that a goal is unknowable if it would have otherwise
827            // failed.
828            // FIXME(#132279): Forking with `TypingMode::non_body_analysis` is a bit questionable
829            // as it would allow us to reveal opaque types, potentially causing unexpected
830            // cycles.
831            let non_intercrate_infcx = infcx.fork_with_typing_mode(TypingMode::non_body_analysis());
832            if non_intercrate_infcx.predicate_may_hold(&Obligation::new(
833                infcx.tcx,
834                ObligationCause::dummy(),
835                param_env,
836                predicate,
837            )) {
838                return;
839            }
840
841            // Normalize the trait ref for diagnostics, ignoring any errors if this fails.
842            let trait_ref = deeply_normalize_for_diagnostics(infcx, param_env, trait_ref);
843            let self_ty = trait_ref.self_ty();
844            let self_ty = self_ty.has_concrete_skeleton().then(|| self_ty);
845            self.causes.insert(match conflict {
846                Conflict::Upstream => {
847                    IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_ref, self_ty }
848                }
849                Conflict::Downstream => {
850                    IntercrateAmbiguityCause::DownstreamCrate { trait_ref, self_ty }
851                }
852            });
853        });
854    }
855}
856
857fn search_ambiguity_causes<'tcx>(
858    infcx: &InferCtxt<'tcx>,
859    goal: Goal<'tcx, ty::Predicate<'tcx>>,
860    causes: &mut FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
861) {
862    infcx.probe(|_| {
863        infcx.visit_proof_tree(
864            goal,
865            &mut AmbiguityCausesVisitor { cache: Default::default(), causes },
866        )
867    });
868}