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::DefKind;
12use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
13use rustc_hir::find_attr;
14use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, TyCtxtInferExt};
15use rustc_infer::traits::PredicateObligations;
16use rustc_macros::{TypeFoldable, TypeVisitable};
17use rustc_middle::bug;
18use rustc_middle::traits::query::NoSolution;
19use rustc_middle::traits::solve::{CandidateSource, Certainty, Goal};
20use rustc_middle::traits::specialization_graph::OverlapMode;
21use rustc_middle::ty::fast_reject::DeepRejectCtxt;
22use rustc_middle::ty::{
23    self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
24    Unnormalized,
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).skip_norm_wip(),
214        trait_ref: is_of_trait
215            .then(|| tcx.impl_trait_ref(impl_def_id).instantiate(tcx, impl_args).skip_norm_wip()),
216        predicates: tcx
217            .predicates_of(impl_def_id)
218            .instantiate(tcx, impl_args)
219            .iter()
220            .map(|(c, _)| c.skip_norm_wip().as_predicate())
221            .collect(),
222    }
223}
224
225fn fresh_impl_header_normalized<'tcx>(
226    infcx: &InferCtxt<'tcx>,
227    param_env: ty::ParamEnv<'tcx>,
228    impl_def_id: DefId,
229    is_of_trait: bool,
230) -> ImplHeader<'tcx> {
231    let header = fresh_impl_header(infcx, impl_def_id, is_of_trait);
232
233    let InferOk { value: mut header, obligations } =
234        infcx.at(&ObligationCause::dummy(), param_env).normalize(Unnormalized::new_wip(header));
235
236    header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
237    header
238}
239
240/// Can both impl `a` and impl `b` be satisfied by a common type (including
241/// where-clauses)? If so, returns an `ImplHeader` that unifies the two impls.
242#[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(242u32),
                                    ::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:290",
                                    "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(290u32),
                                    ::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:311",
                                        "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(311u32),
                                        ::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:323",
                                    "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(323u32),
                                    ::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))]
243fn overlap<'tcx>(
244    tcx: TyCtxt<'tcx>,
245    track_ambiguity_causes: TrackAmbiguityCauses,
246    skip_leak_check: SkipLeakCheck,
247    impl1_def_id: DefId,
248    impl2_def_id: DefId,
249    overlap_mode: OverlapMode,
250    is_of_trait: bool,
251) -> Option<OverlapResult<'tcx>> {
252    if overlap_mode.use_negative_impl() {
253        if impl_intersection_has_negative_obligation(tcx, impl1_def_id, impl2_def_id, is_of_trait)
254            || impl_intersection_has_negative_obligation(
255                tcx,
256                impl2_def_id,
257                impl1_def_id,
258                is_of_trait,
259            )
260        {
261            return None;
262        }
263    }
264
265    let infcx = tcx
266        .infer_ctxt()
267        .skip_leak_check(skip_leak_check.is_yes())
268        .with_next_trait_solver(tcx.next_trait_solver_in_coherence())
269        .build(TypingMode::Coherence);
270    let selcx = &mut SelectionContext::new(&infcx);
271    if track_ambiguity_causes.is_yes() {
272        selcx.enable_tracking_intercrate_ambiguity_causes();
273    }
274
275    // For the purposes of this check, we don't bring any placeholder
276    // types into scope; instead, we replace the generic types with
277    // fresh type variables, and hence we do our evaluations in an
278    // empty environment.
279    let param_env = ty::ParamEnv::empty();
280
281    let impl1_header =
282        fresh_impl_header_normalized(selcx.infcx, param_env, impl1_def_id, is_of_trait);
283    let impl2_header =
284        fresh_impl_header_normalized(selcx.infcx, param_env, impl2_def_id, is_of_trait);
285
286    // Equate the headers to find their intersection (the general type, with infer vars,
287    // that may apply both impls).
288    let mut obligations =
289        equate_impl_headers(selcx.infcx, param_env, &impl1_header, &impl2_header)?;
290    debug!("overlap: unification check succeeded");
291
292    obligations.extend(
293        [&impl1_header.predicates, &impl2_header.predicates].into_iter().flatten().map(
294            |&predicate| Obligation::new(infcx.tcx, ObligationCause::dummy(), param_env, predicate),
295        ),
296    );
297
298    let mut overflowing_predicates = Vec::new();
299    if overlap_mode.use_implicit_negative() {
300        match impl_intersection_has_impossible_obligation(selcx, &obligations) {
301            IntersectionHasImpossibleObligations::Yes => return None,
302            IntersectionHasImpossibleObligations::No { overflowing_predicates: p } => {
303                overflowing_predicates = p
304            }
305        }
306    }
307
308    // We toggle the `leak_check` by using `skip_leak_check` when constructing the
309    // inference context, so this may be a noop.
310    if infcx.leak_check(ty::UniverseIndex::ROOT, None).is_err() {
311        debug!("overlap: leak check failed");
312        return None;
313    }
314
315    let intercrate_ambiguity_causes = if !overlap_mode.use_implicit_negative() {
316        Default::default()
317    } else if infcx.next_trait_solver() {
318        compute_intercrate_ambiguity_causes(&infcx, &obligations)
319    } else {
320        selcx.take_intercrate_ambiguity_causes()
321    };
322
323    debug!("overlap: intercrate_ambiguity_causes={:#?}", intercrate_ambiguity_causes);
324    let involves_placeholder = infcx
325        .inner
326        .borrow_mut()
327        .unwrap_region_constraints()
328        .data()
329        .constraints
330        .iter()
331        .any(|c| c.0.involves_placeholders());
332
333    let mut impl_header = infcx.resolve_vars_if_possible(impl1_header);
334
335    // Deeply normalize the impl header for diagnostics, ignoring any errors if this fails.
336    if infcx.next_trait_solver() {
337        impl_header = deeply_normalize_for_diagnostics(&infcx, param_env, impl_header);
338    }
339
340    Some(OverlapResult {
341        impl_header,
342        intercrate_ambiguity_causes,
343        involves_placeholder,
344        overflowing_predicates,
345    })
346}
347
348x;#[instrument(level = "debug", skip(infcx), ret)]
349fn equate_impl_headers<'tcx>(
350    infcx: &InferCtxt<'tcx>,
351    param_env: ty::ParamEnv<'tcx>,
352    impl1: &ImplHeader<'tcx>,
353    impl2: &ImplHeader<'tcx>,
354) -> Option<PredicateObligations<'tcx>> {
355    let result =
356        match (impl1.trait_ref, impl2.trait_ref) {
357            (Some(impl1_ref), Some(impl2_ref)) => infcx
358                .at(&ObligationCause::dummy(), param_env)
359                .eq(DefineOpaqueTypes::Yes, impl1_ref, impl2_ref),
360            (None, None) => infcx.at(&ObligationCause::dummy(), param_env).eq(
361                DefineOpaqueTypes::Yes,
362                impl1.self_ty,
363                impl2.self_ty,
364            ),
365            _ => bug!("equate_impl_headers given mismatched impl kinds"),
366        };
367
368    result.map(|infer_ok| infer_ok.obligations).ok()
369}
370
371/// The result of [fn impl_intersection_has_impossible_obligation].
372#[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)]
373enum IntersectionHasImpossibleObligations<'tcx> {
374    Yes,
375    No {
376        /// With `-Znext-solver=coherence`, some obligations may
377        /// fail if only the user increased the recursion limit.
378        ///
379        /// We return those obligations here and mention them in the
380        /// error message.
381        overflowing_predicates: Vec<ty::Predicate<'tcx>>,
382    },
383}
384
385/// Check if both impls can be satisfied by a common type by considering whether
386/// any of either impl's obligations is not known to hold.
387///
388/// For example, given these two impls:
389///     `impl From<MyLocalType> for Box<dyn Error>` (in my crate)
390///     `impl<E> From<E> for Box<dyn Error> where E: Error` (in libstd)
391///
392/// After replacing both impl headers with inference vars (which happens before
393/// this function is called), we get:
394///     `Box<dyn Error>: From<MyLocalType>`
395///     `Box<dyn Error>: From<?E>`
396///
397/// This gives us `?E = MyLocalType`. We then certainly know that `MyLocalType: Error`
398/// never holds in intercrate mode since a local impl does not exist, and a
399/// downstream impl cannot be added -- therefore can consider the intersection
400/// of the two impls above to be empty.
401///
402/// Importantly, this works even if there isn't a `impl !Error for MyLocalType`.
403x;#[instrument(level = "debug", skip(selcx), ret)]
404fn impl_intersection_has_impossible_obligation<'a, 'cx, 'tcx>(
405    selcx: &mut SelectionContext<'cx, 'tcx>,
406    obligations: &'a [PredicateObligation<'tcx>],
407) -> IntersectionHasImpossibleObligations<'tcx> {
408    let infcx = selcx.infcx;
409
410    if infcx.next_trait_solver() {
411        // A fast path optimization, try evaluating all goals with
412        // a very low recursion depth and bail if any of them don't
413        // hold.
414        if !obligations.iter().all(|o| {
415            <&SolverDelegate<'tcx>>::from(infcx)
416                .root_goal_may_hold_with_depth(8, Goal::new(infcx.tcx, o.param_env, o.predicate))
417        }) {
418            return IntersectionHasImpossibleObligations::Yes;
419        }
420
421        let ocx = ObligationCtxt::new(infcx);
422        ocx.register_obligations(obligations.iter().cloned());
423        let hard_errors = ocx.try_evaluate_obligations();
424        if !hard_errors.is_empty() {
425            assert!(
426                hard_errors.iter().all(|e| e.is_true_error()),
427                "should not have detected ambiguity during first pass"
428            );
429            return IntersectionHasImpossibleObligations::Yes;
430        }
431
432        // Make a new `ObligationCtxt` and re-prove the ambiguities with a richer
433        // `FulfillmentError`. This is so that we can detect overflowing obligations
434        // without needing to run the `BestObligation` visitor on true errors.
435        let ambiguities = ocx.into_pending_obligations();
436        let ocx = ObligationCtxt::new_with_diagnostics(infcx);
437        ocx.register_obligations(ambiguities);
438        let errors_and_ambiguities = ocx.evaluate_obligations_error_on_ambiguity();
439        // We only care about the obligations that are *definitely* true errors.
440        // Ambiguities do not prove the disjointness of two impls.
441        let (errors, ambiguities): (Vec<_>, Vec<_>) =
442            errors_and_ambiguities.into_iter().partition(|error| error.is_true_error());
443        assert!(errors.is_empty(), "should not have ambiguities during second pass");
444
445        IntersectionHasImpossibleObligations::No {
446            overflowing_predicates: ambiguities
447                .into_iter()
448                .filter(|error| {
449                    matches!(error.code, FulfillmentErrorCode::Ambiguity { overflow: Some(true) })
450                })
451                .map(|e| infcx.resolve_vars_if_possible(e.obligation.predicate))
452                .collect(),
453        }
454    } else {
455        for obligation in obligations {
456            // We use `evaluate_root_obligation` to correctly track intercrate
457            // ambiguity clauses.
458            let evaluation_result = selcx.evaluate_root_obligation(obligation);
459
460            match evaluation_result {
461                Ok(result) => {
462                    if !result.may_apply() {
463                        return IntersectionHasImpossibleObligations::Yes;
464                    }
465                }
466                // If overflow occurs, we need to conservatively treat the goal as possibly holding,
467                // since there can be instantiations of this goal that don't overflow and result in
468                // success. While this isn't much of a problem in the old solver, since we treat overflow
469                // fatally, this still can be encountered: <https://github.com/rust-lang/rust/issues/105231>.
470                Err(_overflow) => {}
471            }
472        }
473
474        IntersectionHasImpossibleObligations::No { overflowing_predicates: Vec::new() }
475    }
476}
477
478/// Check if both impls can be satisfied by a common type by considering whether
479/// any of first impl's obligations is known not to hold *via a negative predicate*.
480///
481/// For example, given these two impls:
482///     `struct MyCustomBox<T: ?Sized>(Box<T>);`
483///     `impl From<&str> for MyCustomBox<dyn Error>` (in my crate)
484///     `impl<E> From<E> for MyCustomBox<dyn Error> where E: Error` (in my crate)
485///
486/// After replacing the second impl's header with inference vars, we get:
487///     `MyCustomBox<dyn Error>: From<&str>`
488///     `MyCustomBox<dyn Error>: From<?E>`
489///
490/// This gives us `?E = &str`. We then try to prove the first impl's predicates
491/// after negating, giving us `&str: !Error`. This is a negative impl provided by
492/// libstd, and therefore we can guarantee for certain that libstd will never add
493/// a positive impl for `&str: Error` (without it being a breaking change).
494fn impl_intersection_has_negative_obligation(
495    tcx: TyCtxt<'_>,
496    impl1_def_id: DefId,
497    impl2_def_id: DefId,
498    is_of_trait: bool,
499) -> bool {
500    {
    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:500",
                        "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(500u32),
                        ::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);
501
502    // N.B. We need to unify impl headers *with* `TypingMode::Coherence`,
503    // even if proving negative predicates doesn't need `TypingMode::Coherence`.
504    let ref infcx = tcx.infer_ctxt().with_next_trait_solver(true).build(TypingMode::Coherence);
505    let root_universe = infcx.universe();
506    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);
507
508    let impl1_header = fresh_impl_header(infcx, impl1_def_id, is_of_trait);
509    let impl2_header = fresh_impl_header(infcx, impl2_def_id, is_of_trait);
510
511    // Equate the headers to find their intersection (the general type, with infer vars,
512    // that may apply both impls).
513    let Some(equate_obligations) =
514        equate_impl_headers(infcx, ty::ParamEnv::empty(), &impl1_header, &impl2_header)
515    else {
516        return false;
517    };
518
519    // FIXME(with_negative_coherence): the infcx has constraints from equating
520    // the impl headers. We should use these constraints as assumptions, not as
521    // requirements, when proving the negated where clauses below.
522    drop(equate_obligations);
523    drop(infcx.take_registered_region_obligations());
524    drop(infcx.take_registered_region_assumptions());
525    drop(infcx.take_and_reset_region_constraints());
526
527    plug_infer_with_placeholders(
528        infcx,
529        root_universe,
530        (impl1_header.impl_args, impl2_header.impl_args),
531    );
532
533    // Right above we plug inference variables with placeholders,
534    // this gets us new impl1_header_args with the inference variables actually resolved
535    // to those placeholders.
536    let impl1_header_args = infcx.resolve_vars_if_possible(impl1_header.impl_args);
537    // So there are no infer variables left now, except regions which aren't resolved by `resolve_vars_if_possible`.
538    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());
539
540    let param_env = ty::EarlyBinder::bind(tcx.param_env(impl1_def_id))
541        .instantiate(tcx, impl1_header_args)
542        .skip_norm_wip();
543
544    util::elaborate(
545        tcx,
546        tcx.predicates_of(impl2_def_id)
547            .instantiate(tcx, impl2_header.impl_args)
548            .into_iter()
549            .map(|(c, s)| (c.skip_norm_wip(), s)),
550    )
551    .elaborate_sized()
552    .any(|(clause, _)| try_prove_negated_where_clause(infcx, clause, param_env))
553}
554
555fn plug_infer_with_placeholders<'tcx>(
556    infcx: &InferCtxt<'tcx>,
557    universe: ty::UniverseIndex,
558    value: impl TypeVisitable<TyCtxt<'tcx>>,
559) {
560    struct PlugInferWithPlaceholder<'a, 'tcx> {
561        infcx: &'a InferCtxt<'tcx>,
562        universe: ty::UniverseIndex,
563        var: ty::BoundVar,
564    }
565
566    impl<'tcx> PlugInferWithPlaceholder<'_, 'tcx> {
567        fn next_var(&mut self) -> ty::BoundVar {
568            let var = self.var;
569            self.var = self.var + 1;
570            var
571        }
572    }
573
574    impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for PlugInferWithPlaceholder<'_, 'tcx> {
575        fn visit_ty(&mut self, ty: Ty<'tcx>) {
576            let ty = self.infcx.shallow_resolve(ty);
577            if ty.is_ty_var() {
578                let Ok(InferOk { value: (), obligations }) =
579                    self.infcx.at(&ObligationCause::dummy(), ty::ParamEnv::empty()).eq(
580                        // Comparing against a type variable never registers hidden types anyway
581                        DefineOpaqueTypes::Yes,
582                        ty,
583                        Ty::new_placeholder(
584                            self.infcx.tcx,
585                            ty::PlaceholderType::new(
586                                self.universe,
587                                ty::BoundTy { var: self.next_var(), kind: ty::BoundTyKind::Anon },
588                            ),
589                        ),
590                    )
591                else {
592                    ::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")
593                };
594                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);
595            } else {
596                ty.super_visit_with(self);
597            }
598        }
599
600        fn visit_const(&mut self, ct: ty::Const<'tcx>) {
601            let ct = self.infcx.shallow_resolve_const(ct);
602            if ct.is_ct_infer() {
603                let Ok(InferOk { value: (), obligations }) =
604                    self.infcx.at(&ObligationCause::dummy(), ty::ParamEnv::empty()).eq(
605                        // The types of the constants are the same, so there is no hidden type
606                        // registration happening anyway.
607                        DefineOpaqueTypes::Yes,
608                        ct,
609                        ty::Const::new_placeholder(
610                            self.infcx.tcx,
611                            ty::PlaceholderConst::new(
612                                self.universe,
613                                ty::BoundConst::new(self.next_var()),
614                            ),
615                        ),
616                    )
617                else {
618                    ::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")
619                };
620                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);
621            } else {
622                ct.super_visit_with(self);
623            }
624        }
625
626        fn visit_region(&mut self, r: ty::Region<'tcx>) {
627            if let ty::ReVar(vid) = r.kind() {
628                let r = self
629                    .infcx
630                    .inner
631                    .borrow_mut()
632                    .unwrap_region_constraints()
633                    .opportunistic_resolve_var(self.infcx.tcx, vid);
634                if r.is_var() {
635                    let Ok(InferOk { value: (), obligations }) =
636                        self.infcx.at(&ObligationCause::dummy(), ty::ParamEnv::empty()).eq(
637                            // Lifetimes don't contain opaque types (or any types for that matter).
638                            DefineOpaqueTypes::Yes,
639                            r,
640                            ty::Region::new_placeholder(
641                                self.infcx.tcx,
642                                ty::PlaceholderRegion::new(
643                                    self.universe,
644                                    ty::BoundRegion {
645                                        var: self.next_var(),
646                                        kind: ty::BoundRegionKind::Anon,
647                                    },
648                                ),
649                            ),
650                        )
651                    else {
652                        ::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")
653                    };
654                    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);
655                }
656            }
657        }
658    }
659
660    value.visit_with(&mut PlugInferWithPlaceholder { infcx, universe, var: ty::BoundVar::ZERO });
661}
662
663fn try_prove_negated_where_clause<'tcx>(
664    root_infcx: &InferCtxt<'tcx>,
665    clause: ty::Clause<'tcx>,
666    param_env: ty::ParamEnv<'tcx>,
667) -> bool {
668    let Some(negative_predicate) = clause.as_predicate().flip_polarity(root_infcx.tcx) else {
669        return false;
670    };
671
672    // N.B. We don't need to use intercrate mode here because we're trying to prove
673    // the *existence* of a negative goal, not the non-existence of a positive goal.
674    // Without this, we over-eagerly register coherence ambiguity candidates when
675    // impl candidates do exist.
676    // FIXME(#132279): `TypingMode::non_body_analysis` is a bit questionable here as it
677    // would cause us to reveal opaque types to leak their auto traits.
678    let ref infcx = root_infcx.fork_with_typing_mode(TypingMode::non_body_analysis());
679    let ocx = ObligationCtxt::new(infcx);
680    ocx.register_obligation(Obligation::new(
681        infcx.tcx,
682        ObligationCause::dummy(),
683        param_env,
684        negative_predicate,
685    ));
686    if !ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
687        return false;
688    }
689
690    // FIXME: We could use the assumed_wf_types from both impls, I think,
691    // if that wasn't implemented just for LocalDefId, and we'd need to do
692    // the normalization ourselves since this is totally fallible...
693    let errors = ocx.resolve_regions(CRATE_DEF_ID, param_env, []);
694    if !errors.is_empty() {
695        return false;
696    }
697
698    true
699}
700
701/// Compute the `intercrate_ambiguity_causes` for the new solver using
702/// "proof trees".
703///
704/// This is a bit scuffed but seems to be good enough, at least
705/// when looking at UI tests. Given that it is only used to improve
706/// diagnostics this is good enough. We can always improve it once there
707/// are test cases where it is currently not enough.
708fn compute_intercrate_ambiguity_causes<'tcx>(
709    infcx: &InferCtxt<'tcx>,
710    obligations: &[PredicateObligation<'tcx>],
711) -> FxIndexSet<IntercrateAmbiguityCause<'tcx>> {
712    let mut causes: FxIndexSet<IntercrateAmbiguityCause<'tcx>> = Default::default();
713
714    for obligation in obligations {
715        search_ambiguity_causes(infcx, obligation.as_goal(), &mut causes);
716    }
717
718    causes
719}
720
721struct AmbiguityCausesVisitor<'a, 'tcx> {
722    cache: FxHashSet<Goal<'tcx, ty::Predicate<'tcx>>>,
723    causes: &'a mut FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
724}
725
726impl<'a, 'tcx> ProofTreeVisitor<'tcx> for AmbiguityCausesVisitor<'a, 'tcx> {
727    fn span(&self) -> Span {
728        DUMMY_SP
729    }
730
731    fn visit_goal(&mut self, goal: &InspectGoal<'_, 'tcx>) {
732        if !self.cache.insert(goal.goal()) {
733            return;
734        }
735
736        let infcx = goal.infcx();
737        for cand in goal.candidates() {
738            cand.visit_nested_in_probe(self);
739        }
740        // When searching for intercrate ambiguity causes, we only need to look
741        // at ambiguous goals, as for others the coherence unknowable candidate
742        // was irrelevant.
743        match goal.result() {
744            Ok(Certainty::Yes) | Err(NoSolution) => return,
745            Ok(Certainty::Maybe { .. }) => {}
746        }
747
748        // For bound predicates we simply call `infcx.enter_forall`
749        // and then prove the resulting predicate as a nested goal.
750        let Goal { param_env, predicate } = goal.goal();
751        let predicate_kind = goal.infcx().enter_forall_and_leak_universe(predicate.kind());
752        let trait_ref = match predicate_kind {
753            ty::PredicateKind::Clause(ty::ClauseKind::Trait(tr)) => tr.trait_ref,
754            ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj))
755                if #[allow(non_exhaustive_omitted_patterns)] match infcx.tcx.def_kind(proj.projection_term.def_id())
    {
    DefKind::AssocTy | DefKind::AssocConst { .. } => true,
    _ => false,
}matches!(
756                    infcx.tcx.def_kind(proj.projection_term.def_id()),
757                    DefKind::AssocTy | DefKind::AssocConst { .. }
758                ) =>
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}