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